<?php
/**
 * Direct SMTP Email Service
 * Sends emails directly via SMTP connection (no libraries needed)
 * Works on Windows XAMPP without any configuration
 */

class DirectSMTPService {
    private $smtp_host = 'smtp.gmail.com';
    private $smtp_port = 465;
    private $smtp_user = 'mohamedhalith117@gmail.com';
    private $smtp_pass = 'arctfbzmhhddkfqr';
    private $from_email = 'mohamedhalith117@gmail.com';
    private $from_name = 'Interior Design Solutions';
    private $socket = null;
    
    public function __construct() {
        $this->loadConfig();
    }
    
    /**
     * Load configuration from file or environment
     */
    private function loadConfig() {
        // Check for config file first
        if (file_exists(__DIR__ . '/../config/mail.php')) {
            $config = include __DIR__ . '/../config/mail.php';
            $this->smtp_host = $config['SMTP_HOST'] ?? $this->smtp_host;
            $this->smtp_port = $config['SMTP_PORT'] ?? $this->smtp_port;
            $this->smtp_user = $config['SMTP_USER'] ?? '';
            $this->smtp_pass = $config['SMTP_PASS'] ?? '';
            $this->from_email = $config['FROM_EMAIL'] ?? $this->from_email;
            $this->from_name = $config['FROM_NAME'] ?? $this->from_name;
        }
    }
    
    /**
     * 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 with SMTP credentials.'
                ];
            }

            $transport = ((int)$this->smtp_port === 465) ? 'ssl' : 'tcp';
            $socket = @fsockopen($transport . '://' . $this->smtp_host, (int)$this->smtp_port, $errno, $errstr, 8);
            
            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 connection successful'
                ];
            }
            
            return [
                'success' => false,
                'message' => 'SMTP server error: ' . trim($response)
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Send email via SMTP
     */
    public function sendEmail($to, $subject, $body, $is_html = true) {
        try {
            if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
                return [
                    'success' => false,
                    'message' => 'Invalid email address'
                ];
            }
            
            // If no SMTP config, use fallback mail()
            if (!$this->smtp_user || !$this->smtp_pass) {
                return $this->sendViaMailFunction($to, $subject, $body, $is_html);
            }
            
            // Try to send via SMTP
            $result = $this->sendViaSMTP($to, $subject, $body, $is_html);
            
            if (!$result['success']) {
                // Fallback to mail() function
                return $this->sendViaMailFunction($to, $subject, $body, $is_html);
            }
            
            return $result;
            
        } catch (Exception $e) {
            error_log("Email send error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Email service error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Send via SMTP protocol
     */
    private function sendViaSMTP($to, $subject, $body, $is_html) {
        try {
            // Create context with SSL options
            $context = stream_context_create([
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                ]
            ]);
            
            $port = (int)$this->smtp_port;
            $useImplicitSsl = ($port === 465);

            // Connect
            $socket = @stream_socket_client(
                ($useImplicitSsl ? "ssl://" : "tcp://") . "{$this->smtp_host}:{$port}",
                $errno,
                $errstr,
                10,
                STREAM_CLIENT_CONNECT,
                $context
            );
            
            if (!$socket) {
                return ['success' => false, 'message' => 'SMTP connection failed: ' . $errstr];
            }
            
            $this->socket = $socket;
            
            // Read server greeting
            $response = $this->getResponse();
            if (strpos($response, '220') === false) {
                return ['success' => false, 'message' => 'SMTP greeting error'];
            }
            
            // EHLO
            $this->sendCommand("EHLO localhost\r\n");
            $response = $this->getResponse();
            if (strpos($response, '250') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'EHLO failed'];
            }
            
            // For port 587 (or non-465), upgrade plain TCP connection using STARTTLS.
            if (!$useImplicitSsl) {
                $this->sendCommand("STARTTLS\r\n");
                $response = $this->getResponse();
                
                if (strpos($response, '220') === false) {
                    fclose($this->socket);
                    return ['success' => false, 'message' => 'STARTTLS failed'];
                }
                
                if (!stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                    fclose($this->socket);
                    return ['success' => false, 'message' => 'TLS negotiation failed'];
                }
                
                $this->sendCommand("EHLO localhost\r\n");
                $response = $this->getResponse();
                if (strpos($response, '250') === false) {
                    fclose($this->socket);
                    return ['success' => false, 'message' => 'EHLO after STARTTLS failed'];
                }
            }
            
            // AUTH LOGIN
            $this->sendCommand("AUTH LOGIN\r\n");
            $response = $this->getResponse();
            
            if (strpos($response, '334') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'AUTH failed'];
            }
            
            // Send username (base64)
            $this->sendCommand(base64_encode($this->smtp_user) . "\r\n");
            $response = $this->getResponse();
            
            if (strpos($response, '334') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'Username rejected'];
            }
            
            // Send password (base64)
            $this->sendCommand(base64_encode($this->smtp_pass) . "\r\n");
            $response = $this->getResponse();
            
