<?php
/**
 * Email Functions
 * Email functions for the ticketing system using SMTP
 */

require_once 'email_config.php';

// Function to send email using SMTP
function sendEmail($to, $subject, $message, $from = NO_REPLY_EMAIL) {
    // Suppress warnings in development
    // In production, configure SMTP settings in email_config.php
    return @mail($to, $subject, $message, buildEmailHeaders($from));
}

// Function to build email headers
function buildEmailHeaders($from) {
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: " . $from . "\r\n";
    $headers .= "Reply-To: " . $from . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    return $headers;
}

// Function to notify customer when ticket is created
function notifyTicketCreated($pdo, $ticket_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Prepare email
    $subject = "Support Ticket #" . $ticket_id . " Created";
    $message = getTicketCreatedEmailTemplate($ticket_id, $ticket['subject'], $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify customer when ticket status is updated
function notifyTicketStatusUpdated($pdo, $ticket_id, $old_status, $new_status) {
    // Only notify if status actually changed
    if ($old_status === $new_status) {
        return true;
    }
    
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Prepare email
    $subject = "Support Ticket #" . $ticket_id . " Status Updated";
    $message = getTicketStatusUpdatedEmailTemplate($ticket_id, $ticket['subject'], $new_status, $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify customer when there's a new reply
function notifyNewReply($pdo, $ticket_id, $reply_author_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Get reply author details
    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$reply_author_id]);
    $reply_author = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$reply_author) {
        return false;
    }
    
    // Prepare email
    $subject = "New Reply to Support Ticket #" . $ticket_id;
    $message = getNewReplyEmailTemplate($ticket_id, $ticket['subject'], $reply_author['username'], $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify support agents of new ticket
function notifyNewTicketToAgents($pdo, $ticket_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Get all support agents/admins
    $stmt = $pdo->query("SELECT email, username FROM users WHERE role = 'admin'");
    $agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $success = true;
    
    foreach ($agents as $agent) {
        $subject = "New Support Ticket #" . $ticket_id . " Created";
        $message = "
        <html>
        <body>
            <h2>New Support Ticket</h2>
            <p>Hello {$agent['username']},</p>
            <p>A new support ticket has been created.</p>
            <p><strong>Ticket Details:</strong></p>
            <ul>
                <li>Ticket ID: #{$ticket_id}</li>
                <li>Customer: {$ticket['customer_name']}</li>
                <li>Type: {$ticket['type_name']}</li>
                <li>Subject: {$ticket['subject']}</li>
                <li>Priority: {$ticket['priority']}</li>
            </ul>
            <p>Please log in to the admin panel to view and respond to this ticket.</p>
            <p>Best regards,<br>The System</p>
        </body>
        </html>
        ";
        
        if (!sendEmail($agent['email'], $subject, $message, SUPPORT_EMAIL)) {
            $success = false;
        }
    }
    
    return $success;
}
?>