<?php
/**
 * Email Service
 * 
 * This service provides methods to send various types of email notifications
 */

namespace Services\Email;

class EmailService {
    private $fromEmail;
    private $fromName;
    private $replyToEmail;
    private $siteName;
    private $siteUrl;
    
    /**
     * Constructor
     */
    public function __construct() {
        // Load configuration
        require_once __DIR__ . '/../../config/email_config.php';
        
        // Set default email settings from config
        $this->fromEmail = EMAIL_FROM;
        $this->fromName = EMAIL_FROM_NAME;
        $this->replyToEmail = EMAIL_REPLY_TO;
        $this->siteName = SITE_NAME;
        $this->siteUrl = SITE_URL;
    }
    
    /**
     * Send an assignment notification email
     * 
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name
     * @param string $memberName Name of the assigned member
     * @param int $assignmentId Assignment ID
     * @param string $assignmentType Type of assignment
     * @param string $priority Priority level
     * @param string $dueDate Due date (if any)
     * @param string $notes Assignment notes
     * @return bool Success status
     */
    public function sendAssignmentNotification($toEmail, $toName, $memberName, $assignmentId, $assignmentType, $priority, $dueDate = null, $notes = '') {
        // Set email subject
        $subject = "[$this->siteName] New Assignment: $memberName";
        
        // Format assignment type and priority for display
        $assignmentTypeFormatted = ucfirst($assignmentType);
        $priorityFormatted = ucfirst($priority);
        
        // Format due date
        $dueDateText = $dueDate ? date('F j, Y, g:i a', strtotime($dueDate)) : 'No due date specified';
        
        // Prepare email content
        $message = "
        <html>
        <head>
            <title>New Assignment Notification</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #3c8dbc; color: white; padding: 10px; text-align: center; }
                .content { padding: 20px; background-color: #f8f9fa; border: 1px solid #ddd; }
                .footer { font-size: 12px; text-align: center; margin-top: 20px; color: #777; }
                .priority-urgent { color: #dc3545; font-weight: bold; }
                .priority-high { color: #fd7e14; font-weight: bold; }
                .priority-normal { color: #17a2b8; }
                .priority-low { color: #6c757d; }
                .button { display: inline-block; padding: 10px 15px; background-color: #28a745; color: white; text-decoration: none; border-radius: 4px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>New Assignment Notification</h2>
                </div>
                <div class='content'>
                    <p>Hello $toName,</p>
                    
                    <p>You have been assigned a new task in the $this->siteName admin panel.</p>
                    
                    <h3>Assignment Details:</h3>
                    <ul>
                        <li><strong>Member:</strong> $memberName</li>
                        <li><strong>Assignment Type:</strong> $assignmentTypeFormatted</li>
                        <li><strong>Priority:</strong> <span class='priority-$priority'>$priorityFormatted</span></li>
                        <li><strong>Due Date:</strong> $dueDateText</li>
                        <li><strong>Assignment ID:</strong> #$assignmentId</li>
                    </ul>
                    
                    " . ($notes ? "<h3>Notes:</h3><p>$notes</p>" : "") . "
                    
                    <p>Please log in to the admin panel to view and manage this assignment.</p>
                    
                    <p style='text-align: center;'>
                        <a href='$this->siteUrl/adminlte/assignments.php' class='button'>View Assignment</a>
                    </p>
                </div>
                <div class='footer'>
                    <p>This is an automated message from $this->siteName. Please do not reply to this email.</p>
                    <p>&copy; " . date('Y') . " $this->siteName. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        // Set headers for HTML email
        $headers = $this->getEmailHeaders();
        
        // Send email
        return $this->sendEmail($toEmail, $subject, $message, $headers);
    }
    
    /**
     * Send a bulk assignment notification email
     * 
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name
     * @param array $assignments Array of assignment details
     * @param string $assignmentType Type of assignment
     * @param string $priority Priority level
     * @param string $dueDate Due date (if any)
     * @return bool Success status
     */
    public function sendBulkAssignmentNotification($toEmail, $toName, $assignments, $assignmentType, $priority, $dueDate = null) {
        // Set email subject
        $subject = "[$this->siteName] Multiple New Assignments";
        
        // Format assignment type and priority for display
        $assignmentTypeFormatted = ucfirst($assignmentType);
        $priorityFormatted = ucfirst($priority);
        
        // Format due date
        $dueDateText = $dueDate ? date('F j, Y, g:i a', strtotime($dueDate)) : 'No due date specified';
        
        // Build assignment list
        $assignmentList = '';
        foreach ($assignments as $assignment) {
            $assignmentList .= "<li><strong>{$assignment['member_name']}</strong> (Assignment ID: #{$assignment['assignment_id']})</li>";
        }
        
        // Prepare email content
        $message = "
        <html>
        <head>
            <title>Bulk Assignment Notification</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #3c8dbc; color: white; padding: 10px; text-align: center; }
                .content { padding: 20px; background-color: #f8f9fa; border: 1px solid #ddd; }
                .footer { font-size: 12px; text-align: center; margin-top: 20px; color: #777; }
                .priority-urgent { color: #dc3545; font-weight: bold; }
                .priority-high { color: #fd7e14; font-weight: bold; }
                .priority-normal { color: #17a2b8; }
                .priority-low { color: #6c757d; }
                .button { display: inline-block; padding: 10px 15px; background-color: #28a745; color: white; text-decoration: none; border-radius: 4px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Bulk Assignment Notification</h2>
                </div>
                <div class='content'>
                    <p>Hello $toName,</p>
                    
                    <p>You have been assigned <strong>" . count($assignments) . " new tasks</strong> in the $this->siteName admin panel.</p>
                    
                    <h3>Common Assignment Details:</h3>
                    <ul>
                        <li><strong>Assignment Type:</strong> $assignmentTypeFormatted</li>
                        <li><strong>Priority:</strong> <span class='priority-$priority'>$priorityFormatted</span></li>
                        <li><strong>Due Date:</strong> $dueDateText</li>
                    </ul>
                    
                    <h3>Assigned Members:</h3>
                    <ul>
                        $assignmentList
                    </ul>
                    
                    <p>Please log in to the admin panel to view and manage these assignments.</p>
                    
                    <p style='text-align: center;'>
                        <a href='$this->siteUrl/adminlte/assignments.php' class='button'>View Assignments</a>
                    </p>
                </div>
                <div class='footer'>
                    <p>This is an automated message from $this->siteName. Please do not reply to this email.</p>
                    <p>&copy; " . date('Y') . " $this->siteName. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        // Set headers for HTML email
        $headers = $this->getEmailHeaders();
        
        // Send email
        return $this->sendEmail($toEmail, $subject, $message, $headers);
    }
    
    /**
     * Send a status update notification email
     * 
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name
     * @param string $memberName Name of the assigned member
     * @param int $assignmentId Assignment ID
     * @param string $newStatus New status of the assignment
     * @return bool Success status
     */
    public function sendStatusUpdateNotification($toEmail, $toName, $memberName, $assignmentId, $newStatus) {
        // Set email subject
        $subject = "[$this->siteName] Assignment Status Update: $memberName";
        
        // Format status for display
        $statusFormatted = ucfirst($newStatus);
        
        // Status-specific content
        $statusMessage = '';
        $statusColor = '';
        
        switch ($newStatus) {
            case 'completed':
                $statusMessage = 'The assignment has been marked as completed.';
                $statusColor = '#28a745';
                break;
            case 'cancelled':
                $statusMessage = 'The assignment has been cancelled.';
                $statusColor = '#dc3545';
                break;
            case 'active':
                $statusMessage = 'The assignment is now active.';
                $statusColor = '#17a2b8';
                break;
            case 'overdue':
                $statusMessage = 'The assignment is now overdue. Please attend to it as soon as possible.';
                $statusColor = '#fd7e14';
                break;
            default:
                $statusMessage = "The assignment status has been updated to $statusFormatted.";
                $statusColor = '#6c757d';
        }
        
        // Prepare email content
        $message = "
        <html>
        <head>
            <title>Assignment Status Update</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #3c8dbc; color: white; padding: 10px; text-align: center; }
                .content { padding: 20px; background-color: #f8f9fa; border: 1px solid #ddd; }
                .footer { font-size: 12px; text-align: center; margin-top: 20px; color: #777; }
                .status { font-weight: bold; color: $statusColor; }
                .button { display: inline-block; padding: 10px 15px; background-color: #3c8dbc; color: white; text-decoration: none; border-radius: 4px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Assignment Status Update</h2>
                </div>
                <div class='content'>
                    <p>Hello $toName,</p>
                    
                    <p>The status of your assignment for <strong>$memberName</strong> (Assignment ID: #$assignmentId) has been updated to <span class='status'>$statusFormatted</span>.</p>
                    
                    <p>$statusMessage</p>
                    
                    <p>Please log in to the admin panel for more details.</p>
                    
                    <p style='text-align: center;'>
                        <a href='$this->siteUrl/adminlte/assignments.php' class='button'>View Assignments</a>
                    </p>
                </div>
                <div class='footer'>
                    <p>This is an automated message from $this->siteName. Please do not reply to this email.</p>
                    <p>&copy; " . date('Y') . " $this->siteName. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        // Set headers for HTML email
        $headers = $this->getEmailHeaders();
        
        // Send email
        return $this->sendEmail($toEmail, $subject, $message, $headers);
    }
    
    /**
     * Send a due date reminder email
     * 
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name
     * @param array $assignments Array of assignment details
     * @return bool Success status
     */
    public function sendDueDateReminder($toEmail, $toName, $assignments) {
        // Set email subject
        $subject = "[$this->siteName] Assignment Due Date Reminder";
        
        // Build assignment list
        $assignmentList = '';
        foreach ($assignments as $assignment) {
            $dueDate = date('F j, Y, g:i a', strtotime($assignment['due_date']));
            $priorityClass = "priority-{$assignment['priority']}";
            $priorityText = ucfirst($assignment['priority']);
            
            $assignmentList .= "
            <tr>
                <td>{$assignment['member_name']}</td>
                <td>{$assignment['assignment_type']}</td>
                <td class='$priorityClass'>$priorityText</td>
                <td>$dueDate</td>
                <td>#{$assignment['id']}</td>
            </tr>";
        }
        
        // Prepare email content
        $message = "
        <html>
        <head>
            <title>Assignment Due Date Reminder</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 700px; margin: 0 auto; padding: 20px; }
                .header { background-color: #fd7e14; color: white; padding: 10px; text-align: center; }
                .content { padding: 20px; background-color: #f8f9fa; border: 1px solid #ddd; }
                .footer { font-size: 12px; text-align: center; margin-top: 20px; color: #777; }
                .priority-urgent { color: #dc3545; font-weight: bold; }
                .priority-high { color: #fd7e14; font-weight: bold; }
                .priority-normal { color: #17a2b8; }
                .priority-low { color: #6c757d; }
                .button { display: inline-block; padding: 10px 15px; background-color: #fd7e14; color: white; text-decoration: none; border-radius: 4px; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
                th { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Assignment Due Date Reminder</h2>
                </div>
                <div class='content'>
                    <p>Hello $toName,</p>
                    
                    <p>This is a reminder that you have <strong>" . count($assignments) . " assignment(s)</strong> that are due soon or overdue.</p>
                    
                    <h3>Assignment Details:</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>Member</th>
                                <th>Type</th>
                                <th>Priority</th>
                                <th>Due Date</th>
                                <th>ID</th>
                            </tr>
                        </thead>
                        <tbody>
                            $assignmentList
                        </tbody>
                    </table>
                    
                    <p>Please log in to the admin panel to review and complete these assignments.</p>
                    
                    <p style='text-align: center;'>
                        <a href='$this->siteUrl/adminlte/assignments.php' class='button'>View Assignments</a>
                    </p>
                </div>
                <div class='footer'>
                    <p>This is an automated message from $this->siteName. Please do not reply to this email.</p>
                    <p>&copy; " . date('Y') . " $this->siteName. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        // Set headers for HTML email
        $headers = $this->getEmailHeaders();
        
        // Send email
        return $this->sendEmail($toEmail, $subject, $message, $headers);
    }
    
    /**
     * Get standard email headers
     * 
     * @return string Email headers
     */
    private function getEmailHeaders() {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: $this->fromName <$this->fromEmail>\r\n";
        $headers .= "Reply-To: $this->replyToEmail\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        return $headers;
    }
    
    /**
     * Send an email
     * 
     * @param string $to Recipient email
     * @param string $subject Email subject
     * @param string $message Email message
     * @param string $headers Email headers
     * @return bool Success status
     */
    private function sendEmail($to, $subject, $message, $headers) {
        // Check if we should actually send emails or just log them
        if (defined('EMAIL_DEBUG_MODE') && EMAIL_DEBUG_MODE) {
            // Log email instead of sending
            $logFile = __DIR__ . '/../../logs/email_log.txt';
            $logMessage = "[" . date('Y-m-d H:i:s') . "] To: $to | Subject: $subject | Headers: $headers | Message: " . substr(strip_tags($message), 0, 200) . "...\n";
            
            if (file_put_contents($logFile, $logMessage, FILE_APPEND)) {
                return true;
            }
            
            return false;
        }
        
        // Actually send the email
        return mail($to, $subject, $message, $headers);
    }
    
    /**
     * Send an assignment reminder notification
     * 
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name
     * @param string $memberName Name of the assigned member
     * @param int $assignmentId Assignment ID
     * @param string $assignmentTitle Assignment title
     * @param string $dueDate Due date
     * @param string $reminderType Type of reminder: 'upcoming', 'overdue', or 'inactive'
     * @param int $daysOverdue For overdue reminders, the number of days overdue
     * @return bool Success status
     */
    public function sendAssignmentReminderNotification($toEmail, $toName, $memberName, $assignmentId, $assignmentTitle, $dueDate, $reminderType, $daysOverdue = 0) {
        // Include email templates
        require_once __DIR__ . '/templates/reminder_templates.php';
        
        // Set email subject based on reminder type
        switch ($reminderType) {
            case 'upcoming':
                $subject = "[$this->siteName] Assignment Due Soon: $assignmentTitle";
                $template = getUpcomingDueTemplate($toName, $memberName, $assignmentId, $assignmentTitle, $dueDate, $this->siteName, $this->siteUrl);
                break;
                
            case 'overdue':
                $subject = "[$this->siteName] OVERDUE Assignment: $assignmentTitle";
                $template = getOverdueTemplate($toName, $memberName, $assignmentId, $assignmentTitle, $dueDate, $daysOverdue, $this->siteName, $this->siteUrl);
                break;
                
            case 'inactive':
                $subject = "[$this->siteName] Inactive Assignment: $assignmentTitle";
                $template = getInactiveTemplate($toName, $memberName, $assignmentId, $assignmentTitle, $dueDate, $this->siteName, $this->siteUrl);
                break;
                
            default:
                return false;
        }
        
        // Get email headers
        $headers = $this->getEmailHeaders();
        
        // Send the email
        return $this->sendEmail($toEmail, $subject, $template, $headers);
    }
    
    /**
     * Send a supervisor escalation notification for an inactive assignment
     * 
     * @param string $toEmail Supervisor's email
     * @param string $toName Supervisor's name
     * @param string $adminName Name of the assigned admin
     * @param string $memberName Name of the member
     * @param int $assignmentId Assignment ID
     * @param string $assignmentTitle Assignment title
     * @param string $dueDate Due date
     * @return bool Success status
     */
    public function sendSupervisorEscalationNotification($toEmail, $toName, $adminName, $memberName, $assignmentId, $assignmentTitle, $dueDate) {
        // Include email templates
        require_once __DIR__ . '/templates/reminder_templates.php';
        
        // Set email subject
        $subject = "[$this->siteName] Assignment Escalation: $adminName - $assignmentTitle";
        
        // Get template
        $template = getSupervisorEscalationTemplate($toName, $adminName, $memberName, $assignmentId, $assignmentTitle, $dueDate, $this->siteName, $this->siteUrl);
        
        // Get email headers
        $headers = $this->getEmailHeaders();
        
        // Send the email
        return $this->sendEmail($toEmail, $subject, $template, $headers);
    }
}
