<?php
// PHPMailer email functions - Manual installation
require_once __DIR__ '/../phpmailer/src/Exception.php';
require_once 
__DIR__ '/../phpmailer/src/PHPMailer.php';
require_once 
__DIR__ '/../phpmailer/src/SMTP.php';
require_once 
__DIR__ '/email_config.php';

use 
PHPMailer\PHPMailer\PHPMailer;
use 
PHPMailer\PHPMailer\SMTP;
use 
PHPMailer\PHPMailer\Exception;

/**
 * Create and configure PHPMailer instance
 */
function create_mailer() {
    
$mail = new PHPMailer(true);
    
    try {
        
// Server settings
        
if (EMAIL_DEBUG) {
            
$mail->SMTPDebug SMTP::DEBUG_SERVER;
        }
        
        
$mail->isSMTP();
        
$mail->Host       SMTP_HOST;
        
$mail->SMTPAuth   true;
        
$mail->Username   SMTP_USERNAME;
        
$mail->Password   SMTP_PASSWORD;
        
$mail->SMTPSecure SMTP_SECURE;
        
$mail->Port       SMTP_PORT;
        
        
// Default sender
        
$mail->setFrom(FROM_EMAILFROM_NAME);
        
$mail->addReplyTo(REPLY_TO_EMAILFROM_NAME);
        
        
// Content settings
        
$mail->isHTML(true);
        
$mail->CharSet 'UTF-8';
        
        return 
$mail;
        
    } catch (
Exception $e) {
        
error_log("PHPMailer configuration error: " $e->getMessage());
        return 
false;
    }
}

/**
 * Send notification email using PHPMailer
 */
function send_notification_email_phpmailer($userEmail$userName$requestId$workflowTitle$stateTitle$isCompletion false$requesterName '') {
    if (!
ENABLE_EMAIL_NOTIFICATIONS) {
        return 
true// Skip if disabled
    
}
    
    
$mail create_mailer();
    if (!
$mail) {
        return 
false;
    }
    
    try {
        
// Recipients
        
$mail->addAddress($userEmail$userName);
        
        
// Subject
        
$subject $isCompletion 
            
"Request #$requestId Completed - $workflowTitle"
            
"New Task Assignment - Request #$requestId";
        
$mail->Subject $subject;
        
        
// Email content
        
$mail->Body build_email_template_phpmailer($userName$requestId$workflowTitle$stateTitle$isCompletion$requesterName);
        
        
// Alternative plain text body
        
$mail->AltBody build_plain_text_email($userName$requestId$workflowTitle$stateTitle$isCompletion$requesterName);
        
        
$result $mail->send();
        
        
// Log successful send
        
if ($result) {
            
error_log("Email sent successfully to: $userEmail for request #$requestId");
        }
        
        return 
$result;
        
    } catch (
Exception $e) {
        
error_log("Email send failed to $userEmail: " $e->getMessage());
        return 
false;
    }
}

/**
 * Build HTML email template for PHPMailer
 */
