<?php session_start();
// bank_linking.php
include 'includes/head.php';

// Check ticket ID validity
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo "<script>
        window.location.href = 'tickets.php';
    </script>";
    exit;
}

$ticket_id = intval($_GET['id']);

// Get ticket details
$ticket_sql = "SELECT * FROM support_tickets WHERE id = '$ticket_id' AND user_id = '$user_id'";
$ticket_result = mysqli_query($conn, $ticket_sql);

if (mysqli_num_rows($ticket_result) == 0) {
    echo "<script>
        window.location.href = 'tickets.php';
    </script>";
    exit;
}

$ticket = mysqli_fetch_assoc($ticket_result);
$ticket_number = $ticket['ticket_number'];
$ticket_subject = $ticket['subject'];
$ticket_priority = $ticket['priority'];

// Get user details for notification
$userQuery = mysqli_query($conn, "SELECT first_name, last_name, email FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$email = $userData['email'];

// Get ticket replies
$replies_sql = "SELECT tr.*, u.username, u.email 
                FROM ticket_replies tr 
                LEFT JOIN users u ON tr.user_id = u.id 
                WHERE tr.ticket_id = '$ticket_id' 
                ORDER BY tr.created_at ASC";
$replies_result = mysqli_query($conn, $replies_sql);

// Handle new reply submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['new_reply'])) {
    $message = $conn->real_escape_string($_POST['message']);
    
    if (!empty($message)) {
        $reply_sql = "INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply) 
                      VALUES ('$ticket_id', '$user_id', '$message', 0)";
        
        if (mysqli_query($conn, $reply_sql)) {
            $reply_id = mysqli_insert_id($conn);
            
            // Update ticket updated_at timestamp
            $update_sql = "UPDATE support_tickets SET updated_at = NOW() WHERE id = '$ticket_id'";
            mysqli_query($conn, $update_sql);
            
            // NOTIFICATION: User Replied to Ticket (USER CONFIRMATION)
            $mail_subject = "Reply Added to Ticket #" . $ticket_number;
            $mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                
                                <p class='message'>
                                    ✅ <strong>Your reply has been added to support ticket #" . $ticket_number . "</strong><br>
                                    Our support team will review your message and respond as soon as possible.
                                </p>

                                <!-- Ticket Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Ticket Number:</strong> " . $ticket_number . "<br>
                                        <strong>Subject:</strong> " . htmlspecialchars($ticket_subject) . "<br>
                                        <strong>Priority:</strong> <span style='color: " . 
                                            ($ticket_priority == 'urgent' ? '#dc3545' : 
                                             ($ticket_priority == 'high' ? '#ffc107' : '#28a745')) . 
                                            "; font-weight: bold;'>" . ucfirst($ticket_priority) . "</span><br>
                                        <strong>Reply Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Reply ID:</strong> REPLY-" . $reply_id . "<br>
                                        <strong>Ticket Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>" . ucfirst($ticket['status']) . "</span>
                                    </div>
                                </div>

                                <!-- Your Message -->
                                <div class='message-section'>
                                    <h3 style='color: #2c3e50;'>Your Reply</h3>
                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                        <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($message)) . "</p>
                                    </div>
                                </div>

                                <!-- What Happens Next -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                                    <p style='color: #6c757d;'>Here's what you can expect:</p>
                                    <ul style='color: #6c757d;'>
                                        <li>Our support team will review your reply</li>
                                        <li>Average response time: 2-4 hours (business hours)</li>
                                        <li>You'll receive email notification when we respond</li>
                                        <li>You can track progress in your dashboard</li>
                                    </ul>
                                </div>

                                <!-- Action Buttons -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/ticket_details.php?id=" . $ticket_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View Ticket
                                    </a>
                                    <a href='" . $myUrl . "/support.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        Support Center
                                    </a>
                                </div>

                                <!-- Response Time -->
                                <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #0056b3;'>⏰ Response Time Expectations</h4>
                                    <p style='color: #0056b3;'>
                                        <strong>" . ucfirst($ticket_priority) . " Priority Ticket:</strong><br>
                                        " . ($ticket_priority == 'urgent' ? 
                                            'Response within 1 hour' : 
                                            ($ticket_priority == 'high' ? 
                                             'Response within 2-4 hours' : 
                                             'Response within 24 hours')) . "
                                    </p>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>Need immediate assistance?</p>
                                    <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Us Directly</a>
                                </div>
                            </div>";

            // Send user notification
            require_once("../proccess/mail_sender.php");

            // NOTIFICATION: User Replied to Ticket (ADMIN ALERT)
            $admin_mail_subject = "User Replied to Ticket #" . $ticket_number;
            $admin_mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>User Replied to Support Ticket</h2>
                                    
                                    <p class='message'>
                                        A user has added a new reply to their support ticket.
                                    </p>

                                    <!-- Ticket Details -->
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Ticket Number:</strong> " . $ticket_number . "<br>
                                            <strong>Ticket ID:</strong> " . $ticket_id . "<br>
                                            <strong>User ID:</strong> " . $user_id . "<br>
                                            <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                            <strong>User Email:</strong> " . $email . "<br>
                                            <strong>Subject:</strong> " . htmlspecialchars($ticket_subject) . "<br>
                                            <strong>Priority:</strong> <span style='color: " . 
                                                ($ticket_priority == 'urgent' ? '#dc3545' : 
                                                 ($ticket_priority == 'high' ? '#ffc107' : '#28a745')) . 
                                                "; font-weight: bold;'>" . ucfirst($ticket_priority) . "</span><br>
                                            <strong>Current Status:</strong> " . ucfirst($ticket['status']) . "<br>
                                            <strong>Reply Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>Reply ID:</strong> REPLY-" . $reply_id . "<br>
                                            <strong>Total Replies:</strong> " . (mysqli_num_rows($replies_result) + 2) . "
                                        </div>
                                    </div>

                                    <!-- User's Message -->
                                    <div class='message-section'>
                                        <h3 style='color: #2c3e50;'>User's Reply</h3>
                                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                            <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($message)) . "</p>
                                        </div>
                                    </div>

                                    <!-- Ticket History -->
                                    <div class='next-steps'>
                                        <h3 style='color: #2c3e50;'>Ticket History</h3>
                                        <p style='color: #6c757d;'>
                                            <strong>Created:</strong> " . date('M j, Y g:i A', strtotime($ticket['created_at'])) . "<br>
                                            <strong>Last Admin Reply:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT MAX(created_at) as last_reply FROM ticket_replies 
                                                     WHERE ticket_id='$ticket_id' AND is_admin_reply=1"))['last_reply'] ?? 'Never') . "<br>
                                            <strong>Response Time:</strong> " . 
                                                (isset($ticket['first_response_at']) ? 
                                                 round((strtotime($ticket['first_response_at']) - strtotime($ticket['created_at'])) / 3600, 1) . ' hours' : 'Pending') . "<br>
                                            <strong>Assigned To:</strong> " . 
                                                (isset($ticket['assigned_to']) ? 'Agent #' . $ticket['assigned_to'] : 'Unassigned') . "
                                        </p>
                                    </div>

                                    <!-- Admin Actions -->
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/support/ticket.php?id=" . $ticket_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            Respond to Ticket
                                        </a>
                                        <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View User Profile
                                        </a>
                                    </div>

                                    <!-- SLA Information -->
                                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #856404;'>⏰ SLA Reminder</h4>
                                        <p style='color: #856404;'>
                                            <strong>Priority: " . ucfirst($ticket_priority) . "</strong><br>
                                            " . ($ticket_priority == 'urgent' ? 
                                                'Response required within 1 hour' : 
                                                ($ticket_priority == 'high' ? 
                                                 'Response required within 4 hours' : 
                                                 'Response required within 24 hours')) . "<br>
                                            Current time: " . date('g:i A') . "
                                        </p>
                                    </div>

                                    <!-- Support Section -->
                                    <div class='support-section'>
                                        <p class='support-text'>Ticket requires attention.</p>
                                        <a href='" . $myUrl . "/admin/support/assign-ticket.php?id=" . $ticket_id . "' class='support-link'>Assign to Support Agent</a>
                                    </div>
                                </div>";

            // Send admin notification
            require_once("../proccess/admin_mailer.php");
            
            $success = "Reply added successfully!";
        } else {
            $error = "Failed to add reply: " . mysqli_error($conn);
        }
    } else {
        $error = "Please enter a message";
    }
}