            if (strpos($response, '235') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'Authentication failed'];
            }
            
            // MAIL FROM
            $this->sendCommand("MAIL FROM: <{$this->from_email}>\r\n");
            $response = $this->getResponse();
            if (strpos($response, '250') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'MAIL FROM rejected: ' . trim($response)];
            }
            
            // RCPT TO
            $this->sendCommand("RCPT TO: <{$to}>\r\n");
            $response = $this->getResponse();
            if (strpos($response, '250') === false && strpos($response, '251') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'RCPT TO rejected: ' . trim($response)];
            }
            
            // DATA
            $this->sendCommand("DATA\r\n");
            $response = $this->getResponse();
            if (strpos($response, '354') === false) {
                fclose($this->socket);
                return ['success' => false, 'message' => 'DATA command rejected: ' . trim($response)];
            }
            
            // Build email
            $headers = "From: {$this->from_name} <{$this->from_email}>\r\n";
            $headers .= "To: {$to}\r\n";
            $headers .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
            
            if ($is_html) {
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            }
            
            $message = $headers . "\r\n" . $body;
            
            // Send message
            $this->sendCommand($message . "\r\n.\r\n");
            $response = $this->getResponse();
            
            // QUIT
            $this->sendCommand("QUIT\r\n");
            fclose($this->socket);
            
            if (strpos($response, '250') !== false) {
                return ['success' => true, 'message' => 'Email sent successfully'];
            }
            
            return ['success' => false, 'message' => 'SMTP error: ' . trim($response)];
            
        } catch (Exception $e) {
            if ($this->socket) {
                fclose($this->socket);
            }
            return ['success' => false, 'message' => 'SMTP error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Send command to SMTP server
     */
    private function sendCommand($command) {
        fwrite($this->socket, $command);
    }
    
    /**
     * Get response from SMTP server
     */
    private function getResponse() {
        $response = '';
        while ($line = fgets($this->socket, 512)) {
            $response .= $line;
            if (substr($line, 3, 1) === ' ') {
                break;
            }
        }
        return $response;
    }
    
    /**
     * Fallback to PHP mail() function
     */
    private function sendViaMailFunction($to, $subject, $body, $is_html) {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: " . ($is_html ? "text/html" : "text/plain") . "; charset=UTF-8\r\n";
        $headers .= "From: {$this->from_name} <{$this->from_email}>\r\n";
        
        $result = @mail($to, $subject, $body, $headers);
        
        if ($result) {
            error_log("✓ Email sent to {$to} via mail()");
            return ['success' => true, 'message' => 'Email sent via mail()'];
        } else {
            error_log("✗ mail() failed for {$to}");
            return ['success' => false, 'message' => 'mail() function failed'];
        }
    }
    
    /**
     * 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->sendEmail($to, $subject, $body, true);
    }
    
    /**
     * Send decline email
     */
    public function sendDeclineEmail($to, $customer_name, $reason = '') {
        $subject = "📋 Your Consultation Request Status Update";
        $body = $this->getDeclineTemplate($customer_name, $reason);
        return $this->sendEmail($to, $subject, $body, true);
    }
    
    /**
     * 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; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
                .header h1 { margin: 0; font-size: 24px; }
                .content { padding: 30px; background-color: #f9f9f9; border-left: 4px solid #4CAF50; }
                .details { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; }
                .detail-row { display: flex; padding: 10px 0; border-bottom: 1px solid #eee; }
                .detail-row:last-child { border-bottom: none; }
                .detail-label { flex: 1; font-weight: bold; color: #555; }
                .detail-value { flex: 2; color: #333; }
                .footer { background-color: #333; color: white; padding: 20px; text-align: center; font-size: 12px; border-radius: 0 0 5px 5px; }
                .cta { background-color: #4CAF50; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>✅ Your Consultation Has Been Approved!</h1>
                </div>
                <div class='content'>
                    <p>Hello $customer_name,</p>
                    
                    <p>Great news! Your consultation request has been <strong style='color: #4CAF50;'>APPROVED</strong>.</p>
                    
                    <div class='details'>
                        <div class='detail-row'>
                            <div class='detail-label'>Service Type:</div>
                            <div class='detail-value'>$service_type</div>
                        </div>
                        <div class='detail-row'>
                            <div class='detail-label'>Appointment Date:</div>
                            <div class='detail-value'>$date</div>
                        </div>
                        <div class='detail-row'>
                            <div class='detail-label'>Budget Range:</div>
                            <div class='detail-value'>$budget</div>
                        </div>
                    </div>
                    
                    <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><strong>Thank you,</strong><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 ? "<div class='details'><strong>Reason:</strong> $reason</div>" : "";
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background: linear-gradient(135deg, #f44336 0%, #da190b 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
                .header h1 { margin: 0; font-size: 24px; }
                .content { padding: 30px; background-color: #f9f9f9; border-left: 4px solid #f44336; }
                .details { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; }
                .footer { background-color: #333; color: white; padding: 20px; text-align: center; font-size: 12px; border-radius: 0 0 5px 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>📋 Consultation Request Update</h1>
                </div>
                <div class='content'>
                    <p>Hello $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><strong>Best regards,</strong><br>The Interior Design Team</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2026 Interior Design Solutions. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
}

// Alias for backward compatibility
if (!class_exists('EmailService')) {
    class EmailService extends DirectSMTPService {}
}
?>
