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

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

class GmailEmailService {
    private $db;
    private $mailer;
    private $config;
    
    public function __construct($database) {
        $this->db = $database;
        $this->config = $this->getEmailConfig();
        $this->initializeMailer();
    }
    
    private function getEmailConfig() {
        // Gmail SMTP configuration with App Password
        return [
            'smtp_host' => 'smtp.gmail.com',
            'smtp_port' => 587,
            'smtp_username' => 'masandendyaluvane@gmail.com',
            'smtp_password' => 'kwcn czhz pzvb eico',
            'from_email' => 'masandendyaluvane@gmail.com',
            'from_name' => 'Recruitment Portal',
            'use_smtp' => true
        ];
    }
    
    private function initializeMailer() {
        $this->mailer = new PHPMailer(true);
        
        try {
            // Server settings for Gmail with proper STARTTLS
            $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'];
            
            // Enable debug output for troubleshooting
            $this->mailer->SMTPDebug = 0; // Set to 2 for verbose debugging
            
            // Gmail-specific settings to handle STARTTLS properly
            $this->mailer->SMTPAutoTLS = true;
            $this->mailer->SMTPSecure = 'tls';
            
            // SSL context options for Gmail
            $this->mailer->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                    'cafile' => null,
                ),
                'tls' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                    'cafile' => null,
                )
            );
            
            // Set default from address
            $this->mailer->setFrom($this->config['from_email'], $this->config['from_name']);
            
            // Content type
            $this->mailer->isHTML(true);
            
        } catch (Exception $e) {
            error_log("Gmail SMTP configuration failed: " . $e->getMessage());
            throw $e;
        }
    }
    
    public function sendEmail($to_email, $subject, $html_body, $text_body = '') {
        try {
            // Clear any previous recipients
            $this->mailer->clearAddresses();
            $this->mailer->clearAttachments();
            
            // Recipients
            $this->mailer->addAddress($to_email);
            
            // Content
            $this->mailer->Subject = $subject;
            $this->mailer->Body    = $html_body;
            $this->mailer->AltBody = $text_body ?: strip_tags($html_body);
            
            // Log email attempt to database
            $email_id = $this->logEmailAttempt($to_email, $subject, $html_body);
            
            // Send email
            if ($this->mailer->send()) {
                $this->logEmailSuccess($email_id);
                error_log("Gmail email sent successfully to: $to_email");
                return true;
            } else {
                $this->logEmailFailure($email_id, 'Send failed: ' . $this->mailer->ErrorInfo);
                error_log("Gmail email failed to: $to_email - " . $this->mailer->ErrorInfo);
                return false;
            }
            
        } catch (Exception $e) {
            if (isset($email_id)) {
                $this->logEmailFailure($email_id, $e->getMessage());
            }
            error_log("Gmail email exception to $to_email: " . $e->getMessage());
            
            // Try fallback method
            return $this->sendFallbackEmail($to_email, $subject, $html_body);
        }
    }
    
    private function logEmailAttempt($to_email, $subject, $message) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO email_notifications (to_email, subject, message, status) 
                VALUES (?, ?, ?, 'pending')
            ");
            $stmt->execute([$to_email, $subject, $message]);
            return $this->db->lastInsertId();
        } catch (Exception $e) {
            error_log("Failed to log email attempt: " . $e->getMessage());
            return null;
        }
    }
    
    private function logEmailSuccess($email_id) {
        if ($email_id) {
            try {
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'sent', sent_at = NOW() 
                    WHERE id = ?
                ");
                $stmt->execute([$email_id]);
            } catch (Exception $e) {
                error_log("Failed to log email success: " . $e->getMessage());
            }
        }
    }
    
    private function logEmailFailure($email_id, $error_message) {
        if ($email_id) {
            try {
                $stmt = $this->db->prepare("
                    UPDATE email_notifications 
                    SET status = 'failed' 
                    WHERE id = ?
                ");
                $stmt->execute([$email_id]);
            } catch (Exception $e) {
                error_log("Failed to log email failure: " . $e->getMessage());
            }
        }
    }
    
    private function sendFallbackEmail($to_email, $subject, $html_body) {
        try {
            // Use PHP mail() as fallback
            $headers = array(
                'MIME-Version: 1.0',
                'Content-type: text/html; charset=UTF-8',
                'From: ' . $this->config['from_name'] . ' <' . $this->config['from_email'] . '>',
                'Reply-To: ' . $this->config['from_email'],
                'X-Mailer: PHP/' . phpversion()
            );
            
            $result = mail($to_email, $subject, $html_body, implode("\r\n", $headers));
            
            if ($result) {
                error_log("Fallback email sent successfully to: $to_email");
                return true;
            } else {
                error_log("Fallback email also failed to: $to_email");
                return false;
            }
        } catch (Exception $e) {
            error_log("Fallback email exception to $to_email: " . $e->getMessage());
            return false;
        }
    }
    
    public function sendNotificationEmail($application, $message, $status) {
        $subject = $this->getNotificationSubject($status, $application['job_title']);
        $html_body = $this->buildNotificationEmailBody($application, $message, $status);
        
        return $this->sendEmail($application['email'], $subject, $html_body);
    }
    
    private function getNotificationSubject($status, $job_title) {
        $subjects = [
            'applied' => '✅ Application Received - ' . $job_title,
            'longlisted' => '📋 Application Longlisted - ' . $job_title,
            'shortlisted' => '🎉 Application Shortlisted - ' . $job_title,
            'interviewed' => '📝 Interview Scheduled - ' . $job_title,
            'hired' => '🎊 Congratulations! Job Offer - ' . $job_title,
            'rejected' => '💼 Application Update - ' . $job_title
        ];
        
        return $subjects[$status] ?? 'Application Status Update - ' . $job_title;
    }
    
    private function buildNotificationEmailBody($application, $message, $status) {
        $candidateName = $application['first_name'] . ' ' . $application['last_name'];
        $jobTitle = $application['job_title'];
        $companyName = $application['company_name'];
        
        $statusColors = [
            'applied' => '#28a745',
            'longlisted' => '#17a2b8',
            'shortlisted' => '#ffc107',
            'interviewed' => '#fd7e14',
            'hired' => '#28a745',
            'rejected' => '#6c757d'
        ];
        
        $statusColor = $statusColors[$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="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                <h1 style="color: white; margin: 0; font-size: 28px;">Recruitment Portal</h1>
                <p style="color: #f8f9fa; margin: 10px 0 0 0; font-size: 16px;">Application Status Update</p>
            </div>
            
            <div style="background: white; padding: 30px; border: 1px solid #e9ecef; border-top: none;">
                <div style="background: ' . $statusColor . '; color: white; padding: 15px; border-radius: 5px; text-align: center; margin-bottom: 25px;">
                    <h2 style="margin: 0; font-size: 24px;">Status: ' . ucfirst($status) . '</h2>
                </div>
                
                <p style="font-size: 16px; margin-bottom: 20px;"><strong>Dear ' . htmlspecialchars($candidateName) . ',</strong></p>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
                    <p style="margin: 0; font-size: 16px;">' . nl2br(htmlspecialchars($message)) . '</p>
                </div>
                
                <div style="border: 1px solid #e9ecef; padding: 20px; border-radius: 8px; margin: 25px 0;">
                    <h3 style="color: #495057; margin-top: 0;">Application Details:</h3>
                    <ul style="list-style: none; padding: 0;">
                        <li style="padding: 5px 0;"><strong>Position:</strong> ' . htmlspecialchars($jobTitle) . '</li>
                        <li style="padding: 5px 0;"><strong>Company:</strong> ' . htmlspecialchars($companyName) . '</li>
                        <li style="padding: 5px 0;"><strong>Status:</strong> ' . ucfirst($status) . '</li>
                        <li style="padding: 5px 0;"><strong>Date:</strong> ' . date('F j, Y g:i A') . '</li>
                    </ul>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="' . SITE_URL . '/candidate/dashboard.php" 
                       style="background: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">
                        View Application Dashboard
                    </a>
                </div>
                
                <p style="color: #6c757d; font-size: 14px; margin-top: 30px;">
                    Best regards,<br>
                    <strong>The Recruitment Team</strong><br>
                    ' . htmlspecialchars($companyName) . '
                </p>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; border: 1px solid #e9ecef; border-top: none;">
                <p style="color: #6c757d; font-size: 12px; margin: 0;">
                    This is an automated notification from the Recruitment Portal.<br>
                    Please do not reply directly to this email.
                </p>
            </div>
        </body>
        </html>';
    }
    
    public function sendApprovalNotificationEmail($candidate, $message, $action) {
        $subject = $this->getApprovalSubject($action, $candidate['first_name']);
        $html_body = $this->buildApprovalEmailBody($candidate, $message, $action);
        
        return $this->sendEmail($candidate['email'], $subject, $html_body);
    }
    
    private function getApprovalSubject($action, $first_name) {
        if ($action === 'approve') {
            return '🎉 Internal Account Approved - Welcome to the Recruitment Portal!';
        } else {
            return '⚠️ Internal Account Application - Update Required';
        }
    }
    
    private function buildApprovalEmailBody($candidate, $message, $action) {
        $candidateName = $candidate['first_name'] . ' ' . $candidate['last_name'];
        $statusColor = $action === 'approve' ? '#28a745' : '#ffc107';
        $statusText = $action === 'approve' ? 'Account Approved' : 'Update Required';
        
        return '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Internal Account ' . ucfirst($action) . '</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                <h1 style="color: white; margin: 0; font-size: 28px;">Recruitment Portal</h1>
                <p style="color: #f8f9fa; margin: 10px 0 0 0; font-size: 16px;">Internal Account Update</p>
            </div>
            
            <div style="background: white; padding: 30px; border: 1px solid #e9ecef; border-top: none;">
                <div style="background: ' . $statusColor . '; color: white; padding: 15px; border-radius: 5px; text-align: center; margin-bottom: 25px;">
                    <h2 style="margin: 0; font-size: 24px;">' . $statusText . '</h2>
                </div>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
                    <p style="margin: 0; font-size: 16px;">' . nl2br(htmlspecialchars($message)) . '</p>
                </div>
                
                ' . ($action === 'approve' ? '
                <div style="text-align: center; margin: 30px 0;">
                    <a href="' . SITE_URL . '/candidate/dashboard.php" 
                       style="background: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">
                        Access Your Account
                    </a>
                </div>
                ' : '
                <div style="border: 1px solid #e9ecef; padding: 20px; border-radius: 8px; margin: 25px 0; background: #fff3cd;">
                    <h4 style="color: #856404; margin-top: 0;">Next Steps:</h4>
                    <p style="color: #856404; margin: 0;">Please contact HR to resolve the issues mentioned above and resubmit your application if necessary.</p>
                </div>
                ') . '
                
                <div style="border: 1px solid #e9ecef; padding: 20px; border-radius: 8px; margin: 25px 0;">
                    <h3 style="color: #495057; margin-top: 0;">Account Details:</h3>
                    <ul style="list-style: none; padding: 0;">
                        <li style="padding: 5px 0;"><strong>Name:</strong> ' . htmlspecialchars($candidateName) . '</li>
                        <li style="padding: 5px 0;"><strong>Email:</strong> ' . htmlspecialchars($candidate['email']) . '</li>
                        <li style="padding: 5px 0;"><strong>Status:</strong> ' . ucfirst($action) . 'd</li>
                        <li style="padding: 5px 0;"><strong>Date:</strong> ' . date('F j, Y g:i A') . '</li>
                    </ul>
                </div>
                
                <p style="color: #6c757d; font-size: 14px; margin-top: 30px;">
                    Best regards,<br>
                    <strong>HR Team</strong><br>
                    Recruitment Portal
                </p>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; border: 1px solid #e9ecef; border-top: none;">
                <p style="color: #6c757d; font-size: 12px; margin: 0;">
                    This is an automated notification from the Recruitment Portal.<br>
                    For questions about your internal account, please contact HR directly.
                </p>
            </div>
        </body>
        </html>';
    }

    public function testConnection($test_email = null) {
        $test_email = $test_email ?: $this->config['smtp_username'];
        
        $subject = 'Gmail SMTP Test - Recruitment Portal';
        $body = '
        <h2>🎉 Gmail SMTP Test Successful!</h2>
        <p>This email confirms that Gmail SMTP is working correctly with your recruitment portal.</p>
        <p><strong>Configuration:</strong></p>
        <ul>
            <li>SMTP Host: ' . $this->config['smtp_host'] . '</li>
            <li>Port: ' . $this->config['smtp_port'] . '</li>
            <li>Username: ' . $this->config['smtp_username'] . '</li>
            <li>From: ' . $this->config['from_name'] . '</li>
        </ul>
        <p><em>Sent: ' . date('Y-m-d H:i:s') . '</em></p>
        ';
        
        return $this->sendEmail($test_email, $subject, $body);
    }
}
?>