// Handle ticket status update (if user can close/resolve)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_status'])) {
    $new_status = $conn->real_escape_string($_POST['status']);
    
    if (in_array($new_status, array('resolved', 'closed'))) {
        $status_sql = "UPDATE support_tickets SET status = '$new_status', updated_at = NOW() 
                       WHERE id = '$ticket_id' AND user_id = '$user_id'";
        
        if (mysqli_query($conn, $status_sql)) {
            
            // NOTIFICATION: Ticket Status Updated (USER)
            $mail_subject = "Ticket #" . $ticket_number . " Status Updated";
            $mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                
                                <p class='message'>
                                    " . ($new_status == 'resolved' ? 
                                        "✅ <strong>You marked ticket #" . $ticket_number . " as resolved!</strong><br>
                                        Thank you for confirming that your issue has been resolved." : 
                                        "🔒 <strong>You closed ticket #" . $ticket_number . ".</strong><br>
                                        This ticket is now closed and archived.") . "
                                </p>

                                <!-- Ticket Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Ticket Number:</strong> " . $ticket_number . "<br>
                                        <strong>Subject:</strong> " . htmlspecialchars($ticket_subject) . "<br>
                                        <strong>Previous Status:</strong> <span style='color: #17a2b8;'>" . ucfirst($ticket['status']) . "</span><br>
                                        <strong>New Status:</strong> <span style='color: #28a745; font-weight: bold;'>" . ucfirst($new_status) . "</span><br>
                                        <strong>Status Change Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Ticket Created:</strong> " . date('F j, Y', strtotime($ticket['created_at'])) . "<br>
                                        <strong>Total Replies:</strong> " . (mysqli_num_rows($replies_result) + 1) . "
                                    </div>
                                </div>

                                " . ($new_status == 'resolved' ? "
                                <!-- Resolution Confirmation -->
                                <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #155724;'>✅ Resolution Confirmed</h4>
                                    <p style='color: #155724;'>
                                        By marking this ticket as resolved, you've confirmed that:
                                    </p>
                                    <ul style='color: #155724;'>
                                        <li>Your issue has been addressed</li>
                                        <li>You're satisfied with the solution</li>
                                        <li>No further assistance is required</li>
                                    </ul>
                                </div>
                                " : "
                                <!-- Ticket Closed -->
                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #721c24;'>🔒 Ticket Closed</h4>
                                    <p style='color: #721c24;'>
                                        This ticket is now closed. Please note:
                                    </p>
                                    <ul style='color: #721c24;'>
                                        <li>No further replies can be added</li>
                                        <li>The ticket is archived for reference</li>
                                        <li>You can view it in your ticket history</li>
                                        <li>To reopen, create a new ticket</li>
                                    </ul>
                                </div>
                                ") . "

                                <!-- What's Next -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>What's Next?</h3>
                                    <p style='color: #6c757d;'>" . ($new_status == 'resolved' ? 
                                        "Your ticket will remain in your history for reference. If you have related issues, please create a new ticket." : 
                                        "The ticket conversation is saved. You can create a new ticket anytime for additional support.") . "</p>
                                </div>

                                <!-- Action Buttons -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/tickets.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View All Tickets
                                    </a>
                                    <a href='" . $myUrl . "/create_ticket.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        Create New Ticket
                                    </a>
                                </div>

                                <!-- Feedback Request -->
                                <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #0056b3;'>💬 How was your support experience?</h4>
                                    <p style='color: #0056b3;'>
                                        We value your feedback! Please take a moment to rate your support experience.
                                    </p>
                                    <div style='text-align: center; margin-top: 10px;'>
                                        <a href='" . $myUrl . "/feedback.php?ticket=" . $ticket_id . "' class='support-link' style='display: inline-block; padding: 10px 20px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            Leave Feedback
                                        </a>
                                    </div>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>Thank you for using " . $sitename . " support!</p>
                                    <a href='" . $myUrl . "/help' class='support-link'>Visit Help Center</a>
                                </div>
                            </div>";

            // Send user notification
            require_once("../proccess/mail_sender.php");

            // NOTIFICATION: Ticket Status Updated (ADMIN)
            $admin_mail_subject = "Ticket #" . $ticket_number . " Status Updated by User";
            $admin_mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>Ticket Status Updated by User</h2>
                                    
                                    <p class='message'>
                                        A user has updated the status of their support ticket.
                                    </p>

                                    <!-- Ticket Details -->
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Ticket Number:</strong> " . $ticket_number . "<br>
                                            <strong>Ticket ID:</strong> " . $ticket_id . "<br>
                                            <strong>User ID:</strong> " . $user_id . "<br>
                                            <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                            <strong>User Email:</strong> " . $email . "<br>
                                            <strong>Subject:</strong> " . htmlspecialchars($ticket_subject) . "<br>
                                            <strong>Previous Status:</strong> " . ucfirst($ticket['status']) . "<br>
                                            <strong>New Status:</strong> <span style='color: #28a745; font-weight: bold;'>" . ucfirst($new_status) . "</span><br>
                                            <strong>Status Change Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>Ticket Created:</strong> " . date('F j, Y', strtotime($ticket['created_at'])) . "<br>
                                            <strong>Total Replies:</strong> " . (mysqli_num_rows($replies_result) + 1) . "<br>
                                            <strong>Action:</strong> User-initiated status change
                                        </div>
                                    </div>

                                    <!-- Resolution Details -->
                                    <div class='next-steps'>
                                        <h3 style='color: #2c3e50;'>" . ($new_status == 'resolved' ? 'Resolution Details' : 'Closure Details') . "</h3>
                                        <p style='color: #6c757d;'>
                                            <strong>User Action:</strong> Marked ticket as " . $new_status . "<br>
                                            <strong>Last Admin Reply:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT created_at FROM ticket_replies 
                                                     WHERE ticket_id='$ticket_id' AND is_admin_reply=1 
                                                     ORDER BY created_at DESC LIMIT 1"))['created_at'] ?? 'No admin reply') . "<br>
                                            <strong>Total Admin Replies:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT COUNT(*) as count FROM ticket_replies 
                                                     WHERE ticket_id='$ticket_id' AND is_admin_reply=1"))['count'] ?? 0) . "<br>
                                            <strong>Time to " . $new_status . ":</strong> " . 
                                                round((time() - strtotime($ticket['created_at'])) / (60 * 60 * 24), 1) . " days
                                        </p>
                                    </div>

                                    <!-- Admin Actions -->
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/support/ticket.php?id=" . $ticket_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View Ticket Details
                                        </a>
                                        <a href='" . $myUrl . "/admin/support/tickets.php?status=" . $new_status . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            View " . ucfirst($new_status) . " Tickets
                                        </a>
                                    </div>

                                    <!-- Notes -->
                                    <div class='support-section'>
                                        <p class='support-text'>" . ($new_status == 'resolved' ? 
                                            'Ticket marked as resolved by user. Consider following up for feedback.' : 
                                            'Ticket closed by user. No further action required.') . "</p>
                                    </div>
                                </div>";

            // Send admin notification
            require_once("../proccess/admin_mailer.php");
            
            $success = "Ticket status updated to " . ucfirst($new_status);
            // Refresh ticket data
            $ticket_result = mysqli_query($conn, $ticket_sql);
            $ticket = mysqli_fetch_assoc($ticket_result);
        } else {
            $error = "Failed to update status: " . mysqli_error($conn);
        }
    }
}

