<?php
/**
 * Email Class using PHPMailer
 * PSAU GAD Information System
 */

// Include Composer autoloader
require_once BASE_PATH . '/vendor/autoload.php';

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

class Email {
    private $mailer;
    private $db;
    
    public function __construct() {
        $this->mailer = new PHPMailer(true);
        $this->db = getDB();
        $this->configure();
    }
    
    /**
     * Configure PHPMailer
     */
    private function configure() {
        try {
            // Server settings
            $this->mailer->isSMTP();
            $this->mailer->Host = SMTP_HOST;
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = SMTP_USERNAME;
            $this->mailer->Password = SMTP_PASSWORD;
            $this->mailer->SMTPSecure = SMTP_ENCRYPTION;
            $this->mailer->Port = SMTP_PORT;
            
            // Default sender
            $this->mailer->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
            $this->mailer->isHTML(true);
        } catch (Exception $e) {
            logError("Email configuration error: " . $e->getMessage());
        }
    }
    
    /**
     * Send email
     */
    public function send($to, $subject, $body, $altBody = '') {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            $this->mailer->AltBody = $altBody ?: strip_tags($body);
            
            $result = $this->mailer->send();
            
            if ($result) {
                logError("Email sent successfully to: " . $to);
            }
            
            return $result;
        } catch (Exception $e) {
            logError("Email send error: " . $this->mailer->ErrorInfo, ['to' => $to, 'subject' => $subject]);
            return false;
        }
    }
    
    /**
     * Log email notification
     */
    private function logNotification($userId, $emailType, $subject, $body, $isSent, $errorMessage = null) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO email_notifications (user_id, email_type, subject, body, is_sent, error_message)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$userId, $emailType, $subject, $body, $isSent ? 1 : 0, $errorMessage]);
        } catch (PDOException $e) {
            logError("Failed to log email notification: " . $e->getMessage());
        }
    }
    
    /**
     * Send registration confirmation email
     */
    public function sendRegistrationConfirmation($userId, $activityTitle) {
        $user = $this->getUserEmail($userId);
        if (!$user) return false;
        
        $subject = "Registration Confirmation - " . $activityTitle;
        $body = $this->getEmailTemplate('registration_confirmation', [
            'activity_title' => $activityTitle,
            'user_name' => $user['name']
        ]);
        
        $result = $this->send($user['email'], $subject, $body);
        $this->logNotification($userId, 'registration_confirmation', $subject, $body, $result);
        
        return $result;
    }
    
    /**
     * Send approval notification
     */
    public function sendApprovalNotification($userId, $activityTitle, $preTestLink) {
        $user = $this->getUserEmail($userId);
        if (!$user) return false;
        
        $subject = "Registration Approved - " . $activityTitle;
        $body = $this->getEmailTemplate('approval', [
            'activity_title' => $activityTitle,
            'user_name' => $user['name'],
            'pre_test_link' => $preTestLink
        ]);
        
        $result = $this->send($user['email'], $subject, $body);
        $this->logNotification($userId, 'approval', $subject, $body, $result);
        
        return $result;
    }
    
    /**
     * Send QR code email
     */
    public function sendQRCode($userId, $activityTitle, $qrCodePath) {
        $user = $this->getUserEmail($userId);
        if (!$user) return false;
        
        $subject = "Your QR Code for " . $activityTitle;
        $body = $this->getEmailTemplate('qr_code', [
            'activity_title' => $activityTitle,
            'user_name' => $user['name']
        ]);
        
        // Attach QR code
        try {
            $this->mailer->addAttachment($qrCodePath);
        } catch (Exception $e) {
            logError("Failed to attach QR code: " . $e->getMessage());
        }
        
        $result = $this->send($user['email'], $subject, $body);
        $this->logNotification($userId, 'qr_code', $subject, $body, $result);
        
        return $result;
    }
    
    /**
     * Send post-test notification
     */
    public function sendPostTestNotification($userId, $activityTitle, $postTestLink) {
        $user = $this->getUserEmail($userId);
        if (!$user) return false;
        
        $subject = "Post-Test and Evaluation - " . $activityTitle;
        $body = $this->getEmailTemplate('post_test', [
            'activity_title' => $activityTitle,
            'user_name' => $user['name'],
            'post_test_link' => $postTestLink
        ]);
        
        $result = $this->send($user['email'], $subject, $body);
        $this->logNotification($userId, 'post_test', $subject, $body, $result);
        
        return $result;
    }
    
    /**
     * Send certificate notification
     */
    public function sendCertificateNotification($userId, $activityTitle, $certificateLink) {
        $user = $this->getUserEmail($userId);
        if (!$user) return false;
        
        $subject = "Certificate Available - " . $activityTitle;
        $body = $this->getEmailTemplate('certificate', [
            'activity_title' => $activityTitle,
            'user_name' => $user['name'],
            'certificate_link' => $certificateLink
        ]);
        
        $result = $this->send($user['email'], $subject, $body);
        $this->logNotification($userId, 'certificate', $subject, $body, $result);
        
        return $result;
    }
    
    /**
     * Get user email and name
     */
    private function getUserEmail($userId) {
        try {
            $stmt = $this->db->prepare("
                SELECT u.email, 
                       CONCAT(ep.first_name, ' ', ep.last_name) as name
                FROM users u
                LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
                WHERE u.user_id = ?
            ");
            $stmt->execute([$userId]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            logError("Failed to get user email: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Get email template
     */
    private function getEmailTemplate($type, $data = []) {
        $templates = [
            'registration_confirmation' => '
                <h2>Registration Confirmation</h2>
                <p>Dear {user_name},</p>
                <p>Thank you for registering for <strong>{activity_title}</strong>.</p>
                <p>Your registration is currently pending approval. You will receive another email once your registration is approved.</p>
                <p>Best regards,<br>PSAU GAD Team</p>
            ',
            'approval' => '
                <h2>Registration Approved</h2>
                <p>Dear {user_name},</p>
                <p>Your registration for <strong>{activity_title}</strong> has been approved!</p>
                <p>Please complete the pre-test by clicking the link below:</p>
                <p><a href="{pre_test_link}" style="background-color: #8b5cf6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Take Pre-Test</a></p>
                <p>Best regards,<br>PSAU GAD Team</p>
            ',
            'qr_code' => '
                <h2>Your QR Code for Attendance</h2>
                <p>Dear {user_name},</p>
                <p>Please find attached your QR code for <strong>{activity_title}</strong>.</p>
                <p>Please present this QR code at the event for attendance verification.</p>
                <p>Best regards,<br>PSAU GAD Team</p>
            ',
            'post_test' => '
                <h2>Post-Test and Evaluation</h2>
                <p>Dear {user_name},</p>
                <p>Thank you for attending <strong>{activity_title}</strong>.</p>
                <p>Please complete the post-test and evaluation by clicking the link below:</p>
                <p><a href="{post_test_link}" style="background-color: #8b5cf6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Take Post-Test</a></p>
                <p>Best regards,<br>PSAU GAD Team</p>
            ',
            'certificate' => '
                <h2>Certificate Available</h2>
                <p>Dear {user_name},</p>
                <p>Congratulations! Your certificate for <strong>{activity_title}</strong> is now available.</p>
                <p>You can download your certificate by clicking the link below:</p>
                <p><a href="{certificate_link}" style="background-color: #8b5cf6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Download Certificate</a></p>
                <p>Best regards,<br>PSAU GAD Team</p>
            '
        ];
        
        $template = $templates[$type] ?? '';
        
        // Replace placeholders
        foreach ($data as $key => $value) {
            $template = str_replace('{' . $key . '}', $value, $template);
        }
        
        return $this->wrapTemplate($template);
    }
    
    /**
     * Wrap content in email template
     */
    private function wrapTemplate($content) {
        return '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                h2 { color: #8b5cf6; }
                .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div style="text-align: center; margin-bottom: 20px;">
                    <h1 style="color: #8b5cf6;">PSAU GAD</h1>
                    <p>Gender and Development Information System</p>
                </div>
                ' . $content . '
                <div class="footer">
                    <p>This is an automated message from PSAU GAD Information System. Please do not reply to this email.</p>
                    <p>&copy; 2025 Pampanga State Agricultural University. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ';
    }
}

