<?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;
        }
    }
}
?>