function build_email_template_phpmailer($userName$requestId$workflowTitle$stateTitle$isCompletion$requesterName) {
    
$baseUrl get_base_url();
    
$requestUrl $baseUrl "/index.php?page=request_handle&req=" $requestId;
    
    if (
$isCompletion) {
        
$title "Request Completed";
        
$message "Your request has been completed and closed.";
        
$actionText "View Completed Request";
        
$iconColor "#059669";
        
$icon "✅";
        
$headerColor "#059669";
    } else {
        
$title "New Task Assignment";
        
$message "A new request has been assigned to you and requires your attention.";
        
$actionText "Handle Request";
        
$iconColor "#2563eb";
        
$icon "📋";
        
$headerColor "#2563eb";
    }
    
    
$currentYear date('Y');
    
    
$html "
    <!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>" 
htmlspecialchars($title) . "</title>
        <style>
            body { 
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                line-height: 1.6; 
                color: #1e293b; 
                background-color: #f8fafc; 
                margin: 0; 
                padding: 20px; 
            }
            .email-container { 
                max-width: 600px; 
                margin: 0 auto; 
                background-color: #ffffff; 
                border-radius: 12px; 
                overflow: hidden; 
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1); 
            }
            .email-header { 
                background: linear-gradient(135deg, 
$headerColor, " . ($isCompletion '#047857' '#1d4ed8') . "); 
                color: white; 
                padding: 30px 20px; 
                text-align: center; 
            }
            .email-header h1 { 
                margin: 0; 
                font-size: 24px; 
                font-weight: 700; 
            }
            .email-content { 
                padding: 30px 20px; 
            }
            .greeting { 
                font-size: 18px; 
                font-weight: 600; 
                margin-bottom: 20px; 
                color: #1e293b; 
            }
            .notification-card { 
                background: linear-gradient(135deg, #f8fafc, #e2e8f0); 
                border-radius: 12px; 
                padding: 24px; 
                margin: 20px 0; 
                border-left: 4px solid 
$iconColor
            }
            .notification-icon { 
                font-size: 32px; 
                margin-bottom: 12px; 
                display: block; 
            }
            .notification-title { 
                font-size: 20px; 
                font-weight: 700; 
                color: #1e293b; 
                margin-bottom: 8px; 
            }
            .notification-message { 
                color: #64748b; 
                font-size: 16px; 
                line-height: 1.5; 
            }
            .request-details { 
                background: #ffffff; 
                border-radius: 8px; 
                padding: 20px; 
                margin: 20px 0; 
                border: 1px solid #e2e8f0; 
            }
            .request-details h4 { 
                font-size: 16px; 
                font-weight: 600; 
                color: #1e293b; 
                margin-bottom: 16px; 
                border-bottom: 2px solid #e2e8f0; 
                padding-bottom: 8px; 
            }
            .detail-row { 
                display: flex; 
                justify-content: space-between; 
                margin: 12px 0; 
                padding: 8px 0; 
                border-bottom: 1px solid #f1f5f9; 
            }
            .detail-label { 
                font-weight: 600; 
                color: #64748b; 
                flex: 1; 
            }
            .detail-value { 
                color: #1e293b; 
                flex: 2; 
                text-align: right; 
                font-weight: 500; 
            }
            .action-button { 
                display: inline-block; 
                background: linear-gradient(135deg, 
$iconColor, " . ($isCompletion '#047857' '#1d4ed8') . "); 
                color: white; 
                padding: 16px 32px; 
                text-decoration: none; 
                border-radius: 8px; 
                font-weight: 600; 
                font-size: 16px; 
                margin: 20px 0; 
                text-align: center; 
                display: block; 
            }
            .email-footer { 
                background: #f8fafc; 
                padding: 24px 20px; 
                text-align: center; 
                color: #64748b; 
                font-size: 14px; 
                border-top: 1px solid #e2e8f0; 
            }
        </style>
    </head>
    <body>
        <div class='email-container'>
            <div class='email-header'>
                <h1>
$icon " htmlspecialchars(COMPANY_NAME) . "</h1>
                <div>Ticket System Notification</div>
            </div>
            
            <div class='email-content'>
                <div class='greeting'>Hello " 
htmlspecialchars($userName) . ",</div>
                
                <div class='notification-card'>
                    <span class='notification-icon'>
$icon</span>
                    <div class='notification-title'>
$title</div>
                    <div class='notification-message'>
$message</div>
                </div>
                
                <div class='request-details'>
                    <h4>Request Details</h4>
                    <div class='detail-row'>
                        <span class='detail-label'>Request ID:</span>
                        <span class='detail-value'>#
$requestId</span>
                    </div>
                    <div class='detail-row'>
                        <span class='detail-label'>Workflow:</span>
                        <span class='detail-value'>" 
htmlspecialchars($workflowTitle) . "</span>
                    </div>
                    <div class='detail-row'>
                        <span class='detail-label'>Current State:</span>
                        <span class='detail-value'>" 
htmlspecialchars($stateTitle) . "</span>
                    </div>"
;
    
    if (!
$isCompletion && $requesterName) {
        
$html .= "
                    <div class='detail-row'>
                        <span class='detail-label'>Requested by:</span>
                        <span class='detail-value'>" 
htmlspecialchars($requesterName) . "</span>
                    </div>"
;
    }
    
    
$html .= "
                </div>
                
                <a href='
$requestUrl' class='action-button'>$actionText</a>
            </div>
            
            <div class='email-footer'>
                <p>This is an automated message from " 
htmlspecialchars(COMPANY_NAME) . ".</p>
                <p>&copy; 
$currentYear " htmlspecialchars(COMPANY_NAME) . ". All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>"
;
    
    return 
$html;
}