// Refresh replies after any changes
$replies_result = mysqli_query($conn, $replies_sql);
?>
<!DOCTYPE html>
<html lang="en">

<style>
    .ticket-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .message-bubble {
        max-width: 70%;
        margin-bottom: 20px;
        position: relative;
    }
    .user-message {
        margin-left: auto;
        background: #007bff;
        color: white;
        border-radius: 18px 18px 4px 18px;
    }
    .admin-message {
        margin-right: auto;
        background: #f8f9fa;
        color: #333;
        border: 1px solid #e9ecef;
        border-radius: 18px 18px 18px 4px;
    }
    .message-content {
        padding: 12px 16px;
    }
    .message-meta {
        font-size: 0.75em;
        opacity: 0.8;
        margin-top: 5px;
    }
    .status-badge {
        font-size: 0.8em;
        padding: 6px 12px;
    }
    .priority-badge {
        font-size: 0.7em;
        padding: 4px 8px;
    }
    .ticket-info-card {
        border-left: 4px solid #007bff;
    }
    .reply-form {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-top: 30px;
    }
    .attachment-preview {
        border: 1px dashed #ddd;
        border-radius: 8px;
        padding: 15px;
        text-align: center;
        margin-top: 10px;
    }
    .timeline-item {
        position: relative;
        padding-left: 30px;
        margin-bottom: 20px;
    }
    .timeline-item:before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: #007bff;
    }
