<?php
// Load Composer autoloader
require_once __DIR__ . '/../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class EmailServiceSMTP {
    private $db;
    private $mailer;
    private $config;
    private $debug_enabled;
    
    public function __construct($database, $debug = false) {
        $this->db = $database;
        $this->debug_enabled = $debug;
        $this->config = $this->getEmailConfig();
        $this->initializeMailer();
    }
    
    private function getEmailConfig() {
        $config_file = __DIR__ . '/../config/email_config.php';
        
        if (file_exists($config_file)) {
            $config = include $config_file;
            return array_merge([
                'from_name' => SITE_NAME,
                'use_smtp' => true,
                'smtp_debug' => 0
            ], $config);
        }
        
        // Fallback configuration for cPanel
        return [
            'smtp_host' => 'mail.sanpcref.co.za',
            'smtp_port' => 587,
            'smtp_username' => 'recruitment@sanpcref.co.za',
            'smtp_password' => 'P@$$word@2025',
            'smtp_secure' => 'tls',
            'from_email' => 'recruitment@sanpcref.co.za',
            'from_name' => 'SANPC Recruitment Portal',
            'use_smtp' => true,
            'smtp_auth' => true,
            'smtp_debug' => 0
        ];
    }
    
    private function initializeMailer() {
        $this->mailer = new PHPMailer(true);
        
        try {
            // Server settings
            $this->mailer->isSMTP();
            $this->mailer->Host = $this->config['smtp_host'];
            $this->mailer->SMTPAuth = $this->config['smtp_auth'] ?? true;
            $this->mailer->Username = $this->config['smtp_username'];
            $this->mailer->Password = $this->config['smtp_password'];
            
            // Encryption settings
            $smtp_secure = $this->config['smtp_secure'] ?? 'tls';
            if ($smtp_secure === 'tls') {
                $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } elseif ($smtp_secure === 'ssl') {
                $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            }
            
            $this->mailer->Port = $this->config['smtp_port'];
            
            // Additional settings for cPanel compatibility
            $this->mailer->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
            
            // Debug settings
            if ($this->debug_enabled || ($this->config['smtp_debug'] ?? 0) > 0) {
                $this->mailer->SMTPDebug = SMTP::DEBUG_SERVER;
                $this->mailer->Debugoutput = function($str, $level) {
                    error_log("SMTP Debug Level $level: $str");
                };
            }
            
            // Timeout settings
            $this->mailer->Timeout = $this->config['timeout'] ?? 30;
            $this->mailer->SMTPKeepAlive = $this->config['smtp_keepalive'] ?? false;
            
            // Set from address
            $this->mailer->setFrom(
                $this->config['from_email'], 
                $this->config['from_name']
            );
            
            // Set reply-to if configured
            if (isset($this->config['reply_to_email'])) {
                $this->mailer->addReplyTo(
                    $this->config['reply_to_email'],
                    $this->config['reply_to_name'] ?? $this->config['from_name']
                );
            }
            
            // Email format
            $this->mailer->isHTML(true);
            $this->mailer->CharSet = $this->config['charset'] ?? 'UTF-8';
            $this->mailer->WordWrap = $this->config['word_wrap'] ?? 50;
            
            // Additional headers
            if (isset($this->config['additional_headers'])) {
                foreach ($this->config['additional_headers'] as $name => $value) {
                    $this->mailer->addCustomHeader($name, $value);
                }
            }
            
        } catch (Exception $e) {
            error_log("Failed to initialize SMTP mailer: " . $e->getMessage());
            throw $e;
        }
    }
    
    public function sendEmail($to_email, $subject, $html_body, $text_body = '', $attachments = []) {
        try {
            // Log email attempt
            $stmt = $this->db->prepare("
                INSERT INTO email_notifications (to_email, subject, message, status) 
                VALUES (?, ?, ?, 'pending')
            ");
            $stmt->execute([$to_email, $subject, $html_body]);
            $email_id = $this->db->lastInsertId();
            
            // Clear any previous recipients
            $this->mailer->clearAddresses();
            $this->mailer->clearAttachments();
            
            // Set recipient
            $this->mailer->addAddress($to_email);
            
            // Set content
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $html_body;
            
            if (!empty($text_body)) {
                $this->mailer->AltBody = $text_body;
            } else {
                $this->mailer->AltBody = strip_tags($html_body);
            }
            
            // Add attachments if any
            foreach ($attachments as $attachment) {
                if (is_array($attachment)) {
                    $this->mailer->addAttachment(
                        $attachment['path'],
                        $attachment['name'] ?? basename($attachment['path'])
                    );
                } else {
                    $this->mailer->addAttachment($attachment);
                }
            }
            
            // Attempt to send
            if ($this->mailer->send()) {
                // Mark as sent
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'sent', sent_at = NOW() 
                    WHERE id = ?
                ");
                $stmt->execute([$email_id]);
                
                if ($this->debug_enabled) {
                    error_log("Email sent successfully to: $to_email");
                }
                
                return true;
            } else {
                throw new Exception('Email could not be sent: ' . $this->mailer->ErrorInfo);
            }
            
        } catch (Exception $e) {
            // Log error
            $error_message = $e->getMessage();
            error_log("Email sending failed to $to_email: $error_message");
            
            if (isset($email_id)) {
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'failed', error_message = ? 
                    WHERE id = ?
                ");
                $stmt->execute([$error_message, $email_id]);
            }
            
            // Try alternative SMTP settings if available
            if (isset($this->config['smtp_host_alt']) && !$this->hasTriedAlternative()) {
                if ($this->debug_enabled) {
                    error_log("Trying alternative SMTP settings...");
                }
                return $this->sendEmailWithAlternativeSettings($to_email, $subject, $html_body, $text_body, $attachments, $email_id);
            }
            
            return false;
        }
    }
    
    private $alternative_tried = false;
    
    private function hasTriedAlternative() {
        return $this->alternative_tried;
    }
    
    private function sendEmailWithAlternativeSettings($to_email, $subject, $html_body, $text_body, $attachments, $email_id) {
        $this->alternative_tried = true;
        
        try {
            // Reconfigure with alternative settings
            $this->mailer->Host = $this->config['smtp_host_alt'];
            $this->mailer->Port = $this->config['smtp_port_alt'] ?? 465;
            
            if (isset($this->config['smtp_secure_alt'])) {
                if ($this->config['smtp_secure_alt'] === 'ssl') {
                    $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                } else {
                    $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                }
            }
            
            if ($this->mailer->send()) {
                // Mark as sent with alternative
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'sent', sent_at = NOW(), error_message = CONCAT(COALESCE(error_message, ''), ' [Sent via alternative SMTP]')
                    WHERE id = ?
                ");
                $stmt->execute([$email_id]);
                
                if ($this->debug_enabled) {
                    error_log("Email sent successfully via alternative SMTP to: $to_email");
                }
                
                return true;
            }
            
            return false;
            
        } catch (Exception $e) {
            error_log("Alternative SMTP also failed: " . $e->getMessage());
            
            $stmt = $this->db->prepare("
                UPDATE email_notifications 
                SET error_message = CONCAT(COALESCE(error_message, ''), ' [Alt SMTP: ', ?, ']')
                WHERE id = ?
            ");
            $stmt->execute([$e->getMessage(), $email_id]);
            
            return false;
        }
    }
    
    public function sendNotificationEmail($application, $message, $status) {
        $subject = $this->getEmailSubject($status, $application['job_title'], $application['company_name']);
        $html_body = $this->generateEmailHTML($application, $message, $status);
        
        return $this->sendEmail($application['email'], $subject, $html_body);
    }
    
    private function getEmailSubject($status, $job_title, $company_name) {
        switch ($status) {
            case 'shortlisted':
                return "Great News! You've Been Shortlisted - $job_title at SANPC";
            case 'interviewed':
                return "Interview Update - $job_title at SANPC";
            case 'hired':
                return "Congratulations! You've Been Hired - $job_title at SANPC";
            case 'rejected':
                return "Application Update - $job_title at SANPC";
            default:
                return "Application Status Update - $job_title at SANPC";
        }
    }
    
    private function generateEmailHTML($application, $message, $status) {
        $status_colors = [
            'shortlisted' => '#28a745',
            'interviewed' => '#17a2b8',
            'hired' => '#28a745',
            'rejected' => '#dc3545',
            'applied' => '#007bff'
        ];
        
        $color = $status_colors[$status] ?? '#007bff';
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Application Status Update - SANPC</title>
        </head>
        <body style='margin: 0; padding: 0; background-color: #f8f9fa; font-family: Arial, sans-serif;'>
            <div style='max-width: 600px; margin: 0 auto; background-color: #ffffff;'>
                <!-- Header -->
                <div style='background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: white; padding: 30px; text-align: center;'>
                    <h1 style='margin: 0; font-size: 28px; font-weight: bold;'>SANPC Recruitment Portal</h1>
                    <p style='margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;'>Application Status Update</p>
                </div>
                
                <!-- Content -->
                <div style='padding: 40px 30px;'>
                    <!-- Job Info -->
                    <div style='background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid $color;'>
                        <h2 style='margin: 0 0 5px 0; color: #333; font-size: 22px;'>" . htmlspecialchars($application['job_title']) . "</h2>
                        <p style='margin: 0; color: #666; font-size: 16px;'>" . htmlspecialchars($application['company_name']) . "</p>
                    </div>
                    
                    <!-- Message -->
                    <div style='margin-bottom: 30px;'>
                        <p style='color: #333; font-size: 16px; line-height: 1.6; margin-bottom: 15px;'>
                            Dear " . htmlspecialchars($application['first_name']) . ",
                        </p>
                        <p style='color: #333; font-size: 16px; line-height: 1.6;'>
                            " . htmlspecialchars($message) . "
                        </p>
                    </div>
                    
                    <!-- Status Badge -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <span style='background-color: $color; color: white; padding: 12px 24px; border-radius: 25px; font-size: 16px; font-weight: bold; text-transform: uppercase;'>
                            " . ucfirst($status) . "
                        </span>
                    </div>
                    
                    <!-- Call to Action -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . SITE_URL . "/candidate/applications.php' 
                           style='background-color: #007bff; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-size: 16px; font-weight: bold;'>
                            View My Applications
                        </a>
                    </div>
                    
                    <!-- Tips Section -->
                    <div style='background-color: #e9ecef; padding: 20px; border-radius: 8px; margin-top: 30px;'>
                        <h3 style='margin: 0 0 15px 0; color: #495057; font-size: 18px;'>
                            💡 What's Next?
                        </h3>
                        " . $this->getStatusAdvice($status) . "
                    </div>
                </div>
                
                <!-- Footer -->
                <div style='background-color: #f8f9fa; padding: 30px; text-align: center; border-top: 1px solid #e9ecef;'>
                    <p style='margin: 0 0 10px 0; color: #6c757d; font-size: 14px;'>
                        This is an automated message from SANPC Recruitment Portal.
                    </p>
                    <p style='margin: 0; color: #6c757d; font-size: 12px;'>
                        Please do not reply to this email. For support, contact recruitment@sanpcref.co.za
                    </p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    private function getStatusAdvice($status) {
        switch ($status) {
            case 'shortlisted':
                return "<p style='margin: 0; color: #495057; line-height: 1.6;'>You've made it to the next round! The hiring team will be contacting you soon for the next steps. Keep an eye on your email and phone.</p>";
            case 'interviewed':
                return "<p style='margin: 0; color: #495057; line-height: 1.6;'>Thank you for taking the time to interview with us. We'll be making our decision soon and will notify you of the outcome.</p>";
            case 'hired':
                return "<p style='margin: 0; color: #495057; line-height: 1.6;'>Congratulations! The company will be contacting you directly with next steps, including onboarding information and start date details.</p>";
            case 'rejected':
                return "<p style='margin: 0; color: #495057; line-height: 1.6;'>Don't give up! Keep applying to other positions that match your skills. Consider this valuable experience for future applications.</p>";
            default:
                return "<p style='margin: 0; color: #495057; line-height: 1.6;'>Stay tuned for updates on your application. We'll notify you of any changes to your status.</p>";
        }
    }
    
    public function testEmail($test_email) {
        $subject = "SMTP Email Test - SANPC Recruitment Portal";
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;'>
            <h2 style='color: #007bff;'>SMTP Email Test Successful!</h2>
            <p>This is a test email from SANPC Recruitment Portal using production SMTP settings.</p>
            <ul>
                <li><strong>SMTP Host:</strong> {$this->config['smtp_host']}</li>
                <li><strong>SMTP Port:</strong> {$this->config['smtp_port']}</li>
                <li><strong>Encryption:</strong> {$this->config['smtp_secure']}</li>
                <li><strong>From Email:</strong> {$this->config['from_email']}</li>
            </ul>
            <p><strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "</p>
            <p>If you receive this email, the SMTP configuration is working correctly!</p>
        </div>";
        
        return $this->sendEmail($test_email, $subject, $body);
    }
    
    public function getLastError() {
        return $this->mailer->ErrorInfo;
    }
    
    public function enableDebug() {
        $this->debug_enabled = true;
        $this->mailer->SMTPDebug = SMTP::DEBUG_SERVER;
    }
    
    public function disableDebug() {
        $this->debug_enabled = false;
        $this->mailer->SMTPDebug = SMTP::DEBUG_OFF;
    }
}
?>