<?php
ob_start();
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Function to send ticket reply notification email
function sendTicketReplyNotificationEmail($to, $name, $ticket_id, $subject, $message, $priority, $admin_name) {
    // Log the function call
    error_log("Attempting to send ticket reply notification email to: $to");
    
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.firstnationalbankinc.com/logo.png';
    $bankColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#0066cc';
    $currentYear = date('Y');
    
    // Set priority color
    $priorityColors = [
        'low' => '#28a745', // Green
        'medium' => '#ffc107', // Yellow
        'high' => '#dc3545' // Red
    ];
    $priorityColor = $priorityColors[$priority] ?? $priorityColors['medium'];
    
    $emailSubject = "Update on Your Support Ticket #$ticket_id: $subject";
    
    // Format the date properly
    $formattedDate = date('F j, Y, g:i a');
    
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Ticket Update</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            border: 1px solid #dddddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .email-header {
            background-color: $bankColor;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 200px;
            height: auto;
        }
        .email-body {
            padding: 20px 30px;
        }
        .email-footer {
            background-color: #f8f8f8;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666666;
            border-top: 1px solid #dddddd;
        }
        h1 {
            color: $bankColor;
            margin-top: 0;
        }
        .ticket-details {
            background-color: #f9f9f9;
            border-left: 4px solid $bankColor;
            padding: 15px;
            margin: 20px 0;
        }
        .ticket-message {
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            padding: 15px;
            margin: 15px 0;
            border-radius: 4px;
        }
        .priority-badge {
            display: inline-block;
            background-color: $priorityColor;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .button {
            display: inline-block;
            background-color: $bankColor;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 4px;
            margin: 20px 0;
            font-weight: bold;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            width: 30%;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
        </div>
        <div class="email-body">
            <h1>Support Ticket Update</h1>
            <p>Dear $name,</p>
            <p>There has been a new reply to your support ticket. Our team is working to assist you.</p>
            
            <div class="ticket-details">
                <h2>Ticket Details</h2>
                <table>
                    <tr>
                        <th>Ticket ID</th>
                        <td>#$ticket_id</td>
                    </tr>
                    <tr>
                        <th>Subject</th>
                        <td>$subject</td>
                    </tr>
                    <tr>
                        <th>Priority</th>
                        <td><span class="priority-badge" style="background-color: $priorityColor;">$priority</span></td>
                    </tr>
                    <tr>
                        <th>Updated On</th>
                        <td>$formattedDate</td>
                    </tr>
                    <tr>
                        <th>Reply From</th>
                        <td>$admin_name</td>
                    </tr>
                </table>
            </div>
            
            <div class="ticket-message">
                <h3>New Reply:</h3>
                <p>$message</p>
            </div>
            
            <p>You can view and respond to this ticket by clicking the button below or logging into your account.</p>
            
            <div style="text-align: center;">
                <a href="{$_SERVER['HTTP_ORIGIN']}/user/view_ticket.php?id=$ticket_id" class="button" style="color: white;">View Ticket</a>

            </div>
            
            <p>If you have any questions or need further assistance, please don't hesitate to contact our support team.</p>
            
            <p>Thank you for your patience.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        <div class="email-footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;
    
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : $bankName;
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'info@firstnationalbankinc.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Log the email details
    error_log("Email details: To: $to, Subject: $emailSubject, From: $fromName <$fromEmail>");
    
    // Save a copy of the email to a file for debugging
    $logDir = "../logs";
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $emailLog = fopen("$logDir/ticket_reply_email_" . time() . ".html", "w");
    if ($emailLog) {
        fwrite($emailLog, "To: $to\nSubject: $emailSubject\nHeaders: $headers\n\n$emailBody");
        fclose($emailLog);
        error_log("Email content saved to log file");
    }
    
    // Try to send email
    try {
        $result = mail($to, $emailSubject, $emailBody, $headers);
        error_log("PHP mail() result: " . ($result ? "Success" : "Failed"));
        return $result;
    } catch (Exception $e) {
        error_log("Error sending ticket reply notification email: " . $e->getMessage());
        return false;
    }
}

// Function to send ticket status change notification email
function sendTicketStatusChangeEmail($to, $name, $ticket_id, $subject, $new_status, $priority, $admin_name) {
    // Log the function call
    error_log("Attempting to send ticket status change notification email to: $to");
    
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.firstnationalbankinc.com/logo.png';
    $bankColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#0066cc';
    $currentYear = date('Y');
    
    // Set priority color
    $priorityColors = [
        'low' => '#28a745', // Green
        'medium' => '#ffc107', // Yellow
        'high' => '#dc3545' // Red
    ];
    $priorityColor = $priorityColors[$priority] ?? $priorityColors['medium'];
    
    // Set status color
    $statusColors = [
        'open' => '#0284c7', // Blue
        'in_progress' => '#f59e0b', // Orange
        'closed' => '#10b981' // Green
    ];
    $statusColor = $statusColors[$new_status] ?? $statusColors['open'];
    $displayStatus = ucfirst(str_replace('_', ' ', $new_status));
    
    $emailSubject = "Status Update: Support Ticket #$ticket_id: $subject";
    
    // Format the date properly
    $formattedDate = date('F j, Y, g:i a');
    
    // Status-specific message
    $statusMessage = '';
    if ($new_status == 'closed') {
        $statusMessage = 'This ticket has been marked as resolved. If you feel your issue has not been fully addressed, you can reopen the ticket by responding to it.';
    } else if ($new_status == 'in_progress') {
        $statusMessage = 'Our support team is currently working on your ticket. We\'ll update you as soon as there\'s progress.';
    } else if ($new_status == 'open') {
        $statusMessage = 'Your ticket has been reopened and is awaiting attention from our support team.';
    }
    
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Ticket Status Update</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            border: 1px solid #dddddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .email-header {
            background-color: $bankColor;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 200px;
            height: auto;
        }
        .email-body {
            padding: 20px 30px;
        }
        .email-footer {
            background-color: #f8f8f8;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666666;
            border-top: 1px solid #dddddd;
        }
        h1 {
            color: $bankColor;
            margin-top: 0;
        }
        .ticket-details {
            background-color: #f9f9f9;
            border-left: 4px solid $bankColor;
            padding: 15px;
            margin: 20px 0;
        }
        .status-message {
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            padding: 15px;
            margin: 15px 0;
            border-radius: 4px;
        }
        .priority-badge {
            display: inline-block;
            background-color: $priorityColor;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .status-badge {
            display: inline-block;
            background-color: $statusColor;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .button {
            display: inline-block;
            background-color: $bankColor;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 4px;
            margin: 20px 0;
            font-weight: bold;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            width: 30%;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
        </div>
        <div class="email-body">
            <h1>Support Ticket Status Update</h1>
            <p>Dear $name,</p>
            <p>The status of your support ticket has been updated.</p>
            
            <div class="ticket-details">
                <h2>Ticket Details</h2>
                <table>
                    <tr>
                        <th>Ticket ID</th>
                        <td>#$ticket_id</td>
                    </tr>
                    <tr>
                        <th>Subject</th>
                        <td>$subject</td>
                    </tr>
                    <tr>
                        <th>Priority</th>
                        <td><span class="priority-badge" style="background-color: $priorityColor;">$priority</span></td>
                    </tr>
                    <tr>
                        <th>New Status</th>
                        <td><span class="status-badge" style="background-color: $statusColor;">$displayStatus</span></td>
                    </tr>
                    <tr>
                        <th>Updated On</th>
                        <td>$formattedDate</td>
                    </tr>
                    <tr>
                        <th>Updated By</th>
                        <td>$admin_name</td>
                    </tr>
                </table>
            </div>
            
            <div class="status-message">
                <h3>Status Information:</h3>
                <p>$statusMessage</p>
            </div>
            
            <p>You can view and respond to this ticket by clicking the button below or logging into your account.</p>
            
            <div style="text-align: center;">
               <a href="{$_SERVER['HTTP_ORIGIN']}/user/view_ticket.php?id=$ticket_id" class="button" style="color: white;">View Ticket</a>

            </div>
            
            <p>If you have any questions or need further assistance, please don't hesitate to contact our support team.</p>
            
            <p>Thank you for your patience.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        <div class="email-footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;
    
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : $bankName;
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'info@firstnationalbankinc.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Log the email details
    error_log("Email details: To: $to, Subject: $emailSubject, From: $fromName <$fromEmail>");
    
    // Save a copy of the email to a file for debugging
    $logDir = "../logs";
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $emailLog = fopen("$logDir/ticket_status_email_" . time() . ".html", "w");
    if ($emailLog) {
        fwrite($emailLog, "To: $to\nSubject: $emailSubject\nHeaders: $headers\n\n$emailBody");
        fclose($emailLog);
        error_log("Email content saved to log file");
    }
    
    // Try to send email
    try {
        $result = mail($to, $emailSubject, $emailBody, $headers);
        error_log("PHP mail() result: " . ($result ? "Success" : "Failed"));
        return $result;
    } catch (Exception $e) {
        error_log("Error sending ticket status change notification email: " . $e->getMessage());
        return false;
    }
}

// Check for success message in cookie
$cookie_success_message = $_COOKIE['ticket_success_message'] ?? null;
if ($cookie_success_message) {
    // Set the message in the session so it can be displayed
    $_SESSION['success_message'] = $cookie_success_message;
    // Clear the cookie
    setcookie('ticket_success_message', '', time() - 3600, '/');
}

// Get ticket ID from URL
$ticket_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$ticket_id) {
    $_SESSION['error_message'] = "Invalid ticket ID.";
    header("Location: tickets.php");
    exit();
}

// Initialize database connection
$database = new Database();
$db = $database->getConnection();

// Process reply form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    try {
        // Get the message from the form
        $message = trim($_POST['message']);
        
        if (empty($message)) {
            throw new Exception("Reply message cannot be empty.");
        }
        
        // Get current admin user ID with proper validation
        $admin_id = $_SESSION['user_id'] ?? null;
        
        // Verify that this admin_id exists in the users table
        $stmt = $db->prepare("SELECT id FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin_exists = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$admin_exists) {
            // Admin ID doesn't exist, find a valid admin user
            $stmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1");
            $stmt->execute();
            $admin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($admin) {
                $admin_id = $admin['id'];
                error_log("Using alternative admin ID: " . $admin_id);
            } else {
                // If no admin found, try to use the ticket owner's ID
                $stmt = $db->prepare("SELECT user_id FROM tickets WHERE id = ?");
                $stmt->execute([$ticket_id]);
                $ticket_owner = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($ticket_owner) {
                    $admin_id = $ticket_owner['user_id'];
                    error_log("No admin found, using ticket owner ID: " . $admin_id);
                } else {
                    throw new Exception("Could not find a valid user ID to associate with this reply.");
                }
            }
        }
        
        // Begin transaction
        $db->beginTransaction();
        
        // Insert the reply
        $stmt = $db->prepare("
            INSERT INTO ticket_messages (ticket_id, sender_id, message, is_admin, created_at)
            VALUES (?, ?, ?, 1, NOW())
        ");
        $stmt->execute([$ticket_id, $admin_id, $message]);
        
        // Update the ticket's updated_at timestamp
        $stmt = $db->prepare("UPDATE tickets SET updated_at = NOW() WHERE id = ?");
        $stmt->execute([$ticket_id]);
        
        // Get user email and ticket details for notification
        $stmt = $db->prepare("
            SELECT u.email, u.first_name, u.last_name, t.subject, t.priority 
            FROM users u
            JOIN tickets t ON u.id = t.user_id
            WHERE t.id = ?
        ");
        $stmt->execute([$ticket_id]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Get admin name
        $stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $admin_name = $admin_data ? ($admin_data['first_name'] . ' ' . $admin_data['last_name']) : 'Support Team';
        
        // Commit transaction
        $db->commit();
        
        // Set success message
        $successMessage = "Your reply has been sent successfully.";
        
        // Send email notification if we have user email
        if ($user_data && !empty($user_data['email'])) {
            $userName = $user_data['first_name'] . ' ' . $user_data['last_name'];
            error_log("Attempting to send reply notification email to: " . $user_data['email'] . " for user: " . $userName);
            
            $emailSent = sendTicketReplyNotificationEmail(
                $user_data['email'],
                $userName,
                $ticket_id,
                $user_data['subject'],
                $message,
                $user_data['priority'],
                $admin_name
            );
            
            if ($emailSent) {
                error_log("Ticket reply notification email sent to user: " . $user_data['email']);
                $successMessage .= " Email notification has been sent to the user.";
            } else {
                error_log("Failed to send ticket reply notification email");
                $successMessage .= " However, the email notification could not be sent.";
            }
        } else {
            error_log("User email not found, skipping email notification");
            $successMessage .= " No email was sent because the user does not have an email address.";
        }
        
        $_SESSION['success_message'] = $successMessage;
        
        // Redirect to the same page to prevent form resubmission
        if (!headers_sent()) {
            header("Location: ticket_details.php?id=$ticket_id");
            exit();
        } else {
            echo "<script>window.location.href = 'ticket_details.php?id=$ticket_id';</script>";
            exit();
        }
        
    } catch (Exception $e) {
        // Rollback transaction if there was an error
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        
        $_SESSION['error_message'] = "Error sending reply: " . $e->getMessage();
        error_log("Ticket reply error: " . $e->getMessage());
        
        // Redirect to the same page
        if (!headers_sent()) {
            header("Location: ticket_details.php?id=$ticket_id");
            exit();
        } else {
            echo "<script>window.location.href = 'ticket_details.php?id=$ticket_id';</script>";
            exit();
        }
    }
 catch (Exception $e) {
        // Rollback transaction if there was an error
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        
        $_SESSION['error_message'] = "Error sending reply: " . $e->getMessage();
        
        // Redirect to the same page
        header("Location: ticket_details.php?id=$ticket_id");
        exit();
    }
}

// Process status change
if (isset($_GET['change_status']) && in_array($_GET['change_status'], ['open', 'in_progress', 'closed'])) {
    try {
        $new_status = $_GET['change_status'];
        
        // Get current admin user ID with proper validation
        $admin_id = $_SESSION['user_id'] ?? null;
        
        // Verify that this admin_id exists in the users table
        $stmt = $db->prepare("SELECT id FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin_exists = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$admin_exists) {
            // Admin ID doesn't exist, find a valid admin user
            $stmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1");
            $stmt->execute();
            $admin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($admin) {
                $admin_id = $admin['id'];
                error_log("Using alternative admin ID: " . $admin_id);
            } else {
                // If no admin found, try to use the ticket owner's ID
                $stmt = $db->prepare("SELECT user_id FROM tickets WHERE id = ?");
                $stmt->execute([$ticket_id]);
                $ticket_owner = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($ticket_owner) {
                    $admin_id = $ticket_owner['user_id'];
                    error_log("No admin found, using ticket owner ID: " . $admin_id);
                } else {
                    throw new Exception("Could not find a valid user ID to associate with this status change.");
                }
            }
        }
        
        // Begin transaction
        $db->beginTransaction();
        
        // Update ticket status
        $stmt = $db->prepare("UPDATE tickets SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$new_status, $ticket_id]);
        
        // Add a system message about the status change
        $status_message = "Ticket status changed to " . ucfirst(str_replace('_', ' ', $new_status));
        $stmt = $db->prepare("
            INSERT INTO ticket_messages (ticket_id, sender_id, message, is_admin, created_at)
            VALUES (?, ?, ?, 1, NOW())
        ");
        $stmt->execute([$ticket_id, $admin_id, $status_message]);
        
        // Get user email and ticket details for notification
        $stmt = $db->prepare("
            SELECT u.email, u.first_name, u.last_name, t.subject, t.priority 
            FROM users u
            JOIN tickets t ON u.id = t.user_id
            WHERE t.id = ?
        ");
        $stmt->execute([$ticket_id]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Get admin name
        $stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $admin_name = $admin_data ? ($admin_data['first_name'] . ' ' . $admin_data['last_name']) : 'Support Team';
        
        // Commit transaction
        $db->commit();
        
        // Set success message
        $successMessage = "Ticket status updated successfully.";
        
        // Send email notification if we have user email
        if ($user_data && !empty($user_data['email'])) {
            $userName = $user_data['first_name'] . ' ' . $user_data['last_name'];
            error_log("Attempting to send status change notification email to: " . $user_data['email'] . " for user: " . $userName);
            
            $emailSent = sendTicketStatusChangeEmail(
                $user_data['email'],
                $userName,
                $ticket_id,
                $user_data['subject'],
                $new_status,
                $user_data['priority'],
                $admin_name
            );
            
            if ($emailSent) {
                error_log("Ticket status change notification email sent to user: " . $user_data['email']);
                $successMessage .= " Email notification has been sent to the user.";
            } else {
                error_log("Failed to send ticket status change notification email");
                $successMessage .= " However, the email notification could not be sent.";
            }
        } else {
            error_log("User email not found, skipping email notification");
            $successMessage .= " No email was sent because the user does not have an email address.";
        }
        
        $_SESSION['success_message'] = $successMessage;
        
        // Redirect to the same page to refresh data
        if (!headers_sent()) {
            header("Location: ticket_details.php?id=$ticket_id");
            exit();
        } else {
            echo "<script>window.location.href = 'ticket_details.php?id=$ticket_id';</script>";
            exit();
        }
        
    } catch (Exception $e) {
        // Rollback transaction if there was an error
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        
        $_SESSION['error_message'] = "Error updating ticket status: " . $e->getMessage();
        error_log("Ticket status change error: " . $e->getMessage());
        
        // Redirect to the same page
        if (!headers_sent()) {
            header("Location: ticket_details.php?id=$ticket_id");
            exit();
        } else {
            echo "<script>window.location.href = 'ticket_details.php?id=$ticket_id';</script>";
            exit();
        }
    }
}

// Fetch ticket details
try {
    $stmt = $db->prepare("
        SELECT t.*, u.first_name, u.last_name, u.email, u.username 
        FROM tickets t
        JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        $_SESSION['error_message'] = "Ticket not found.";
        header("Location: tickets.php");
        exit();
    }
    
    // Fetch ticket messages
    $stmt = $db->prepare("
        SELECT tm.*, u.first_name, u.last_name, u.email, u.username 
        FROM ticket_messages tm
        JOIN users u ON tm.sender_id = u.id
        WHERE tm.ticket_id = ?
        ORDER BY tm.created_at ASC
    ");
    $stmt->execute([$ticket_id]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $_SESSION['error_message'] = "Error retrieving ticket details: " . $e->getMessage();
    header("Location: tickets.php");
    exit();
}

// Set page title
$page_title = "Ticket #" . $ticket_id . ": " . $ticket['subject'];
$page = 'tickets';

include 'includes/header.php';
ob_end_flush();
?>

<style>
/* Ticket Details Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --secondary-color: #0ea5e9;
    --secondary-light: #e0f2fe;
    --success-color: #10b981;
    --success-light: #d1fae5;
    --warning-color: #f59e0b;
    --warning-light: #fef3c7;
    --danger-color: #ef4444;
    --danger-light: #fee2e2;
    --gray-50: #f9fafb;
    --gray-100: #f3f4f6;
    --gray-200: #e5e7eb;
    --gray-300: #d1d5db;
    --gray-400: #9ca3af;
    --gray-500: #6b7280;
    --gray-600: #4b5563;
    --gray-700: #374151;
    --gray-800: #1f2937;
    --gray-900: #111827;
    --border-radius: 0.5rem;
    --box-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);
}

.message-bubble {
    padding: 1.25rem;
    border-radius: var(--border-radius);
    margin-bottom: 1.5rem;
    background-color: white;
    box-shadow: var(--box-shadow);
    position: relative;
}

.message-bubble.admin {
    border-left: 4px solid var(--primary-color);
}

.message-bubble.user {
    border-left: 4px solid var(--secondary-color);
}

.message-bubble.system {
    background-color: var(--gray-50);
    border-left: 4px solid var(--gray-400);
    font-style: italic;
    color: var(--gray-600);
}

.message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.75rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid var(--gray-200);
}

.message-sender {
    font-weight: 600;
    color: var(--gray-800);
    display: flex;
    align-items: center;
}

.sender-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 0.75rem;
    font-weight: 600;
}

.admin-avatar {
    background-color: var(--primary-light);
    color: var(--primary-color);
}

.user-avatar {
    background-color: var(--secondary-light);
    color: var(--secondary-color);
}

.message-time {
    color: var(--gray-500);
    font-size: 0.875rem;
}

.message-content {
    white-space: pre-line;
    color: var(--gray-700);
}

.status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 600;
}

.status-badge.open {
    background-color: var(--secondary-light);
    color: var(--secondary-color);
}

.status-badge.in_progress {
    background-color: var(--warning-light);
    color: var(--warning-color);
}

.status-badge.closed {
    background-color: var(--success-light);
    color: var(--success-color);
}

.priority-badge {
    padding: 0.15rem 0.5rem;
    border-radius: 9999px;
    font-size: 0.75rem;
}

.priority-high {
    background-color: var(--danger-light);
    color: var(--danger-color);
}

.priority-medium {
    background-color: var(--warning-light);
    color: var(--warning-color);
}

.priority-low {
    background-color: var(--gray-100);
    color: var(--gray-600);
}
</style>
<div class="container-fluid">
    <!-- Display Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
<!-- Main Content Area -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center">
        <a href="tickets.php" class="btn btn-outline-secondary me-3">
            <i class='bx bx-arrow-back'></i>
        </a>
        <div>
            <h1 class="h3 mb-0">Ticket #<?php echo $ticket_id; ?></h1>
            <p class="text-muted mb-0"><?php echo htmlspecialchars($ticket['subject']); ?></p>
        </div>
    </div>
    <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="statusDropdown" data-bs-toggle="dropdown" aria-expanded="false">
            Change Status
        </button>
        <ul class="dropdown-menu" aria-labelledby="statusDropdown">
            <li><a class="dropdown-item" href="ticket_details.php?id=<?php echo $ticket_id; ?>&change_status=open">Mark as Open</a></li>
            <li><a class="dropdown-item" href="ticket_details.php?id=<?php echo $ticket_id; ?>&change_status=in_progress">Mark as In Progress</a></li>
            <li><a class="dropdown-item" href="ticket_details.php?id=<?php echo $ticket_id; ?>&change_status=closed">Mark as Closed</a></li>
        </ul>
    </div>
</div>
<?php if (isset($error_message)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $error_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Left Column - Ticket Details and Messages -->
    <div class="col-lg-8">
        <!-- Ticket Information Card -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Ticket Information</h5>
                <span class="status-badge <?php echo $ticket['status']; ?>">
                    <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                </span>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-3 fw-bold">Subject:</div>
                    <div class="col-md-9"><?php echo htmlspecialchars($ticket['subject']); ?></div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-3 fw-bold">Priority:</div>
                    <div class="col-md-9">
                        <span class="priority-badge priority-<?php echo $ticket['priority']; ?>">
                            <?php echo ucfirst($ticket['priority']); ?>
                        </span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-3 fw-bold">Created:</div>
                    <div class="col-md-9"><?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></div>
                </div>
                <div class="row">
                    <div class="col-md-3 fw-bold">Last Updated:</div>
                    <div class="col-md-9"><?php echo date('M j, Y g:i A', strtotime($ticket['updated_at'] ?? $ticket['created_at'])); ?></div>
                </div>
            </div>
        </div>

        <!-- Conversation Card -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Conversation</h5>
            </div>
            <div class="card-body">
                <?php if (empty($messages)): ?>
                    <div class="text-center py-5">
                        <i class='bx bx-message-detail' style="font-size: 4rem; color: #d1d5db;"></i>
                        <h5 class="mt-3">No Messages Yet</h5>
                        <p class="text-muted">This ticket doesn't have any messages yet.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($messages as $message): ?>
                        <?php 
                        $is_system_message = strpos($message['message'], 'Ticket status changed to') !== false;
                        $bubble_class = $is_system_message ? 'system' : ($message['is_admin'] ? 'admin' : 'user');
                        ?>
                        <div class="message-bubble <?php echo $bubble_class; ?>">
                            <div class="message-header">
                                <div class="message-sender">
                                    <?php if ($is_system_message): ?>
                                        <div class="sender-avatar" style="background-color: #e5e7eb; color: #4b5563;">
                                            <i class='bx bx-info-circle'></i>
                                        </div>
                                        System Message
                                    <?php elseif ($message['is_admin']): ?>
                                        <div class="sender-avatar admin-avatar">
                                            <i class='bx bx-shield-quarter'></i>
                                        </div>
                                        Support Team
                                    <?php else: ?>
                                        <div class="sender-avatar user-avatar">
                                            <?php echo strtoupper(substr($message['first_name'], 0, 1)); ?>
                                        </div>
                                        <?php echo htmlspecialchars($message['first_name'] . ' ' . $message['last_name']); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="message-time">
                                    <?php echo date('M j, Y g:i A', strtotime($message['created_at'])); ?>
                                </div>
                            </div>
                            <div class="message-content">
                                <?php echo nl2br(htmlspecialchars($message['message'])); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Reply Form -->
        <?php if ($ticket['status'] !== 'closed'): ?>
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">Reply to Ticket</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="ticket_details.php?id=<?php echo $ticket_id; ?>">
                        <div class="mb-3">
                            <label for="canned-responses" class="form-label">Canned Responses</label>
                            <select class="form-select" id="canned-responses">
                                <option value="">Select a response...</option>
                                <option value="Thank you for contacting our support team. We're looking into your issue and will get back to you shortly.">General Acknowledgment</option>
                                <option value="Your issue has been resolved. Please let us know if you need any further assistance.">Issue Resolved</option>
                                <option value="We need more information to assist you better. Could you please provide more details about your issue?">Request More Info</option>
                                <option value="I'm transferring your ticket to our specialized team who will be better equipped to help you with this issue.">Transfer to Specialist</option>
                                <option value="We apologize for the inconvenience this has caused. We're working to resolve this as quickly as possible.">Apology</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="message" class="form-label">Your Reply</label>
                            <textarea class="form-control" id="message" name="message" rows="4" required></textarea>
                        </div>
                        <div class="text-end">
                            <button type="submit" name="reply" class="btn btn-primary">Send Reply</button>
                        </div>
                    </form>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-info mt-4">
                <i class='bx bx-info-circle me-2'></i> This ticket is closed. You can reopen it by changing its status to "Open" or "In Progress".
            </div>
        <?php endif; ?>
    </div>

    <!-- Right Column - Customer Info and Quick Actions -->
    <div class="col-lg-4">
        <!-- Customer Information Card -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Customer Information</h5>
            </div>
            <div class="card-body">
                <div class="d-flex align-items-center mb-3">
                    <div class="icon-circle bg-primary-light me-3" style="width: 48px; height: 48px; font-size: 1.25rem;">
                        <?php echo strtoupper(substr($ticket['first_name'], 0, 1)); ?>
                    </div>
                    <div>
                        <h6 class="mb-0"><?php echo htmlspecialchars($ticket['first_name'] . ' ' . $ticket['last_name']); ?></h6>
                        <span class="text-muted"><?php echo htmlspecialchars($ticket['email']); ?></span>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="row mb-2">
                        <div class="col-5 fw-bold">Account:</div>
                        <div class="col-7"><?php echo htmlspecialchars($ticket['account_number'] ?? 'N/A'); ?></div>
                    </div>
                    <div class="row">
                        <div class="col-5 fw-bold">User ID:</div>
                        <div class="col-7"><?php echo $ticket['user_id']; ?></div>
                    </div>
                </div>
                <div class="d-grid">
                    <a href="user_details.php?id=<?php echo $ticket['user_id']; ?>" class="btn btn-outline-primary">
                        <i class='bx bx-user me-1'></i> View Full Profile
                    </a>
                </div>
            </div>
        </div>

        <!-- Quick Actions Card -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <?php if ($ticket['status'] !== 'closed'): ?>
                        <a href="ticket_details.php?id=<?php echo $ticket_id; ?>&change_status=closed" class="btn btn-outline-success">
                            <i class='bx bx-check-circle me-1'></i> Mark as Resolved
                        </a>
                    <?php else: ?>
                        <a href="ticket_details.php?id=<?php echo $ticket_id; ?>&change_status=open" class="btn btn-outline-warning">
                            <i class='bx bx-revision me-1'></i> Reopen Ticket
                        </a>
                    <?php endif; ?>
                    
                    <a href="tickets.php?user_id=<?php echo $ticket['user_id']; ?>" class="btn btn-outline-secondary">
                        <i class='bx bx-history me-1'></i> View Customer's Tickets
                    </a>
                    
                    <a href="tickets.php" class="btn btn-outline-secondary">
                        <i class='bx bx-arrow-back me-1'></i> Back to All Tickets
                    </a>
                </div>
            </div>
        </div>

        <!-- Ticket Timeline Card -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Ticket Timeline</h5>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <div class="list-group-item">
                        <div class="d-flex w-100 justify-content-between">
                            <h6 class="mb-1">Ticket Created</h6>
                            <small><?php echo date('M j, Y', strtotime($ticket['created_at'])); ?></small>
                        </div>
                        <small class="text-muted"><?php echo date('g:i A', strtotime($ticket['created_at'])); ?></small>
                    </div>
                    
                    <?php 
                    // Extract status changes from messages
                    $status_changes = [];
                    foreach ($messages as $msg) {
                        if (strpos($msg['message'], 'Ticket status changed to') !== false) {
                            $status_changes[] = [
                                'message' => $msg['message'],
                                'created_at' => $msg['created_at']
                            ];
                        }
                    }
                    
                    foreach ($status_changes as $change): 
                    ?>
                        <div class="list-group-item">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1"><?php echo htmlspecialchars($change['message']); ?></h6>
                                <small><?php echo date('M j, Y', strtotime($change['created_at'])); ?></small>
                            </div>
                            <small class="text-muted"><?php echo date('g:i A', strtotime($change['created_at'])); ?></small>
                        </div>
                    <?php endforeach; ?>
                    
                    <?php if ($ticket['updated_at'] && $ticket['updated_at'] !== $ticket['created_at']): ?>
                        <div class="list-group-item">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">Last Updated</h6>
                                <small><?php echo date('M j, Y', strtotime($ticket['updated_at'])); ?></small>
                            </div>
                            <small class="text-muted"><?php echo date('g:i A', strtotime($ticket['updated_at'])); ?></small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Canned responses functionality
    const cannedResponsesSelect = document.getElementById('canned-responses');
    const messageTextarea = document.getElementById('message');
    
    if (cannedResponsesSelect && messageTextarea) {
        cannedResponsesSelect.addEventListener('change', function() {
            if (this.value) {
                messageTextarea.value = this.value;
                messageTextarea.focus();
            }
        });
    }
});
</script>

<?php
// Include the footer
include 'includes/footer.php';
?>