</style>

<body class="dashboard">
    <div id="main-wrapper">
       
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Ticket #<?php echo $ticket['ticket_number']; ?></h3>
                                        <p class="mb-2">Support ticket details and conversation</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="support.php">Support</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="tickets.php">My Tickets</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Ticket Details</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Success/Error Messages -->
                <?php if(!empty($success)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fi fi-rr-check me-2"></i>
                            <?php echo $success; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!empty($error)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fi fi-rr-exclamation me-2"></i>
                            <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="row">
                    <!-- Main Content -->
                    <div class="col-xl-8">
                        <!-- Ticket Header -->
                        <div class="ticket-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h4 class="text-white mb-2"><?php echo htmlspecialchars($ticket['subject']); ?></h4>
                                    <div class="d-flex flex-wrap gap-2 align-items-center">
                                        <?php
                                        // Status badge
                                        $status_class = '';
                                        $status_text = '';
                                        if($ticket['status'] == 'open') {
                                            $status_class = 'bg-warning';
                                            $status_text = 'Open';
                                        } elseif($ticket['status'] == 'in_progress') {
                                            $status_class = 'bg-info';
                                            $status_text = 'In Progress';
                                        } elseif($ticket['status'] == 'resolved') {
                                            $status_class = 'bg-success';
                                            $status_text = 'Resolved';
                                        } else {
                                            $status_class = 'bg-secondary';
                                            $status_text = 'Closed';
                                        }
                                        
                                        // Priority badge
                                        $priority_class = '';
                                        if($ticket['priority'] == 'urgent') $priority_class = 'bg-danger';
                                        elseif($ticket['priority'] == 'high') $priority_class = 'bg-warning';
                                        elseif($ticket['priority'] == 'medium') $priority_class = 'bg-primary';
                                        else $priority_class = 'bg-secondary';
                                        ?>
                                        <span class="badge <?php echo $status_class; ?> status-badge"><?php echo $status_text; ?></span>
                                        <span class="badge <?php echo $priority_class; ?> priority-badge"><?php echo ucfirst($ticket['priority']); ?> Priority</span>
                                        <span class="text-white-50">Created: <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></span>
                                    </div>
                                </div>
                                <div class="col-md-4 text-end">
                                    <a href="tickets.php" class="btn btn-light btn-sm me-2">
                                        <i class="fi fi-rr-arrow-left me-1"></i>Back to Tickets
                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- Ticket Description -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h6 class="card-title mb-0">
                                    <i class="fi fi-rr-document me-2"></i>Original Issue Description
                                </h6>
                            </div>
                            <div class="card-body">
                                <p class="mb-0"><?php echo nl2br(htmlspecialchars($ticket['description'])); ?></p>
                            </div>
                        </div>

                        <!-- Conversation Thread -->
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="card-title mb-0">
                                    <i class="fi fi-rr-comments me-2"></i>Conversation
                                    <span class="badge bg-primary"><?php echo mysqli_num_rows($replies_result) + 1; ?></span>
                                </h6>
                            </div>
                            <div class="card-body">
                                <!-- Original Ticket Message -->
                                <div class="message-bubble user-message">
                                    <div class="message-content">
                                        <div class="message-text">
                                            <?php echo nl2br(htmlspecialchars($ticket['description'])); ?>
                                        </div>
                                        <div class="message-meta">
                                            <strong>You</strong> • <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Replies -->
                                <?php if(mysqli_num_rows($replies_result) > 0): ?>
                                    <?php while($reply = mysqli_fetch_assoc($replies_result)): ?>
                                    <div class="message-bubble <?php echo $reply['is_admin_reply'] ? 'admin-message' : 'user-message'; ?>">
                                        <div class="message-content">
                                            <div class="message-text">
                                                <?php echo nl2br(htmlspecialchars($reply['message'])); ?>
                                            </div>
                                            <div class="message-meta">
                                                <strong><?php echo $reply['is_admin_reply'] ? 'Support Agent' : 'You'; ?></strong> • 
                                                <?php echo date('M j, Y g:i A', strtotime($reply['created_at'])); ?>
                                                <?php if($reply['is_admin_reply']): ?>
                                                    <span class="badge bg-success ms-2">Official Response</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center py-4">
                                        <i class="fi fi-rr-comment-alt fs-1 text-muted mb-3"></i>
                                        <p class="text-muted">No replies yet. Our support team will respond soon.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Reply Form -->
                        <?php if(in_array($ticket['status'], array('open', 'in_progress'))): ?>
                        <div class="reply-form">
                            <h6 class="mb-3">Add Reply</h6>
                            <form method="POST" action="ticket_details.php?id=<?php echo $ticket_id; ?>">
                                <div class="mb-3">
                                    <textarea class="form-control" name="message" rows="4" 
                                              placeholder="Type your message here..." required></textarea>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="fi fi-rr-info me-1"></i>
                                        Your response will be visible to our support team
                                    </small>
                                    <button type="submit" name="new_reply" class="btn btn-primary">
                                        <i class="fi fi-rr-paper-plane me-2"></i>Send Reply
                                    </button>
                                </div>
                            </form>
                        </div>
                        <?php else: ?>
                        <div class="alert alert-info mt-4">
                            <i class="fi fi-rr-info me-2"></i>
                            This ticket is <?php echo $ticket['status']; ?>. You cannot add new replies.
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Sidebar -->
                    <div class="col-xl-4">
                        <!-- Ticket Information -->
                        <div class="card ticket-info-card">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Ticket Information</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <strong>Ticket Number:</strong>
                                    <div class="text-muted"><?php echo $ticket['ticket_number']; ?></div>
                                </div>
                                <div class="mb-3">
                                    <strong>Category:</strong>
                                    <div class="text-muted"><?php echo ucfirst(str_replace('_', ' ', $ticket['category'])); ?></div>
                                </div>
                                <div class="mb-3">
                                    <strong>Priority:</strong>
                                    <div>
                                        <span class="badge <?php echo $priority_class; ?> priority-badge">
                                            <?php echo ucfirst($ticket['priority']); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <strong>Status:</strong>
                                    <div>
                                        <span class="badge <?php echo $status_class; ?> status-badge">
                                            <?php echo $status_text; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <strong>Created:</strong>
                                    <div class="text-muted"><?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></div>
                                </div>
                                <div class="mb-3">
                                    <strong>Last Updated:</strong>
                                    <div class="text-muted"><?php echo date('M j, Y g:i A', strtotime($ticket['updated_at'])); ?></div>
                                </div>
                                <!-- <div>
                                    <strong>Response Language:</strong>
                                    <div class="text-muted"><?php echo ucfirst($ticket['language']); ?></div>
                                </div> -->
                            </div>
                        </div>

                        <!-- Ticket Actions -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Ticket Actions</h6>
                            </div>
                            <div class="card-body">
                                <?php if(in_array($ticket['status'], array('open', 'in_progress'))): ?>
                                <form method="POST" action="ticket_details.php?id=<?php echo $ticket_id; ?>" class="mb-3">
                                    <label class="form-label"><strong>Update Status</strong></label>
                                    <select class="form-select mb-2" name="status">
                                        <option value="resolved">Mark as Resolved</option>
                                        <option value="closed">Close Ticket</option>
                                    </select>
                                    <button type="submit" name="update_status" class="btn btn-outline-primary w-100 btn-sm">
                                        Update Status
                                    </button>
                                </form>
                                <?php endif; ?>
                                
                                <div class="d-grid gap-2">
                                    <a href="create_ticket.php" class="btn btn-primary btn-sm">
                                        <i class="fi fi-rr-plus me-1"></i>Create New Ticket
                                    </a>
                                    <a href="tickets.php" class="btn btn-outline-secondary btn-sm">
                                        <i class="fi fi-rr-list me-1"></i>View All Tickets
                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- Support Information -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Need Urgent Help?</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <i class="fi fi-rr-phone-call text-primary me-2"></i>
                                    <strong>Call Support:</strong>
                                    <div class="text-muted">0861 123 456</div>
                                </div>
                                <div class="mb-3">
                                    <i class="fi fi-rr-envelope text-success me-2"></i>
                                    <strong>Email Support:</strong>
                                    <div class="text-muted">support@E-Financeloans.co.za</div>
                                </div>
                                <div>
                                    <i class="fi fi-rr-clock text-warning me-2"></i>
                                    <strong>Response Time:</strong>
                                    <div class="text-muted">2-4 business hours</div>
                                </div>
                            </div>
                        </div>

                        <!-- Ticket Timeline -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Ticket Timeline</h6>
                            </div>
                            <div class="card-body">
                                <div class="timeline-item">
                                    <strong>Ticket Created</strong>
                                    <div class="text-muted small"><?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></div>
                                </div>
                                <?php
                                // Reset replies result pointer
                                mysqli_data_seek($replies_result, 0);
                                while($reply = mysqli_fetch_assoc($replies_result)):
                                ?>
                                <div class="timeline-item">
                                    <strong><?php echo $reply['is_admin_reply'] ? 'Support Response' : 'Your Reply'; ?></strong>
                                    <div class="text-muted small"><?php echo date('M j, Y g:i A', strtotime($reply['created_at'])); ?></div>
                                </div>
                                <?php endwhile; ?>
                                <div class="timeline-item">
                                    <strong>Last Updated</strong>
                                    <div class="text-muted small"><?php echo date('M j, Y g:i A', strtotime($ticket['updated_at'])); ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Auto-scroll to bottom of conversation
    function scrollToBottom() {
        const conversation = document.querySelector('.card-body');
        if (conversation) {
            conversation.scrollTop = conversation.scrollHeight;
        }
    }
    
    // Scroll to bottom on page load
    document.addEventListener('DOMContentLoaded', function() {
        scrollToBottom();
    });
    
    // Auto-focus reply textarea
    document.addEventListener('DOMContentLoaded', function() {
        const replyTextarea = document.querySelector('textarea[name="message"]');
        if (replyTextarea) {
            replyTextarea.focus();
        }
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>