<?php
require_once __DIR__ . '/PHPMailer-6.8.1/src/Exception.php';
require_once __DIR__ . '/PHPMailer-6.8.1/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer-6.8.1/src/SMTP.php';

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

class EmailService {
    private $db;
    private $mailer;
    private $config;
    
    public function __construct($database) {
        $this->db = $database;
        $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' => false
            ], $config);
        }
        
        // Default configuration
        return [
            'smtp_host' => 'smtp.gmail.com',
            'smtp_port' => 587,
            'smtp_username' => '',
            'smtp_password' => '',
            'from_email' => 'noreply@localhost',
            'from_name' => SITE_NAME,
            'use_smtp' => false
        ];
    }
    
    private function initializeMailer() {
        $this->mailer = new PHPMailer(true);
        
        if ($this->config['use_smtp'] && !empty($this->config['smtp_username'])) {
            // SMTP Configuration
            $this->mailer->isSMTP();
            $this->mailer->Host = $this->config['smtp_host'];
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = $this->config['smtp_username'];
            $this->mailer->Password = $this->config['smtp_password'];
            $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $this->mailer->Port = $this->config['smtp_port'];
        } else {
            // Use PHP mail() function
            $this->mailer->isMail();
        }
        
        // Set from address
        $this->mailer->setFrom($this->config['from_email'], $this->config['from_name']);
        $this->mailer->isHTML(true);
    }
    
    public function sendEmail($to_email, $subject, $html_body, $text_body = '') {
        try {
            // Log email attempt
            $stmt = $this->db->prepare("
                INSERT INTO email_notifications (to_email, subject, message) 
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$to_email, $subject, $html_body]);
            $email_id = $this->db->lastInsertId();
            
            // Configure PHPMailer
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to_email);
            $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);
            }
            
            // Send email
            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]);
                return true;
            } else {
                throw new Exception('Mailer error: ' . $this->mailer->ErrorInfo);
            }
            
        } catch (Exception $e) {
            // Log error
            error_log("Email sending failed: " . $e->getMessage());
            
            if (isset($email_id)) {
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'failed', error_message = ? 
                    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";
            case 'interviewed':
                return "Interview Update - $job_title";
            case 'hired':
                return "Congratulations! You've Been Hired - $job_title";
            case 'rejected':
                return "Application Update - $job_title";
            default:
                return "Application Status Update - $job_title";
        }
    }
    
    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</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;'>" . SITE_NAME . "</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;'>
                            <i style='color: #007bff;'>💡</i> 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 " . SITE_NAME . ".
                    </p>
                    <p style='margin: 0; color: #6c757d; font-size: 12px;'>
                        Please do not reply to this email. For support, visit our website.
                    </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 = "Email Test - " . SITE_NAME;
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;'>
            <h2 style='color: #007bff;'>Email Test Successful!</h2>
            <p>This is a test email from " . SITE_NAME . " notification system.</p>
            <p>If you receive this email, the email functionality is working correctly.</p>
            <p><strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "</p>
        </div>";
        
        return $this->sendEmail($test_email, $subject, $body);
    }
}
?>