<?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) {
        $success = false;
        
        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) {
                error_log("Application not found for notification: $application_id");
                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 should always work)
            $notification_success = $this->createNotification('candidate', $application['candidate_id'], $title, $message, $type, 'application', $application_id);
            
            if ($notification_success) {
                $success = true;
                error_log("In-app notification created for application: $application_id");
            } else {
                error_log("Failed to create in-app notification for application: $application_id");
            }
            
            // Try to send email notification via Gmail SMTP
            try {
                require_once __DIR__ . '/gmail_email_service.php';
                $gmailService = new GmailEmailService($this->db);
                $email_success = $gmailService->sendNotificationEmail($application, $message, $new_status);
                
                if ($email_success) {
                    error_log("Gmail notification sent for application: $application_id to " . $application['email']);
                } else {
                    error_log("Gmail notification failed for application: $application_id to " . $application['email']);
                    
                    // Try fallback to PHP mail service
                    try {
                        require_once __DIR__ . '/email_service_fallback.php';
                        $emailService = new EmailService($this->db);
                        $fallback_success = $emailService->sendNotificationEmail($application, $message, $new_status);
                        if ($fallback_success) {
                            error_log("Fallback email sent for application: $application_id");
                        }
                    } catch (Exception $fallback_e) {
                        error_log("Fallback email also failed for application $application_id: " . $fallback_e->getMessage());
                    }
                }
            } catch (Exception $e) {
                error_log("Gmail notification error for application $application_id: " . $e->getMessage());
                
                // Try fallback to PHP mail service
                try {
                    require_once __DIR__ . '/email_service_fallback.php';
                    $emailService = new EmailService($this->db);
                    $fallback_success = $emailService->sendNotificationEmail($application, $message, $new_status);
                    if ($fallback_success) {
                        error_log("Fallback email sent for application: $application_id");
                    }
                } catch (Exception $fallback_e) {
                    error_log("All email methods failed for application $application_id");
                }
            }
            
            
            return $success;
            
        } catch (Exception $e) {
            error_log("Error notifying application status change for $application_id: " . $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 candidates who previously applied to jobs in the same category about a new job posting
     */
    public function notifyPreviousApplicants($job_id) {
        try {
            // Get the new job details
            $stmt = $this->db->prepare("
                SELECT j.*, c.name as company_name, cat.name as category_name 
                FROM jobs j
                LEFT 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 || !$job['category_id']) {
                error_log("Job not found or has no category for notification: $job_id");
                return false;
            }
            
            // Find candidates who have previously applied to jobs in the same category
            // Exclude candidates who have already applied to this specific job
            $stmt = $this->db->prepare("
                SELECT DISTINCT c.id, c.email, c.first_name, c.last_name
                FROM candidates c
                INNER JOIN job_applications ja ON c.id = ja.candidate_id
                INNER JOIN jobs prev_jobs ON ja.job_id = prev_jobs.id
                WHERE prev_jobs.category_id = ?
                AND c.id NOT IN (
                    SELECT candidate_id 
                    FROM job_applications 
                    WHERE job_id = ?
                )
                AND c.email IS NOT NULL
                AND c.email != ''
            ");
            $stmt->execute([$job['category_id'], $job_id]);
            $candidates = $stmt->fetchAll();
            
            if (empty($candidates)) {
                error_log("No eligible candidates found for job notification: $job_id");
                return true; // Not an error, just no candidates to notify
            }
            
            $success_count = 0;
            $total_candidates = count($candidates);
            
            error_log("Found $total_candidates candidates to notify for new job: " . $job['title']);
            
            foreach ($candidates as $candidate) {
                $success = $this->sendNewJobNotification($candidate, $job);
                if ($success) {
                    $success_count++;
                }
            }
            
            error_log("Successfully notified $success_count out of $total_candidates candidates for job: " . $job['title']);
            return $success_count > 0;
            
        } catch (Exception $e) {
            error_log("Error notifying previous applicants for job $job_id: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send notification to a single candidate about a new job opportunity
     */
    private function sendNewJobNotification($candidate, $job) {
        try {
            // Create in-app notification
            $title = "New Job Opportunity in {$job['category_name']}";
            $message = "A new job '{$job['title']}' at {$job['company_name']} has been posted in the {$job['category_name']} category. Based on your previous applications, this might interest you!";
            
            $notification_success = $this->createNotification(
                'candidate', 
                $candidate['id'], 
                $title, 
                $message, 
                'info', 
                'job_opportunity', 
                $job['id']
            );
            
            // Send email notification
            $email_success = false;
            try {
                $email_subject = "New Job Alert: {$job['title']} at {$job['company_name']}";
                $email_message = $this->formatNewJobEmailMessage($candidate, $job);
                
                require_once __DIR__ . '/gmail_email_service.php';
                $gmailService = new GmailEmailService($this->db);
                $email_success = $gmailService->sendEmail(
                    $candidate['email'],
                    $email_subject,
                    $email_message
                );
                
                if ($email_success) {
                    error_log("New job email sent to: " . $candidate['email'] . " for job: " . $job['title']);
                } else {
                    error_log("Failed to send new job email to: " . $candidate['email'] . " for job: " . $job['title']);
                }
                
            } catch (Exception $e) {
                error_log("Error sending new job email to " . $candidate['email'] . ": " . $e->getMessage());
            }
            
            return $notification_success; // Return true if at least in-app notification succeeded
            
        } catch (Exception $e) {
            error_log("Error sending new job notification to candidate {$candidate['id']}: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Format email message for new job notifications
     */
    private function formatNewJobEmailMessage($candidate, $job) {
        $job_url = SITE_URL . "/job-details.php?id=" . $job['id'];
        
        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;'>New Job Opportunity Alert</p>
                </div>
                
                <div style='background: #e8f5e8; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #28a745;'>
                    <h2 style='color: #155724; margin: 0 0 10px 0;'>" . htmlspecialchars($job['title']) . "</h2>
                    <p style='color: #155724; margin: 0; font-size: 16px;'><strong>" . htmlspecialchars($job['company_name']) . "</strong></p>
                    <p style='color: #155724; margin: 5px 0 0 0;'><i class='fas fa-tag'></i> " . htmlspecialchars($job['category_name']) . " • " . htmlspecialchars($job['location']) . "</p>
                </div>
                
                <div style='margin: 20px 0;'>
                    <p style='color: #333; line-height: 1.6;'>Dear " . htmlspecialchars($candidate['first_name']) . ",</p>
                    <p style='color: #333; line-height: 1.6;'>We have a new job opportunity that might interest you! Based on your previous applications in the <strong>" . htmlspecialchars($job['category_name']) . "</strong> category, we thought you'd like to know about this new position.</p>
                </div>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <h4 style='margin: 0 0 10px 0; color: #333;'>Job Details:</h4>
                    <p style='margin: 5px 0; color: #555;'><strong>Position:</strong> " . htmlspecialchars($job['title']) . "</p>
                    <p style='margin: 5px 0; color: #555;'><strong>Company:</strong> " . htmlspecialchars($job['company_name']) . "</p>
                    <p style='margin: 5px 0; color: #555;'><strong>Category:</strong> " . htmlspecialchars($job['category_name']) . "</p>
                    <p style='margin: 5px 0; color: #555;'><strong>Location:</strong> " . htmlspecialchars($job['location']) . "</p>
                    <p style='margin: 5px 0; color: #555;'><strong>Type:</strong> " . ucfirst(str_replace('-', ' ', $job['employment_type'])) . "</p>
                    " . ($job['deadline'] ? "<p style='margin: 5px 0; color: #555;'><strong>Application Deadline:</strong> " . date('M d, Y', strtotime($job['deadline'])) . "</p>" : "") . "
                </div>
                
                <div style='margin: 20px 0;'>
                    <p style='color: #333; line-height: 1.6;'><strong>Job Description Preview:</strong></p>
                    <p style='color: #666; line-height: 1.6; font-style: italic;'>" . htmlspecialchars(substr(strip_tags($job['description']), 0, 200)) . "...</p>
                </div>
                
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='" . $job_url . "' 
                       style='background: #28a745; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;'>
                        View Job Details & Apply
                    </a>
                </div>
                
                <div style='border-top: 1px solid #eee; padding-top: 20px; margin-top: 30px; text-align: center;'>
                    <p style='color: #999; font-size: 14px; margin: 10px 0;'>
                        Don't want to receive these job alerts? <a href='" . SITE_URL . "/candidate/profile.php' style='color: #0d6efd;'>Manage your email preferences</a>
                    </p>
                    <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>";
    }
}
?>