<?php
class NotificationSystem {
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    /**
     * 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 EmailService
     */
    public function sendEmailNotification($to_email, $subject, $message) {
        try {
            require_once __DIR__ . '/email_service.php';
            $emailService = new EmailService($this->db);
            
            return $emailService->sendEmail($to_email, $subject, $message);
        } 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 EmailService
            require_once __DIR__ . '/email_service.php';
            $emailService = new EmailService($this->db);
            $emailService->sendNotificationEmail($application, $message, $new_status);
            
            return true;
        } catch (Exception $e) {
            error_log("Error notifying application status change: " . $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'
            ],
            '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'
        ];
    }
    
    /**
     * Format email message with HTML template
     */
    private function formatEmailMessage($application, $message, $status) {
        return "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px;'>
            <div style='background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>
                <div style='text-align: center; margin-bottom: 30px;'>
                    <h1 style='color: #0d6efd; margin: 0;'>" . SITE_NAME . "</h1>
                    <p style='color: #666; margin: 5px 0 0 0;'>Application Status Update</p>
                </div>
                
                <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;'>
                    <h2 style='color: #333; margin: 0 0 10px 0;'>" . htmlspecialchars($application['job_title']) . "</h2>
                    <p style='color: #666; margin: 0;'>" . htmlspecialchars($application['company_name']) . "</p>
                </div>
                
                <div style='margin: 20px 0;'>
                    <p style='color: #333; line-height: 1.6;'>Dear " . htmlspecialchars($application['first_name']) . ",</p>
                    <p style='color: #333; line-height: 1.6;'>" . htmlspecialchars($message) . "</p>
                </div>
                
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='" . SITE_URL . "/candidate/applications.php' 
                       style='background: #0d6efd; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; display: inline-block;'>
                        View Application Status
                    </a>
                </div>
                
                <div style='border-top: 1px solid #eee; padding-top: 20px; margin-top: 30px; text-align: center;'>
                    <p style='color: #999; font-size: 12px; margin: 0;'>
                        This is an automated message from " . SITE_NAME . ". Please do not reply to this email.
                    </p>
                </div>
            </div>
        </div>";
    }
    
    /**
     * Generate basic email template
     */
    private function generateEmailTemplate($subject, $message) {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>" . htmlspecialchars($subject) . "</title>
        </head>
        <body style='margin: 0; padding: 0; font-family: Arial, sans-serif;'>
            " . $message . "
        </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;
        }
    }
    
    /**
     * 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);
            
            require_once __DIR__ . '/email_service.php';
            $emailService = new EmailService($this->db);
            $emailService->sendEmail($candidate['email'], $subject, $html_body);
            
            return true;
        } catch (Exception $e) {
            error_log("Error notifying internal candidate approval: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get internal candidate approval/rejection messages
     */
    private function getInternalCandidateMessages($status, $rejection_reason = '') {
        $messages = [
            'approved' => [
                'title' => 'Internal Transfer Application Approved - {company_name}',
                'message' => 'Great news! Your internal transfer application at {company_name} 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 your HR department. You can now log into the recruitment portal using your credentials and start applying for internal positions within {company_name}.',
                'type' => 'success'
            ],
            'rejected' => [
                'title' => 'Internal Transfer Application - {company_name}',
                'message' => 'Your internal transfer application at {company_name} has been reviewed. Please contact HR for more information.',
                'email_message' => 'Thank you for your interest in internal opportunities at {company_name}. 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 - {company_name}',
            '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</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;'>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 to discuss this decision and learn about future opportunities within the company.
                        </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 " . SITE_NAME . ".
                    </p>
                    <p style='margin: 0; color: #6c757d; font-size: 12px;'>
                        Please do not reply to this email. For support, contact your HR department.
                    </p>
                </div>
            </div>
        </body>
        </html>";
    }
}
?>