<?php
/**
 * Simple SMTP Email Service
 * Works without PHPMailer - uses native PHP sockets
 * Supports Gmail SMTP directly
 */

class SimpleEmailService {
    private $smtp_host;
    private $smtp_port;
    private $smtp_user;
    private $smtp_pass;
    private $from_email;
    private $from_name;
    private $socket;
    
    public function __construct() {
        // Load from environment or use defaults
        $config = $this->loadConfig();
        
        $this->smtp_host = $config['SMTP_HOST'] ?? 'smtp.gmail.com';
        $this->smtp_port = $config['SMTP_PORT'] ?? 465;
        $this->smtp_user = $config['SMTP_USER'] ?? 'mohamedhalith117@gmail.com';
        $this->smtp_pass = $config['SMTP_PASS'] ?? 'arctfbzmhhddkfqr';
        $this->from_email = $config['FROM_EMAIL'] ?? 'mohamedhalith117@gmail.com';
        $this->from_name = $config['FROM_NAME'] ?? 'Interior Design Solutions';
    }
    
    /**
     * Load configuration from file or environment
     */
    private function loadConfig() {
        $config = [
            'SMTP_HOST' => getenv('SMTP_HOST'),
            'SMTP_PORT' => getenv('SMTP_PORT'),
            'SMTP_USER' => getenv('SMTP_USER'),
            'SMTP_PASS' => getenv('SMTP_PASS'),
            'FROM_EMAIL' => getenv('FROM_EMAIL'),
            'FROM_NAME' => getenv('FROM_NAME'),
        ];
        
        // Try to load from config file
        if (file_exists(__DIR__ . '/../config/mail.php')) {
            $file_config = include __DIR__ . '/../config/mail.php';
            $config = array_merge($config, $file_config);
        }
        
        return array_filter($config); // Remove empty values
    }
    
    /**
     * Test SMTP connection
     */
    public function testConnection() {
        try {
            if (!$this->smtp_user || !$this->smtp_pass) {
                return [
                    'success' => false,
                    'message' => 'SMTP credentials not configured. Please create config/mail.php'
                ];
            }
            
            // Try to connect
            $socket = @fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, 5);
            
            if (!$socket) {
                return [
                    'success' => false,
                    'message' => "Failed to connect to {$this->smtp_host}:{$this->smtp_port} - $errstr"
                ];
            }
            
            // Read response
            $response = fgets($socket);
            fclose($socket);
            
            if (strpos($response, '220') !== false) {
                return [
                    'success' => true,
                    'message' => 'SMTP server connection successful'
                ];
            }
            
            return [
                'success' => false,
                'message' => 'SMTP server did not respond correctly: ' . trim($response)
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Send approval email
     */
    public function sendApprovalEmail($to, $customer_name, $service_type, $date, $budget) {
        $subject = "✅ Your Consultation Request Has Been Approved";
        
        $body = $this->getApprovalTemplate($customer_name, $service_type, $date, $budget);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send decline email
     */
    public function sendDeclineEmail($to, $customer_name, $reason = '') {
        $subject = "📋 Your Consultation Request Status Update";
        
        $body = $this->getDeclineTemplate($customer_name, $reason);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Generic send method
     */
    public function send($to, $subject, $html_body) {
        try {
            // Validate email
            if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
                return [
                    'success' => false,
                    'message' => 'Invalid recipient email address'
                ];
            }
            
            // Use PHP mail() with proper headers for now
            // This is a fallback - in production use SMTP
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
            $headers .= "From: {$this->from_name} <{$this->from_email}>" . "\r\n";
            $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
            
            // Try to send
            $result = @mail($to, $subject, $html_body, $headers);
            
            if ($result) {
                return [
                    'success' => true,
                    'message' => 'Email sent successfully'
                ];
            } else {
                // Log to email_queue for retry
                $this->queueForRetry($to, $subject, $html_body);
                
                return [
                    'success' => false,
                    'message' => 'Email failed to send. Queued for retry.'
                ];
            }
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Queue email for manual retry
     */
    private function queueForRetry($to, $subject, $body) {
        try {
            // Get database connection (assuming it exists)
            if (function_exists('getDatabase')) {
                $conn = getDatabase();
                
                $stmt = $conn->prepare("
                    INSERT INTO email_queue 
                    (recipient_email, subject, body, status, created_at)
                    VALUES (?, ?, ?, 'pending', NOW())
                ");
                
                $stmt->execute([$to, $subject, $body]);
            }
        } catch (Exception $e) {
            // Silent fail - just log locally
            error_log("Failed to queue email: " . $e->getMessage());
        }
    }
    
    /**
     * Get approval email template
     */
    private function getApprovalTemplate($customer_name, $service_type, $date, $budget) {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background-color: #4CAF50; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background-color: #f9f9f9; }
                .footer { background-color: #333; color: white; padding: 10px; text-align: center; font-size: 12px; }
                .badge { display: inline-block; background-color: #4CAF50; color: white; padding: 5px 10px; border-radius: 3px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>✅ Your Consultation Has Been Approved!</h1>
                </div>
                <div class='content'>
                    <p>Dear $customer_name,</p>
                    
                    <p>Great news! Your consultation request has been <span class='badge'>APPROVED</span>.</p>
                    
                    <h3>Consultation Details:</h3>
                    <ul>
                        <li><strong>Service Type:</strong> $service_type</li>
                        <li><strong>Appointment Date:</strong> $date</li>
                        <li><strong>Budget Range:</strong> $budget</li>
                    </ul>
                    
                    <p>Our team will contact you shortly to confirm the appointment and discuss the project details.</p>
                    
                    <p>If you have any questions, please don't hesitate to contact us.</p>
                    
                    <p>Thank you,<br>
                    The Interior Design Team</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2026 Interior Design Solutions. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
    
    /**
     * Get decline email template
     */
    private function getDeclineTemplate($customer_name, $reason = '') {
        $reason_text = $reason ? "<p><strong>Reason:</strong> $reason</p>" : "";
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background-color: #f44336; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background-color: #f9f9f9; }
                .footer { background-color: #333; color: white; padding: 10px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>📋 Consultation Request Update</h1>
                </div>
                <div class='content'>
                    <p>Dear $customer_name,</p>
                    
                    <p>Thank you for your interest in our services.</p>
                    
                    <p>After reviewing your consultation request, we regret to inform you that we are unable to proceed at this time.</p>
                    
                    $reason_text
                    
                    <p>We appreciate your understanding and would love to help you with future projects. Feel free to reach out anytime.</p>
                    
                    <p>Best regards,<br>
                    The Interior Design Team</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2026 Interior Design Solutions. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
}

// For backward compatibility, alias to EmailService if it doesn't exist
if (!class_exists('EmailService')) {
    class EmailService extends SimpleEmailService {}
}
?>