/**
 * Build plain text email for clients that don't support HTML
 */
function build_plain_text_email($userName$requestId$workflowTitle$stateTitle$isCompletion$requesterName) {
    
$baseUrl get_base_url();
    
$requestUrl $baseUrl "/index.php?page=request_handle&req=" $requestId;
    
    if (
$isCompletion) {
        
$title "Request Completed";
        
$message "Your request has been completed and closed.";
        
$actionText "View Completed Request";
    } else {
        
$title "New Task Assignment";
        
$message "A new request has been assigned to you and requires your attention.";
        
$actionText "Handle Request";
    }
    
    
$text "
strtoupper(COMPANY_NAME) . " - TICKET SYSTEM NOTIFICATION

Hello 
$userName,

$title
$message

REQUEST DETAILS:
- Request ID: #
$requestId
- Workflow: 
$workflowTitle
- Current State: 
$stateTitle";

    if (!
$isCompletion && $requesterName) {
        
$text .= "
- Requested by: 
$requesterName";
    }

    
$text .= "

$actionText$requestUrl

---
This is an automated message from " 
COMPANY_NAME ".
© " 
date('Y') . " " COMPANY_NAME ". All rights reserved.
"
;

    return 
$text;
}

/**
 * Get base URL for email links
 */
function get_base_url() {
    
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' 'https' 'http';
    
$host $_SERVER['HTTP_HOST'] ?? 'localhost';
    
$path dirname($_SERVER['SCRIPT_NAME']);
    return 
$protocol '://' $host $path;
}

/**
 * Send notification emails to actors using PHPMailer
 */
