<?php
// Fallback email service using PHP mail() function
class EmailService {
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    public function sendEmail($to_email, $subject, $html_body, $text_body = '') {
        try {
            // Log email attempt
            $email_id = $this->logEmailAttempt($to_email, $subject, $html_body);
            
            // Prepare headers for HTML email
            $headers = array(
                'MIME-Version: 1.0',
                'Content-type: text/html; charset=UTF-8',
                'From: Recruitment Portal <noreply@localhost>',
                'Reply-To: noreply@localhost',
                'X-Mailer: PHP/' . phpversion()
            );
            
            // Send email using PHP mail()
            $result = mail($to_email, $subject, $html_body, implode("\r\n", $headers));
            
            if ($result) {
                $this->logEmailSuccess($email_id);
                error_log("Fallback email sent successfully to: $to_email");
                return true;
            } else {
                $this->logEmailFailure($email_id);
                error_log("Fallback email failed to: $to_email");
                return false;
            }
            
        } catch (Exception $e) {
            if (isset($email_id)) {
                $this->logEmailFailure($email_id);
            }
            error_log("Fallback email exception to $to_email: " . $e->getMessage());
            return false;
        }
    }
    
    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) {
        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());
            }
        }
    }
    
    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'];
        
        return "
        <html>
        <body style='font-family: Arial, sans-serif; color: #333;'>
            <h2>Application Status Update</h2>
            <p><strong>Dear {$candidateName},</strong></p>
            <p>{$message}</p>
            <hr>
            <p><strong>Position:</strong> {$jobTitle}</p>
            <p><strong>Company:</strong> {$companyName}</p>
            <p><strong>Status:</strong> " . ucfirst($status) . "</p>
            <p><strong>Date:</strong> " . date('F j, Y g:i A') . "</p>
            <hr>
            <p>Best regards,<br>The Recruitment Team</p>
        </body>
        </html>";
    }
}
?>