<?php
require_once __DIR__ . '/email_service_smtp.php';

class NotificationSystemSMTP {
    private $db;
    private $emailService;
    
    public function __construct($database, $debug_email = false) {
        $this->db = $database;
        $this->emailService = new EmailServiceSMTP($database, $debug_email);
    }
    
    /**
     * Create an in-app notification
     */
    public function createNotification($user_type, $user_id, $title, $message, $type = 'info', $related_type = 'general', $related_id = null) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO notifications (user_type, user_id, title, message, type, related_type, related_id) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            return $stmt->execute([$user_type, $user_id, $title, $message, $type, $related_type, $related_id]);
        } catch (PDOException $e) {
            error_log("Error creating notification: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send email notification using SMTP EmailService
     */
    public function sendEmailNotification($to_email, $subject, $message, $attachments = []) {
        try {
            return $this->emailService->sendEmail($to_email, $subject, $message, '', $attachments);
        } catch (Exception $e) {
            error_log("Error sending email notification: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Notify candidate about application status change
     */
    public function notifyApplicationStatusChange($application_id, $old_status, $new_status) {
        try {
            // Get application details
            $stmt = $this->db->prepare("
                SELECT ja.*, c.email, c.first_name, c.last_name, j.title as job_title, comp.name as company_name
                FROM job_applications ja
                JOIN candidates c ON ja.candidate_id = c.id
                JOIN jobs j ON ja.job_id = j.id
                JOIN companies comp ON j.company_id = comp.id
                WHERE ja.id = ?
            ");
            $stmt->execute([$application_id]);
            $application = $stmt->fetch();
            
            if (!$application) {
                return false;
            }
            
            $status_messages = $this->getStatusMessages($new_status);
            $title = $status_messages['title'];
            $message = $status_messages['message'];
            $type = $status_messages['type'];
            
            // Replace placeholders in messages
            $title = str_replace(['{job_title}', '{company_name}'], [$application['job_title'], $application['company_name']], $title);
            $message = str_replace(['{candidate_name}', '{job_title}', '{company_name}', '{status}'], 
                                 [$application['first_name'], $application['job_title'], $application['company_name'], ucfirst($new_status)], 
                                 $message);
            
            // Create in-app notification
            $this->createNotification('candidate', $application['candidate_id'], $title, $message, $type, 'application', $application_id);
            
            // Send email notification using SMTP EmailService
            $email_sent = $this->emailService->sendNotificationEmail($application, $message, $new_status);
            
            if ($email_sent) {
                error_log("Application status email sent successfully to: " . $application['email']);
            } else {
                error_log("Failed to send application status email to: " . $application['email'] . " - " . $this->emailService->getLastError());
            }
            
            return true;
        } catch (Exception $e) {
            error_log("Error notifying application status change: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Notify internal candidate about approval/rejection
     */
    public function notifyInternalCandidateApproval($candidate_id, $status, $rejection_reason = '') {
        try {
            // Get candidate and company details
            $stmt = $this->db->prepare("
                SELECT c.*, comp.name as company_name
                FROM candidates c
                JOIN companies comp ON c.company_id = comp.id
                WHERE c.id = ? AND c.candidate_type = 'internal'
            ");
            $stmt->execute([$candidate_id]);
            $candidate = $stmt->fetch();
            
            if (!$candidate) {
                return false;
            }
            
            $approval_messages = $this->getInternalCandidateMessages($status, $rejection_reason);
            $title = $approval_messages['title'];
            $message = $approval_messages['message'];
            $email_message = $approval_messages['email_message'];
            $type = $approval_messages['type'];
            
            // Replace placeholders in messages
            $title = str_replace(['{company_name}'], [$candidate['company_name']], $title);
            $message = str_replace(['{candidate_name}', '{company_name}', '{rejection_reason}'], 
                                 [$candidate['first_name'], $candidate['company_name'], $rejection_reason], 
                                 $message);
            $email_message = str_replace(['{candidate_name}', '{company_name}', '{rejection_reason}'], 
                                       [$candidate['first_name'], $candidate['company_name'], $rejection_reason], 
                                       $email_message);
            
            // Create in-app notification
            $this->createNotification('candidate', $candidate_id, $title, $message, $type, 'internal_approval', $candidate_id);
            
            // Send email notification
            $subject = $title;
            $html_body = $this->generateInternalCandidateEmailHTML($candidate, $email_message, $status);
            
            $email_sent = $this->emailService->sendEmail($candidate['email'], $subject, $html_body);
            
            if ($email_sent) {
                error_log("Internal candidate " . $status . " email sent successfully to: " . $candidate['email']);
            } else {
                error_log("Failed to send internal candidate email to: " . $candidate['email'] . " - " . $this->emailService->getLastError());
            }
            
            return true;
        } catch (Exception $e) {
            error_log("Error notifying internal candidate approval: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get status-specific messages
     */
    private function getStatusMessages($status) {
        $messages = [
            'applied' => [
                'title' => 'Application Received - {job_title}',
                'message' => 'Your application for {job_title} at {company_name} has been received and is under review.',
                'type' => 'info'
            ],
            'longlisted' => [
                'title' => 'Application Longlisted - {job_title}',
                'message' => 'Good news! Your application for {job_title} at {company_name} has been longlisted for further review.',
                'type' => 'info'
            ],
            'shortlisted' => [
                'title' => 'Great News! You\'ve Been Shortlisted - {job_title}',
                'message' => 'Congratulations! Your application for {job_title} at {company_name} has been shortlisted. The hiring team will be in touch soon.',
                'type' => 'success'
            ],
            'interviewed' => [
                'title' => 'Interview Completed - {job_title}',
                'message' => 'Your interview for {job_title} at {company_name} has been completed. We\'ll notify you of the next steps soon.',
                'type' => 'info'
            ],
            'hired' => [
                'title' => 'Congratulations! You\'ve Been Hired - {job_title}',
                'message' => 'Excellent news! You have been selected for the {job_title} position at {company_name}. The company will contact you with next steps.',
                'type' => 'success'
            ],
            'rejected' => [
                'title' => 'Application Update - {job_title}',
                'message' => 'Thank you for your interest in the {job_title} position at {company_name}. While we were impressed with your qualifications, we have decided to move forward with other candidates. We encourage you to apply for future opportunities.',
                'type' => 'warning'
            ]
        ];
        
        return $messages[$status] ?? [
            'title' => 'Application Status Update - {job_title}',
            'message' => 'Your application status for {job_title} at {company_name} has been updated to {status}.',
            'type' => 'info'
        ];
    }
    
    /**
     * Get internal candidate approval/rejection messages
     */
    private function getInternalCandidateMessages($status, $rejection_reason = '') {
        $messages = [
            'approved' => [
                'title' => 'Internal Transfer Application Approved - SANPC',
                'message' => 'Great news! Your internal transfer application at SANPC has been approved. You can now access your candidate portal and apply for internal positions.',
                'email_message' => 'Congratulations! Your internal transfer application has been approved by the HR department. You can now log into the recruitment portal using your credentials and start applying for internal positions within SANPC.',
                'type' => 'success'
            ],
            'rejected' => [
                'title' => 'Internal Transfer Application - SANPC',
                'message' => 'Your internal transfer application at SANPC has been reviewed. Please contact HR for more information.',
                'email_message' => 'Thank you for your interest in internal opportunities at SANPC. After careful review, we are unable to approve your internal transfer application at this time.' . 
                                ($rejection_reason ? ' Reason: {rejection_reason}' : '') . 
                                ' Please feel free to discuss this with your HR representative for more information about future opportunities.',
                'type' => 'warning'
            ]
        ];
        
        return $messages[$status] ?? [
            'title' => 'Internal Transfer Application Update - SANPC',
            'message' => 'Your internal transfer application status has been updated.',
            'email_message' => 'Your internal transfer application status has been updated. Please contact HR for more details.',
            'type' => 'info'
        ];
    }
    
    /**
     * Generate HTML email template for internal candidate notifications
     */
    private function generateInternalCandidateEmailHTML($candidate, $message, $status) {
        $status_colors = [
            'approved' => '#28a745',
            'rejected' => '#dc3545'
        ];
        
        $color = $status_colors[$status] ?? '#007bff';
        $status_icon = $status === 'approved' ? '✅' : '❌';
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Internal Transfer Application 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;'>Internal Transfer Application Update</p>
                </div>
                
                <!-- Content -->
                <div style='padding: 40px 30px;'>
                    <!-- Status Header -->
                    <div style='text-align: center; margin-bottom: 30px;'>
                        <div style='font-size: 48px; margin-bottom: 15px;'>$status_icon</div>
                        <h2 style='color: $color; margin: 0; font-size: 24px; text-transform: capitalize;'>Application " . ucfirst($status) . "</h2>
                    </div>
                    
                    <!-- Company Info -->
                    <div style='background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid $color;'>
                        <h3 style='margin: 0 0 5px 0; color: #333; font-size: 20px;'>Internal Transfer Request</h3>
                        <p style='margin: 0; color: #666; font-size: 16px;'>" . htmlspecialchars($candidate['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($candidate['first_name']) . ",
                        </p>
                        <p style='color: #333; font-size: 16px; line-height: 1.6;'>
                            " . htmlspecialchars($message) . "
                        </p>
                    </div>
                    
                    <!-- Call to Action -->
                    " . ($status === 'approved' ? "
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . SITE_URL . "/auth/login.php' 
                           style='background-color: #28a745; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-size: 16px; font-weight: bold;'>
                            Login to Your Account
                        </a>
                    </div>
                    
                    <!-- Next Steps -->
                    <div style='background-color: #d4edda; padding: 20px; border-radius: 8px; margin-top: 30px; border-left: 4px solid #28a745;'>
                        <h3 style='margin: 0 0 15px 0; color: #155724; font-size: 18px;'>
                            🎉 What's Next?
                        </h3>
                        <ul style='margin: 0; padding-left: 20px; color: #155724; line-height: 1.6;'>
                            <li>Log into the recruitment portal using your existing credentials</li>
                            <li>Browse internal job opportunities</li>
                            <li>Apply for positions that match your skills and interests</li>
                            <li>Update your profile with current information</li>
                        </ul>
                    </div>
                    " : "
                    <div style='background-color: #f8d7da; padding: 20px; border-radius: 8px; margin-top: 30px; border-left: 4px solid #dc3545;'>
                        <h3 style='margin: 0 0 15px 0; color: #721c24; font-size: 18px;'>
                            📞 Need More Information?
                        </h3>
                        <p style='margin: 0; color: #721c24; line-height: 1.6;'>
                            Please contact your HR representative at recruitment@sanpcref.co.za to discuss this decision and learn about future opportunities within SANPC.
                        </p>
                    </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>";
    }
    
    /**
     * Get notifications for a user
     */
    public function getUserNotifications($user_type, $user_id, $limit = 10, $unread_only = false) {
        try {
            $sql = "
                SELECT * FROM notifications 
                WHERE user_type = ? AND user_id = ?
            ";
            $params = [$user_type, $user_id];
            
            if ($unread_only) {
                $sql .= " AND is_read = FALSE";
            }
            
            $sql .= " ORDER BY created_at DESC LIMIT ?";
            $params[] = $limit;
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            error_log("Error getting notifications: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Mark notification as read
     */
    public function markAsRead($notification_id, $user_type, $user_id) {
        try {
            $stmt = $this->db->prepare("
                UPDATE notifications 
                SET is_read = TRUE 
                WHERE id = ? AND user_type = ? AND user_id = ?
            ");
            return $stmt->execute([$notification_id, $user_type, $user_id]);
        } catch (PDOException $e) {
            error_log("Error marking notification as read: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get unread notification count
     */
    public function getUnreadCount($user_type, $user_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT COUNT(*) as count 
                FROM notifications 
                WHERE user_type = ? AND user_id = ? AND is_read = FALSE
            ");
            $stmt->execute([$user_type, $user_id]);
            $result = $stmt->fetch();
            return (int)$result['count'];
        } catch (PDOException $e) {
            error_log("Error getting unread count: " . $e->getMessage());
            return 0;
        }
    }
    
    /**
     * Test email functionality
     */
    public function testEmail($test_email) {
        return $this->emailService->testEmail($test_email);
    }
    
    /**
     * Enable email debug mode
     */
    public function enableEmailDebug() {
        $this->emailService->enableDebug();
    }
    
    /**
     * Disable email debug mode
     */
    public function disableEmailDebug() {
        $this->emailService->disableDebug();
    }
    
    /**
     * Notify candidates about new job posting in their interested category
     */
    public function notifyNewJobPosting($job_id) {
        try {
            // Get job details
            $stmt = $this->db->prepare("
                SELECT j.*, c.name as company_name, cat.name as category_name
                FROM jobs j
                JOIN companies c ON j.company_id = c.id
                LEFT JOIN job_categories cat ON j.category_id = cat.id
                WHERE j.id = ?
            ");
            $stmt->execute([$job_id]);
            $job = $stmt->fetch();
            
            if (!$job) {
                return false;
            }
            
            // Get candidates who have previously applied for jobs in this category
            $interested_candidates = $this->getCandidatesForCategory($job['category_id'], $job['job_type']);
            
            if (empty($interested_candidates)) {
                error_log("No interested candidates found for job ID: $job_id, category: " . $job['category_id']);
                return true; // Not an error, just no candidates to notify
            }
            
            $notification_count = 0;
            $email_count = 0;
            
            foreach ($interested_candidates as $candidate) {
                // Create in-app notification
                $title = "New Job Opportunity: {$job['title']} at {$job['company_name']}";
                $message = "A new {$job['category_name']} position has been posted that might interest you based on your previous applications.";
                
                $notification_created = $this->createNotification(
                    'candidate', 
                    $candidate['id'], 
                    $title, 
                    $message, 
                    'info', 
                    'new_job', 
                    $job_id
                );
                
                if ($notification_created) {
                    $notification_count++;
                }
                
                // Send email notification
                $email_sent = $this->sendNewJobEmail($candidate, $job);
                if ($email_sent) {
                    $email_count++;
                }
            }
            
            error_log("New job notifications sent - Job ID: $job_id, Notifications: $notification_count, Emails: $email_count");
            return true;
            
        } catch (Exception $e) {
            error_log("Error notifying candidates about new job posting: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get candidates who have previously applied for jobs in the same category
     */
    private function getCandidatesForCategory($category_id, $job_type) {
        try {
            // Base query to find candidates who applied for jobs in this category
            $sql = "
                SELECT DISTINCT c.id, c.first_name, c.last_name, c.email, c.candidate_type
                FROM candidates c
                INNER JOIN job_applications ja ON c.id = ja.candidate_id
                INNER JOIN jobs j ON ja.job_id = j.id
                WHERE j.category_id = ? 
                AND c.approval_status = 'approved'
            ";
            $params = [$category_id];
            
            // Add visibility conditions based on job type
            if ($job_type === 'internal') {
                $sql .= " AND c.candidate_type = 'internal' AND c.employment_status = 'active'";
            } elseif ($job_type === 'external') {
                $sql .= " AND c.candidate_type = 'external'";
            } else {
                // 'both' - include all approved candidates, but check employment status for internal
                $sql .= " AND ((c.candidate_type = 'external') OR (c.candidate_type = 'internal' AND c.employment_status = 'active'))";
            }
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll();
            
        } catch (PDOException $e) {
            error_log("Error getting candidates for category: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Send email notification about new job posting
     */
    private function sendNewJobEmail($candidate, $job) {
        try {
            $subject = "New Job Opportunity: {$job['title']} - " . SITE_NAME;
            $html_body = $this->generateNewJobEmailHTML($candidate, $job);
            
            $email_sent = $this->emailService->sendEmail($candidate['email'], $subject, $html_body);
            
            if ($email_sent) {
                error_log("New job email sent successfully to: " . $candidate['email'] . " for job: " . $job['title']);
            } else {
                error_log("Failed to send new job email to: " . $candidate['email'] . " - " . $this->emailService->getLastError());
            }
            
            return $email_sent;
            
        } catch (Exception $e) {
            error_log("Error sending new job email: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Generate HTML email template for new job notifications
     */
    private function generateNewJobEmailHTML($candidate, $job) {
        $job_type_badge = '';
        if ($job['job_type'] === 'internal') {
            $job_type_badge = '<span style="background-color: #ffc107; color: #212529; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600;">Internal Only</span>';
        } elseif ($job['job_type'] === 'external') {
            $job_type_badge = '<span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600;">External Only</span>';
        }
        
        $salary_info = '';
        if ($job['salary_min'] || $job['salary_max']) {
            $salary_info = '<p style="margin: 10px 0; color: #28a745; font-size: 16px; font-weight: 600;">';
            if ($job['salary_min'] && $job['salary_max']) {
                $salary_info .= '💰 R' . number_format($job['salary_min']) . ' - R' . number_format($job['salary_max']) . ' TCTC';
            } elseif ($job['salary_min']) {
                $salary_info .= '💰 From R' . number_format($job['salary_min']) . ' TCTC';
            } else {
                $salary_info .= '💰 Up to R' . number_format($job['salary_max']) . ' TCTC';
            }
            $salary_info .= '</p>';
        }
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>New Job Opportunity - " . SITE_NAME . "</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;'>New Job Opportunity</p>
                </div>
                
                <!-- Content -->
                <div style='padding: 40px 30px;'>
                    <!-- Greeting -->
                    <div style='margin-bottom: 30px;'>
                        <h2 style='color: #333; margin: 0 0 15px 0; font-size: 24px;'>🎯 New Job Match Found!</h2>
                        <p style='color: #333; font-size: 16px; line-height: 1.6; margin: 0;'>
                            Hi " . htmlspecialchars($candidate['first_name']) . ",
                        </p>
                        <p style='color: #333; font-size: 16px; line-height: 1.6; margin: 15px 0 0 0;'>
                            Based on your previous applications, we found a new " . htmlspecialchars($job['category_name']) . " opportunity that might interest you:
                        </p>
                    </div>
                    
                    <!-- Job Card -->
                    <div style='background-color: #f8f9fa; padding: 25px; border-radius: 12px; margin: 30px 0; border-left: 4px solid #007bff; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>
                        <div style='margin-bottom: 15px;'>
                            <h3 style='margin: 0; color: #007bff; font-size: 22px; font-weight: bold;'>" . htmlspecialchars($job['title']) . "</h3>
                            <p style='margin: 5px 0 0 0; color: #6c757d; font-size: 16px; font-weight: 600;'>" . htmlspecialchars($job['company_name']) . "</p>
                        </div>
                        
                        <div style='margin: 15px 0;'>
                            <p style='margin: 5px 0; color: #495057;'><strong>📍 Location:</strong> " . htmlspecialchars($job['location']) . "</p>
                            <p style='margin: 5px 0; color: #495057;'><strong>💼 Type:</strong> " . ucfirst(str_replace('-', ' ', $job['employment_type'])) . "</p>
                            <p style='margin: 5px 0; color: #495057;'><strong>🎓 Level:</strong> " . ucfirst($job['experience_level']) . " Level</p>
                            <p style='margin: 5px 0; color: #495057;'><strong>🏢 Work Style:</strong> " . ucfirst($job['work_location_type']) . "</p>
                            " . ($job['category_name'] ? "<p style='margin: 5px 0; color: #495057;'><strong>🏷️ Category:</strong> " . htmlspecialchars($job['category_name']) . "</p>" : "") . "
                        </div>
                        
                        " . ($job_type_badge ? "<div style='margin: 15px 0;'>$job_type_badge</div>" : "") . "
                        
                        " . $salary_info . "
                        
                        " . ($job['deadline'] ? "<p style='margin: 15px 0 0 0; color: #dc3545; font-weight: 600;'>⏰ Application deadline: " . date('F j, Y', strtotime($job['deadline'])) . "</p>" : "") . "
                    </div>
                    
                    <!-- Job Description Preview -->
                    <div style='margin: 30px 0;'>
                        <h4 style='color: #333; margin: 0 0 15px 0; font-size: 18px;'>Job Overview:</h4>
                        <div style='background-color: #ffffff; padding: 20px; border: 1px solid #dee2e6; border-radius: 8px;'>
                            <p style='color: #495057; line-height: 1.6; margin: 0;'>
                                " . htmlspecialchars(strlen($job['description']) > 300 ? substr(strip_tags($job['description']), 0, 300) . '...' : strip_tags($job['description'])) . "
                            </p>
                        </div>
                    </div>
                    
                    <!-- Call to Action -->
                    <div style='text-align: center; margin: 40px 0;'>
                        <a href='" . SITE_URL . "/job-details.php?id=" . $job['id'] . "' 
                           style='background-color: #007bff; color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; display: inline-block; font-size: 18px; font-weight: bold; box-shadow: 0 4px 8px rgba(0,123,255,0.3);'>
                            🚀 View Job Details & Apply
                        </a>
                    </div>
                    
                    <!-- Why This Job -->
                    <div style='background-color: #e7f3ff; padding: 20px; border-radius: 8px; margin: 30px 0; border-left: 4px solid #007bff;'>
                        <h4 style='margin: 0 0 15px 0; color: #0056b3; font-size: 16px;'>
                            🎯 Why we think this is perfect for you:
                        </h4>
                        <ul style='margin: 0; padding-left: 20px; color: #0056b3; line-height: 1.6;'>
                            <li>You've previously shown interest in " . htmlspecialchars($job['category_name']) . " positions</li>
                            <li>This role matches your experience level and career goals</li>
                            <li>The company is actively looking for candidates with your background</li>
                        </ul>
                    </div>
                    
                    <!-- Additional Info -->
                    <div style='background-color: #f1f3f4; padding: 20px; border-radius: 8px; margin: 30px 0;'>
                        <h4 style='margin: 0 0 15px 0; color: #495057; font-size: 16px;'>
                            💡 Quick Tips:
                        </h4>
                        <ul style='margin: 0; padding-left: 20px; color: #495057; line-height: 1.6; font-size: 14px;'>
                            <li>Apply early - employers often review applications as they come in</li>
                            <li>Customize your application to highlight relevant experience</li>
                            <li>Make sure your profile is up to date</li>
                            " . ($job['deadline'] ? "<li><strong>Don't wait</strong> - this position has an application deadline</li>" : "") . "
                        </ul>
                    </div>
                </div>
                
                <!-- Footer -->
                <div style='background-color: #f8f9fa; padding: 30px; text-align: center; border-top: 1px solid #e9ecef;'>
                    <p style='margin: 0 0 15px 0; color: #6c757d; font-size: 14px;'>
                        You received this email because you previously applied for jobs in the " . htmlspecialchars($job['category_name']) . " category.
                    </p>
                    <p style='margin: 0; color: #6c757d; font-size: 12px;'>
                        <a href='" . SITE_URL . "/jobs.php' style='color: #007bff; text-decoration: none;'>Browse More Jobs</a> | 
                        <a href='" . SITE_URL . "/candidate/dashboard.php' style='color: #007bff; text-decoration: none;'>My Applications</a>
                    </p>
                    <p style='margin: 15px 0 0 0; color: #6c757d; font-size: 12px;'>
                        This is an automated message from " . SITE_NAME . ". Please do not reply to this email.
                    </p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Notify internal candidate about deactivation/termination
     */
    public function notifyInternalCandidateDeactivation($candidate_id, $deactivation_type, $reason = '') {
        try {
            // Get candidate and company details
            $stmt = $this->db->prepare("
                SELECT c.*, comp.name as company_name
                FROM candidates c
                JOIN companies comp ON c.company_id = comp.id
                WHERE c.id = ? AND c.candidate_type = 'internal'
            ");
            $stmt->execute([$candidate_id]);
            $candidate = $stmt->fetch();
            
            if (!$candidate) {
                return false;
            }
            
            $deactivation_messages = $this->getDeactivationMessages($deactivation_type, $reason);
            $title = $deactivation_messages['title'];
            $message = $deactivation_messages['message'];
            $email_message = $deactivation_messages['email_message'];
            $type = $deactivation_messages['type'];
            
            // Replace placeholders in messages
            $title = str_replace(['{company_name}'], [$candidate['company_name']], $title);
            $message = str_replace(['{candidate_name}', '{company_name}', '{reason}'], 
                                 [$candidate['first_name'], $candidate['company_name'], $reason], 
                                 $message);
            $email_message = str_replace(['{candidate_name}', '{company_name}', '{reason}'], 
                                       [$candidate['first_name'], $candidate['company_name'], $reason], 
                                       $email_message);
            
            // Create in-app notification
            $this->createNotification('candidate', $candidate_id, $title, $message, $type, 'employment_status', $candidate_id);
            
            // Send email notification
            $subject = $title;
            $html_body = $this->generateDeactivationEmailHTML($candidate, $email_message, $deactivation_type, $reason);
            
            $email_sent = $this->emailService->sendEmail($candidate['email'], $subject, $html_body);
            
            if ($email_sent) {
                error_log("Internal candidate " . $deactivation_type . " email sent successfully to: " . $candidate['email']);
            } else {
                error_log("Failed to send internal candidate deactivation email to: " . $candidate['email'] . " - " . $this->emailService->getLastError());
            }
            
            return true;
        } catch (Exception $e) {
            error_log("Error notifying internal candidate deactivation: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get deactivation/termination messages
     */
    private function getDeactivationMessages($deactivation_type, $reason = '') {
        $messages = [
            'inactive' => [
                'title' => 'Employment Status Update - SANPC',
                'message' => 'Your employment status has been temporarily changed to inactive. You will not receive internal job notifications during this period. Please contact HR for more information.',
                'email_message' => 'We are writing to inform you that your employment status has been temporarily changed to inactive. During this period, you will not receive notifications about internal job opportunities.' . 
                                ($reason ? ' Reason: {reason}' : '') . 
                                ' If you have any questions or concerns, please contact the HR department at recruitment@sanpcref.co.za.',
                'type' => 'warning'
            ],
            'terminated' => [
                'title' => 'Employment Status Update - SANPC',
                'message' => 'Your employment has been terminated. You will no longer have access to internal systems and job postings. Please contact HR if you have any questions.',
                'email_message' => 'We regret to inform you that your employment with SANPC has been terminated effective immediately. You will no longer have access to internal systems including the recruitment portal.' . 
                                ($reason ? ' Reason: {reason}' : '') . 
                                ' For any questions regarding final payments, benefits, or other employment-related matters, please contact the HR department at recruitment@sanpcref.co.za.',
                'type' => 'error'
            ]
        ];
        
        return $messages[$deactivation_type] ?? [
            'title' => 'Employment Status Update - SANPC',
            'message' => 'Your employment status has been updated. Please contact HR for more information.',
            'email_message' => 'Your employment status has been updated. Please contact the HR department at recruitment@sanpcref.co.za for more details.',
            'type' => 'info'
        ];
    }
    
    /**
     * Generate HTML email template for deactivation notifications
     */
    private function generateDeactivationEmailHTML($candidate, $message, $deactivation_type, $reason) {
        $type_colors = [
            'inactive' => '#ffc107',
            'terminated' => '#dc3545'
        ];
        
        $color = $type_colors[$deactivation_type] ?? '#6c757d';
        $type_icon = $deactivation_type === 'terminated' ? '🚫' : '⏸️';
        $action_text = $deactivation_type === 'terminated' ? 'Employment Terminated' : 'Employment Status Changed';
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Employment 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, #6c757d 0%, #495057 100%); color: white; padding: 30px; text-align: center;'>
                    <h1 style='margin: 0; font-size: 28px; font-weight: bold;'>SANPC</h1>
                    <p style='margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;'>Employment Status Update</p>
                </div>
                
                <!-- Content -->
                <div style='padding: 40px 30px;'>
                    <!-- Status Header -->
                    <div style='text-align: center; margin-bottom: 30px;'>
                        <div style='font-size: 48px; margin-bottom: 15px;'>$type_icon</div>
                        <h2 style='color: $color; margin: 0; font-size: 24px;'>$action_text</h2>
                    </div>
                    
                    <!-- Company Info -->
                    <div style='background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid $color;'>
                        <h3 style='margin: 0 0 5px 0; color: #333; font-size: 20px;'>SANPC - Human Resources</h3>
                        <p style='margin: 0; color: #666; font-size: 16px;'>" . htmlspecialchars($candidate['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($candidate['first_name']) . ",
                        </p>
                        <p style='color: #333; font-size: 16px; line-height: 1.6;'>
                            " . htmlspecialchars($message) . "
                        </p>
                    </div>
                    
                    " . ($reason ? "
                    <!-- Reason Section -->
                    <div style='background-color: #fff3cd; padding: 20px; border-radius: 8px; margin: 30px 0; border-left: 4px solid #ffc107;'>
                        <h3 style='margin: 0 0 15px 0; color: #856404; font-size: 18px;'>
                            📋 Details
                        </h3>
                        <p style='margin: 0; color: #856404; line-height: 1.6;'>
                            <strong>Reason:</strong> " . htmlspecialchars($reason) . "
                        </p>
                    </div>
                    " : "") . "
                    
                    <!-- Important Notice -->
                    <div style='background-color: " . ($deactivation_type === 'terminated' ? '#f8d7da' : '#fff3cd') . "; padding: 20px; border-radius: 8px; margin-top: 30px; border-left: 4px solid $color;'>
                        <h3 style='margin: 0 0 15px 0; color: " . ($deactivation_type === 'terminated' ? '#721c24' : '#856404') . "; font-size: 18px;'>
                            " . ($deactivation_type === 'terminated' ? '⚠️ Important Notice' : '📢 What This Means') . "
                        </h3>
                        " . ($deactivation_type === 'terminated' ? 
                            "<ul style='margin: 0; padding-left: 20px; color: #721c24; line-height: 1.6;'>
                                <li>Your access to all internal systems has been terminated</li>
                                <li>You will no longer receive internal job notifications</li>
                                <li>Please return any company property in your possession</li>
                                <li>Final payments and benefits information will be communicated separately</li>
                            </ul>" :
                            "<ul style='margin: 0; padding-left: 20px; color: #856404; line-height: 1.6;'>
                                <li>You will temporarily not see internal job postings</li>
                                <li>Your access to the recruitment portal may be limited</li>
                                <li>This status may be reviewed and changed by HR</li>
                                <li>Contact HR if you believe this is an error</li>
                            </ul>"
                        ) . "
                    </div>
                    
                    <!-- Contact Information -->
                    <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;'>
                            📞 Need Assistance?
                        </h3>
                        <p style='margin: 0; color: #495057; line-height: 1.6;'>
                            If you have questions about this decision or need clarification, please contact the HR department:
                        </p>
                        <p style='margin: 10px 0 0 0; color: #495057;'>
                            <strong>Email:</strong> recruitment@sanpcref.co.za<br>
                            <strong>Subject:</strong> Employment Status Inquiry - " . htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']) . "
                        </p>
                    </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 official communication from SANPC Human Resources.
                    </p>
                    <p style='margin: 0; color: #6c757d; font-size: 12px;'>
                        Please do not reply to this email. For inquiries, use the contact information provided above.
                    </p>
                </div>
            </div>
        </body>
        </html>";
    }
}
?>