function send_actor_notification_emails_phpmailer($conn$stateId$requestId$workflowTitle$stateTitle$requesterName) {
    if (!
ENABLE_EMAIL_NOTIFICATIONS) {
        return;
    }
    
    
// Get actors for this state
    
$actorSql "
        SELECT sa.actorType, sa.fk_User, sa.fk_Group
        FROM TICKET_StateActor sa
        WHERE sa.fk_State = ?
    "
;
    
$actorStmt mysqli_prepare($conn$actorSql);
    
mysqli_stmt_bind_param($actorStmt'i'$stateId);
    
mysqli_stmt_execute($actorStmt);
    
$actorResult mysqli_stmt_get_result($actorStmt);
    
    
$emailsSent 0;
    
$emailsFailed 0;
    
    while (
$actor mysqli_fetch_assoc($actorResult)) {
        if (
$actor['actorType'] === 'USER' && $actor['fk_User']) {
            
// Send email to specific user
            
$userSql "SELECT email, firstName, lastName FROM TICKET_User WHERE pk_User = ? AND email IS NOT NULL";
            
$userStmt mysqli_prepare($conn$userSql);
            
mysqli_stmt_bind_param($userStmt'i'$actor['fk_User']);
            
mysqli_stmt_execute($userStmt);
            
mysqli_stmt_bind_result($userStmt$email$firstName$lastName);
            if (
mysqli_stmt_fetch($userStmt) && $email) {
                if (
send_notification_email_phpmailer(
                    
$email
                    
$firstName ' ' $lastName
                    
$requestId
                    
$workflowTitle
                    
$stateTitle
                    
false
                    
$requesterName
                
)) {
                    
$emailsSent++;
                } else {
                    
$emailsFailed++;
                }
            }
            
mysqli_stmt_close($userStmt);
            
        } elseif (
$actor['actorType'] === 'GROUP' && $actor['fk_Group']) {
            
// Send email to all users in group
            
$groupUsersSql "SELECT email, firstName, lastName FROM TICKET_User WHERE fk_Group = ? AND email IS NOT NULL";
            
$groupUsersStmt mysqli_prepare($conn$groupUsersSql);
            
mysqli_stmt_bind_param($groupUsersStmt'i'$actor['fk_Group']);
            
mysqli_stmt_execute($groupUsersStmt);
            
$groupUsersResult mysqli_stmt_get_result($groupUsersStmt);
            
            while (
$groupUser mysqli_fetch_assoc($groupUsersResult)) {
                if (
send_notification_email_phpmailer(
                    
$groupUser['email'], 
                    
$groupUser['firstName'] . ' ' $groupUser['lastName'], 
                    
$requestId
                    
$workflowTitle
                    
$stateTitle
                    
false
                    
$requesterName
                
)) {
                    
$emailsSent++;
                } else {
                    
$emailsFailed++;
                }
            }
            
mysqli_stmt_close($groupUsersStmt);
        }
    }
    
mysqli_stmt_close($actorStmt);
    
    
// Log summary
    
error_log("Email notification summary for request #$requestId$emailsSent sent, $emailsFailed failed");
}

/**
 * Send completion notification email to requester using PHPMailer
 */
function send_completion_notification_email_phpmailer($conn$requestId$workflowTitle$stateTitle$creatorUserId) {
    if (!
ENABLE_EMAIL_NOTIFICATIONS) {
        return;
    }
    
    
$userSql "SELECT email, firstName, lastName FROM TICKET_User WHERE pk_User = ? AND email IS NOT NULL";
    
$userStmt mysqli_prepare($conn$userSql);
    
mysqli_stmt_bind_param($userStmt'i'$creatorUserId);
    
mysqli_stmt_execute($userStmt);
    
mysqli_stmt_bind_result($userStmt$email$firstName$lastName);
    if (
mysqli_stmt_fetch($userStmt) && $email) {
        
$result send_notification_email_phpmailer(
            
$email
            
$firstName ' ' $lastName
            
$requestId
            
$workflowTitle
            
$stateTitle
            
true
        
);
        
        if (
$result) {
            
error_log("Completion email sent successfully for request #$requestId to $email");
        } else {
            
error_log("Failed to send completion email for request #$requestId to $email");
        }
    }
    
mysqli_stmt_close($userStmt);
}

/**
 * Test email configuration
 */
function test_email_configuration($testEmail null) {
    if (!
$testEmail) {
        
$testEmail SMTP_USERNAME;
    }
    
    
$mail create_mailer();
    if (!
$mail) {
        return [
'success' => false'message' => 'Failed to create mailer instance'];
    }
    
    try {
        
$mail->addAddress($testEmail'Test User');
        
$mail->Subject 'Ticket System - Email Configuration Test';
        
$mail->Body '
        <h2>Email Configuration Test</h2>
        <p>If you receive this email, your PHPMailer SMTP configuration is working correctly!</p>
        <p>Test sent at: ' 
date('Y-m-d H:i:s') . '</p>
        '
;
        
$mail->AltBody 'Email configuration test - if you receive this, PHPMailer is working correctly!';
        
        
$result $mail->send();
        
        return [
            
'success' => true
            
'message' => 'Test email sent successfully to ' $testEmail
        
];
        
    } catch (
Exception $e) {
        return [
            
'success' => false
            
'message' => 'Test email failed: ' $e->getMessage()
        ];
    }
}
?>