<?php
// Start the session right away. This is crucial for both page loads (GET) and submissions (POST).
// It must be called before any output.
// Enable error reporting only in debug mode
if (defined('DEBUG_MODE') && DEBUG_MODE) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}


// --- POST & AJAX HANDLING BLOCK (START) ---
// This block will only execute on POST requests. The session is already active.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Helper function to send a standardized JSON response and exit.
    function send_json_response($data)
    {
        if (ob_get_length())
            ob_clean(); // Clean any previous output buffer
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    try {
        require_once 'includes/buffer_controller.php';
        require_once 'includes/functions.php';
        global $pdo, $lang_alerts, $lang_email;

        if (!isset($pdo)) {
            throw new Exception("Database connection is not available for the POST handler.");
        }

        if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
            throw new Exception($lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'] ?? 'Invalid CSRF token. Please try again.');
        }

        // --- Action: Add a comment/reply ---
        if (isset($_POST['submit_comment'])) {
            $ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
            if ($ticket_id === 0) {
                throw new Exception("Ticket ID is missing from the request.");
            }

            $processed_comment_text = cleanHTML($_POST['comment']);
            $attachment_filename = '';

            // Summernote can submit empty tags like <p><br></p>, so we need a robust check.
            if (empty($processed_comment_text) || trim(strip_tags($processed_comment_text)) === '') {
                throw new Exception($lang_alerts['ALERT_COMMENT_CANNOT_BE_EMPTY'] ?? 'Comment cannot be empty.');
            }

            if (!empty($_FILES['attachment']['name'])) {
                $uploadDir = 'uploads/tickets/';
                if ($_FILES['attachment']['error'] !== UPLOAD_ERR_OK) {
                    $error_message_key = 'UPLOAD_ERROR_UNKNOWN';
                    switch ($_FILES['attachment']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $error_message_key = 'UPLOAD_ERROR_INI_SIZE_FORM_SIZE';
                            break;
                        case UPLOAD_ERR_PARTIAL:
                            $error_message_key = 'UPLOAD_ERROR_PARTIAL';
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            $error_message_key = 'UPLOAD_ERROR_NO_FILE';
                            break;
                        case UPLOAD_ERR_NO_TMP_DIR:
                            $error_message_key = 'UPLOAD_ERROR_NO_TMP_DIR';
                            break;
                        case UPLOAD_ERR_CANT_WRITE:
                            $error_message_key = 'UPLOAD_ERROR_CANT_WRITE';
                            break;
                        case UPLOAD_ERR_EXTENSION:
                            $error_message_key = 'UPLOAD_ERROR_EXTENSION';
                            break;
                    }
                    $error_text = $lang_alerts[$error_message_key] ?? 'Unknown upload error.';
                    throw new Exception(sprintf($lang_alerts['UPLOAD_ERROR_FAILED_WITH_CODE'] ?? 'Upload failed: %s (Error code: %s)', $error_text, $_FILES['attachment']['error']));
                } else {
                    $attachment_filename = uploadFile($_FILES['attachment'], $uploadDir);
                    if ($attachment_filename === false || $attachment_filename === '') {
                        throw new Exception($lang_alerts['ALERT_ERROR_UPLOADING_ATTACHMENT_COMMENT_PRESERVED'] ?? 'Error uploading attachment. Please check file size and type.');
                    }
                }
            }

            $stmt = $pdo->prepare("SELECT * FROM tickets WHERE id = ?");
            $stmt->execute([$ticket_id]);
            $ticket = $stmt->fetch();

            if (!$ticket) {
                throw new Exception($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found.');
            }

            // Check if user has access to this ticket
            $current_user_id = $_SESSION['user_id'] ?? null;
            $current_user_email = $_SESSION['email'] ?? null;

            if (!isAdminOrStaff()) {
                if ($ticket['user_id'] != $current_user_id && $ticket['email'] !== $current_user_email) {
                    throw new Exception($lang_alerts['ALERT_PERMISSION_DENIED'] ?? 'You do not have permission to reply to this ticket.');
                }
            }

            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message, attachment) VALUES (?, ?, ?, ?)");
            $stmt->execute([$ticket_id, $_SESSION['user_id'], $processed_comment_text, $attachment_filename]);
            $stmt = $pdo->prepare("UPDATE tickets SET updated_at = NOW() WHERE id = ?");
            $stmt->execute([$ticket_id]);
            $pdo->commit();

            // Email notifications
            $email_comment_subject = sprintf($lang_email['EMAIL_SUBJECT_NEW_COMMENT_ON_TICKET'] ?? "New Comment on Ticket: #%s - %s", $ticket_id, htmlspecialchars($ticket['subject']));
            $ticket_link = getCleanUrl('ticket_view?id=' . $ticket_id);
            $commenter_name = htmlspecialchars($_SESSION['name']);
            $email_comment_body = sprintf($lang_email['EMAIL_BODY_NEW_COMMENT_INTRO'] ?? "<p>A new comment has been added to ticket #%s (Subject: %s).</p>", $ticket_id, htmlspecialchars($ticket['subject'])) .
                "<p><strong>" . ($lang_email['EMAIL_BODY_FIELD_COMMENTER'] ?? 'Commenter:') . "</strong> " . $commenter_name . "</p>" .
                "<p><strong>" . ($lang_email['EMAIL_BODY_FIELD_COMMENT'] ?? 'Comment:') . "</strong><br>" . $processed_comment_text . "</p>" .
                ($attachment_filename ? "<p><strong>" . ($lang_email['EMAIL_BODY_FIELD_ATTACHMENT'] ?? 'Attachment:') . "</strong> " . htmlspecialchars($attachment_filename) . "</p>" : "") .
                sprintf($lang_email['EMAIL_BODY_VIEW_TICKET_AND_COMMENT_LINK'] ?? "<p>You can view the ticket and comment here: <a href='%s'>%s</a></p>", $ticket_link, $ticket_link);

            $specific_user_ids_for_comment = [];
            if (!empty($ticket['user_id']) && $ticket['user_id'] != $_SESSION['user_id']) {
                $specific_user_ids_for_comment[] = $ticket['user_id'];
            }
            notify_relevant_users('notify_ticket_comment', $email_comment_subject, $email_comment_body, $specific_user_ids_for_comment, true);
            if (empty($ticket['user_id']) && !empty($ticket['email'])) {
                send_system_email($ticket['email'], $email_comment_subject, $email_comment_body);
            }

            send_json_response([
                'success' => true,
                'message' => $lang_alerts['ALERT_COMMENT_ADDED_SUCCESSFULLY'] ?? 'Comment added successfully.'
            ]);
        }

        // --- Action: Save a new snippet ---
        if (isset($_POST['save_snippet'])) {
            if (!isAdminOrStaff()) {
                throw new Exception('You do not have permission to perform this action.');
            }
            $subject = sanitizeInput($_POST['snippet_subject'] ?? '');
            $category = sanitizeInput($_POST['snippet_category'] ?? 'General');
            $content = $_POST['snippet_content'] ?? '';

            if (empty($subject) || empty($content)) {
                throw new Exception('Snippet subject and content cannot be empty.');
            }

            $stmt = $pdo->prepare("INSERT INTO ticket_snippets (subject, category, content, created_by) VALUES (?, ?, ?, ?)");
            $stmt->execute([$subject, $category, $content, $_SESSION['user_id']]);

            send_json_response([
                'success' => true,
                'message' => 'Snippet saved successfully.'
            ]);
        }

        // --- Action: Close a ticket ---
        if (isset($_POST['close_ticket'])) {
            $ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
            if ($ticket_id === 0) {
                throw new Exception("Ticket ID is missing from the request.");
            }
            $can_close = false;
            if (isAdminOrStaff()) {
                $can_close = true;
            } else {
                $stmt = $pdo->prepare("SELECT user_id, email FROM tickets WHERE id = ?");
                $stmt->execute([$ticket_id]);
                $ticket = $stmt->fetch();
                if ($ticket && ($ticket['user_id'] == $_SESSION['user_id'] || (!empty($ticket['email']) && $ticket['email'] === ($_SESSION['email'] ?? '')))) {
                    $can_close = true;
                }
            }
            if (!$can_close) {
                throw new Exception($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to close it.');
            }
            $stmt = $pdo->prepare("UPDATE tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$ticket_id]);
            redirectTo('tickets');
            exit;
        }

        // --- Action: Reopen a ticket ---
        if (isset($_POST['reopen_ticket'])) {
            $ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
            if ($ticket_id === 0) {
                throw new Exception("Ticket ID is missing from the request.");
            }
            $can_reopen = false;
            if (isAdminOrStaff()) {
                $can_reopen = true;
            } else {
                $stmt = $pdo->prepare("SELECT user_id, email FROM tickets WHERE id = ?");
                $stmt->execute([$ticket_id]);
                $ticket = $stmt->fetch();
                if ($ticket && ($ticket['user_id'] == $_SESSION['user_id'] || (!empty($ticket['email']) && $ticket['email'] === ($_SESSION['email'] ?? '')))) {
                    $can_reopen = true;
                }
            }
            if (!$can_reopen) {
                throw new Exception($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to reopen it.');
            }
            $stmt = $pdo->prepare("UPDATE tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$ticket_id]);
            redirectTo('tickets');
            exit;
        }

        // --- Action: Update ticket category ---
        if (isset($_POST['update_ticket_category'])) {
            if (!isAdminOrStaff()) {
                throw new Exception($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to update category.');
            }
            $ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
            $category_id = isset($_POST['category_id']) && is_numeric($_POST['category_id']) && $_POST['category_id'] !== '' ? (int) $_POST['category_id'] : null;
            if ($ticket_id === 0) {
                throw new Exception('Ticket ID is missing from the request.');
            }
            $stmt = $pdo->prepare("SELECT id FROM tickets WHERE id = ?");
            $stmt->execute([$ticket_id]);
            if (!$stmt->fetch()) {
                throw new Exception($lang_alerts['ALERT_WARNING_TICKET_NOT_FOUND'] ?? 'Ticket not found.');
            }
            $stmt = $pdo->prepare("UPDATE tickets SET category_id = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$category_id, $ticket_id]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATEGORY_UPDATED'] ?? 'Ticket category updated successfully.', 'success');
            redirectTo('ticket_view/' . $ticket_id . (isset($_GET['email']) ? ('?email=' . urlencode($_GET['email'])) : ''));
            exit;
        }

        // --- Action: Update ticket assignment ---
        if (isset($_POST['update_ticket_assignment'])) {
            if (!isAdminOrStaff()) {
                throw new Exception($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to update assignment.');
            }
            $ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
            $assigned_to = isset($_POST['assigned_to']) && is_numeric($_POST['assigned_to']) && $_POST['assigned_to'] !== '' ? (int) $_POST['assigned_to'] : null;
            if ($ticket_id === 0) {
                throw new Exception('Ticket ID is missing from the request.');
            }
            $stmt = $pdo->prepare("SELECT id FROM tickets WHERE id = ?");
            $stmt->execute([$ticket_id]);
            if (!$stmt->fetch()) {
                throw new Exception($lang_alerts['ALERT_WARNING_TICKET_NOT_FOUND'] ?? 'Ticket not found.');
            }
            $stmt = $pdo->prepare("UPDATE tickets SET assigned_to = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$assigned_to, $ticket_id]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_ASSIGNMENT_UPDATED'] ?? 'Ticket assignment updated successfully.', 'success');
            redirectTo('ticket_view/' . $ticket_id . (isset($_GET['email']) ? ('?email=' . urlencode($_GET['email'])) : ''));
            exit;
        }

        send_json_response(['success' => false, 'message' => 'No recognized POST action.']);

    } catch (Throwable $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        // Ensure this is a JSON response for AJAX calls
        send_json_response(['success' => false, 'message' => 'Server Error: ' . $e->getMessage()]);
    }
}
// --- POST & AJAX HANDLING BLOCK (END) ---


// --- MAIN PAGE RENDERING (EXECUTED ONLY ON GET REQUESTS) ---
require_once 'includes/buffer_controller.php';
$submitted_comment_text_for_form = '';

include 'includes/header.php';

if (!isLoggedIn() && !ALLOW_GUEST_TICKETS) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_LOGIN_TO_VIEW_TICKET_DETAILS'] ?? 'You must be logged in to view ticket details', 'warning');
    redirectTo('login');
    exit;
}

$ticket_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($ticket_id === 0) {
    redirectTo('tickets');
}

$email = isset($_GET['email']) ? sanitizeInput($_GET['email']) : '';
$is_guest_lookup = !isLoggedIn() && !empty($email);

$sql = "SELECT t.*, u.name as user_name, u.email as user_email, u.avatar as user_avatar, tc.name as category_name, tc.icon as category_icon,
               au.name as assigned_user_name, au.email as assigned_user_email
        FROM tickets t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN ticket_categories tc ON t.category_id = tc.id
        LEFT JOIN users au ON t.assigned_to = au.id
        WHERE t.id = ?";

if ($is_guest_lookup) {
    $sql .= " AND (t.email = ? OR (t.user_id IS NOT NULL AND EXISTS (SELECT 1 FROM users WHERE id = t.user_id AND email = ?)))";
    $params = [$ticket_id, $email, $email];
} else if (!isAdminOrStaff()) {
    $user_email = '';
    $stmt_user = $pdo->prepare("SELECT email FROM users WHERE id = ?");
    $stmt_user->execute([$_SESSION['user_id']]);
    $user = $stmt_user->fetch();
    if ($user) {
        $user_email = $user['email'];
    }
    $sql .= " AND (t.user_id = ? OR t.email = ?)";
    $params = [$ticket_id, $_SESSION['user_id'], $user_email];
} else { // Admin or Staff
    $params = [$ticket_id];
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

if ($stmt->rowCount() === 0) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to view it.', 'danger');
    redirectTo('tickets');
    exit;
}
$ticket = $stmt->fetch();

$page_title = isset($lang_frontend['PAGE_TITLE_TICKET_VIEW']) ? sprintf($lang_frontend['PAGE_TITLE_TICKET_VIEW'], $ticket['id'], htmlspecialchars($ticket['subject'])) : 'Ticket #' . $ticket['id'] . ' - ' . htmlspecialchars($ticket['subject']);

$statusClasses = [
    'open' => 'bg-success text-white',
    'closed' => 'bg-secondary text-white'
];
$statusLabels = [
    'open' => $lang_frontend['STATUS_OPEN'] ?? 'Open',
    'closed' => $lang_frontend['STATUS_CLOSED'] ?? 'Closed'
];

$stmt = $pdo->prepare("SELECT c.*, u.name, u.email, u.avatar, u.role
                      FROM ticket_replies c
                      LEFT JOIN users u ON c.user_id = u.id
                      WHERE c.ticket_id = ?
                      ORDER BY c.created_at ASC");
$stmt->execute([$ticket_id]);
$comments = $stmt->fetchAll();

$snippets = [];
if (isAdminOrStaff()) {
    $stmt = $pdo->prepare("SELECT id, subject, category, content FROM ticket_snippets ORDER BY category, subject");
    $stmt->execute();
    $snippets = $stmt->fetchAll();
}

$stmt_cf = $pdo->prepare("SELECT cf.name, cf.type, cf.possible_values, cfv.value FROM custom_field_values cfv JOIN custom_fields cf ON cfv.field_id = cf.id WHERE cfv.item_id = ? ORDER BY cf.sort_order, cf.id");
$stmt_cf->execute([$ticket_id]);
$custom_field_values = $stmt_cf->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1>
        <?php echo sprintf($lang_frontend['PAGE_TITLE_TICKET_VIEW'] ?? 'Ticket #%s - %s', $ticket['id'], htmlspecialchars($ticket['subject'])); ?>
    </h1>
    <div>
        <?php if ($ticket['status'] === 'closed' && isLoggedIn()): ?>
            <form
                action="<?php echo getCleanUrl('ticket_view/' . $ticket_id, $is_guest_lookup ? ['email' => $email] : []); ?>"
                method="post" class="d-inline">
                <?php echo get_csrf_input_field(); ?>
                <button type="submit" name="reopen_ticket" class="btn btn-success me-2">
                    <i class="bi bi-arrow-clockwise"></i>
                    <?php echo $lang_frontend['TICKET_VIEW_BUTTON_REOPEN'] ?? 'Reopen Ticket'; ?>
                </button>
            </form>
        <?php endif; ?>
        <?php if ($ticket['status'] !== 'closed' && isLoggedIn()): ?>
            <button type="button" class="btn btn-danger me-2" data-bs-toggle="modal" data-bs-target="#closeTicketModal">
                <i class="bi bi-check-circle"></i>
                <?php echo $lang_frontend['TICKET_VIEW_BUTTON_CLOSE'] ?? 'Close Ticket'; ?>
            </button>
        <?php endif; ?>
        <a href="<?php echo getCleanUrl('tickets', $is_guest_lookup ? ['email' => $email] : []); ?>"
            class="btn btn-outline-primary">
            <i class="bi bi-arrow-left"></i>
            <?php echo $lang_frontend['TICKET_VIEW_BUTTON_BACK_TO_TICKETS'] ?? 'Back to Tickets'; ?>
        </a>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <!-- Ticket Details -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['CARD_HEADER_DESCRIPTION'] ?? 'Description'; ?></h5>
            </div>
            <div class="card-body">
                <div>
                    <p class="mb-0">
                        <?php echo makeLinksClickable(cleanHTML(html_entity_decode($ticket['message'], ENT_QUOTES | ENT_HTML5, 'UTF-8'))); ?>
                    </p>
                </div>
            </div>
        </div>
        <!-- Conversations -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">
                    <?php echo $lang_frontend['TICKET_VIEW_CARD_HEADER_CONVERSATIONS'] ?? 'Conversations'; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($comments)): ?>
                    <div class="alert alert-info">
                        <?php echo $lang_frontend['TICKET_VIEW_NO_REPLIES_PROMPT'] ?? 'No replies yet. Be the first to reply or comment.'; ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($comments as $comment): ?>
                        <div class="d-flex mb-4">
                            <div class="flex-shrink-0">
                                <?php if (!empty($comment['avatar'])): ?>
                                    <img src="<?php echo BASE_URL . '/uploads/avatars/' . htmlspecialchars($comment['avatar'], ENT_COMPAT, 'UTF-8'); ?>"
                                        alt="<?php echo $lang_frontend['AVATAR_ALT_TEXT'] ?? 'Avatar'; ?>" class="avatar-md">
                                <?php else: ?>
                                    <div class="avatar-md d-flex align-items-center justify-content-center bg-light rounded-circle">
                                        <i class="bi-bi-person text-secondary"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0">
                                        <?php echo htmlspecialchars($comment['name'], ENT_COMPAT, 'UTF-8'); ?>
                                        <?php if (isset($comment['role']) && in_array($comment['role'], ['admin', 'staff'])): ?>
                                            <span
                                                class="badge bg-primary ms-2"><?php echo $lang_frontend['BADGE_TEXT_STAFF'] ?? 'Staff'; ?></span>
                                        <?php endif; ?>
                                    </h6>
                                    <small
                                        class="text-muted"><?php echo getFormattedDate($comment['created_at'], DATETIME_FORMAT); ?></small>
                                </div>
                                <div class="mt-2 mb-1">
                                    <?php echo makeLinksClickable(cleanHTML(html_entity_decode($comment['message'], ENT_QUOTES | ENT_HTML5, 'UTF-8'))); ?>
                                </div>
                                <?php if (!empty($comment['attachment'])): ?>
                                    <div class="mt-2">
                                        <a href="<?php echo BASE_URL . '/uploads/tickets/' . htmlspecialchars($comment['attachment'], ENT_COMPAT, 'UTF-8'); ?>"
                                            target="_blank" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-file-earmark"></i>
                                            <?php echo $lang_frontend['TICKET_VIEW_BUTTON_VIEW_ATTACHMENT'] ?? 'View Attachment'; ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>

                <!-- Add Comment Form -->
                <?php if (isLoggedIn()): ?>
                    <?php if ($ticket['status'] !== 'closed'): ?>
                        <form
                            action="<?php echo getCleanUrl('ticket_view.php', ['id' => $ticket_id] + ($is_guest_lookup ? ['email' => $email] : [])); ?>"
                            method="post" class="mt-4" enctype="multipart/form-data" id="replyForm">
                            <?php echo get_csrf_input_field(); ?>
                            <h5><?php echo $lang_frontend['TICKET_VIEW_FORM_HEADING_ADD_COMMENT'] ?? 'Add a Comment'; ?></h5>
                            <div id="replyMessage" class="mb-3"></div>
                            <div class="mb-3">
                                <label for="comment"
                                    class="form-label visually-hidden"><?php echo $lang_frontend['FORM_LABEL_COMMENT'] ?? 'Comment'; ?></label>
                                <textarea class="form-control" id="comment" name="comment" rows="4"
                                    required><?php echo htmlspecialchars($submitted_comment_text_for_form ?? '', ENT_COMPAT, 'UTF-8'); ?></textarea>
                            </div>

                            <div class="mb-3">
                                <label for="attachment"
                                    class="form-label"><?php echo $lang_frontend['FORM_LABEL_ATTACHMENT_OPTIONAL'] ?? 'Attachment (Optional)'; ?></label>
                                <input type="file" class="form-control" id="attachment" name="attachment"
                                    data-max-size="<?php echo MAX_UPLOAD_SIZE; ?>"
                                    data-allowed-types="<?php echo implode(',', ALLOWED_EXTENSIONS); ?>">
                                <div class="form-text">
                                    <?php echo sprintf($lang_frontend['FORM_TEXT_FILE_UPLOAD_CONSTRAINTS'] ?? 'Max file size: %s MB. Allowed file types: %s', MAX_UPLOAD_SIZE / 1024 / 1024, implode(', ', ALLOWED_EXTENSIONS)); ?>
                                </div>
                            </div>
                            <div class="d-flex justify-content-start">
                                <button type="submit" name="submit_comment" class="btn btn-primary">
                                    <i class="bi bi-paper-plane"></i>
                                    <?php echo $lang_frontend['TICKET_VIEW_BUTTON_SUBMIT_REPLY'] ?? 'Submit Reply'; ?>
                                </button>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="alert alert-warning mt-4">
                            <i class="bi bi-lock"></i>
                            <?php echo $lang_frontend['TICKET_VIEW_ALERT_TICKET_CLOSED_NO_COMMENTS'] ?? 'This ticket is closed. No further comments can be added.'; ?>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="alert alert-info mt-4">
                        <i class="bi bi-info-circle"></i>
                        <?php echo $lang_frontend['TICKET_VIEW_ALERT_LOGIN_TO_COMMENT'] ?? 'You must be logged in to add replies or comments to this ticket.'; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <!-- Details Card -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['CARD_HEADER_DETAILS'] ?? 'Details'; ?></h5>
            </div>
            <div class="card-body">
                <strong><?php echo $lang_frontend['TICKET_VIEW_DETAILS_OPENED_BY'] ?? 'Opened by:'; ?></strong><br>
                <div class="d-flex align-items-center mb-3">
                    <?php if (!empty($ticket['user_id']) && !empty($ticket['user_avatar'])): ?>
                        <img src="<?php echo BASE_URL . '/uploads/avatars/' . $ticket['user_avatar']; ?>"
                            alt="<?php echo $lang_frontend['AVATAR_ALT_TEXT'] ?? 'Avatar'; ?>" class="avatar-md me-3">
                    <?php else: ?>
                        <div
                            class="avatar-md d-flex align-items-center justify-content-center bg-light rounded-circle me-3">
                            <i class="bi-bi-person text-secondary"></i>
                        </div>
                    <?php endif; ?>
                    <div>
                        <h6 class="mb-0">
                            <?php echo htmlspecialchars($ticket['user_name'] ?? ($lang_frontend['TEXT_GUEST_USER'] ?? 'Guest'), ENT_COMPAT, 'UTF-8'); ?>
                        </h6>
                        <p class="mb-0 text-muted">
                            <?php echo htmlspecialchars($ticket['user_email'] ?? $ticket['email'] ?? '', ENT_COMPAT, 'UTF-8'); ?>
                        </p>
                    </div>
                </div>
                <hr>
                <strong><?php echo $lang_frontend['TEXT_CREATED_DATE'] ?? 'Created:'; ?></strong>
                <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['created_at'], DATETIME_FORMAT)); ?>">
                    <?php echo timeAgo($ticket['created_at'], [
                        'just_now' => $lang_frontend['TIMEAGO_JUST_NOW'],
                        'minute_ago' => $lang_frontend['TIMEAGO_MINUTE_AGO'],
                        'minutes_ago' => $lang_frontend['TIMEAGO_MINUTES_AGO'],
                        'hour_ago' => $lang_frontend['TIMEAGO_HOUR_AGO'],
                        'hours_ago' => $lang_frontend['TIMEAGO_HOURS_AGO'],
                        'day_ago' => $lang_frontend['TIMEAGO_DAY_AGO'],
                        'days_ago' => $lang_frontend['TIMEAGO_DAYS_AGO'],
                        'week_ago' => $lang_frontend['TIMEAGO_WEEK_AGO'],
                        'weeks_ago' => $lang_frontend['TIMEAGO_WEEKS_AGO'],
                        'month_ago' => $lang_frontend['TIMEAGO_MONTH_AGO'],
                        'months_ago' => $lang_frontend['TIMEAGO_MONTHS_AGO'],
                        'year_ago' => $lang_frontend['TIMEAGO_YEAR_AGO'],
                        'years_ago' => $lang_frontend['TIMEAGO_YEARS_AGO'],
                    ]); ?>
                </span>
                <br><br>
                <strong><?php echo $lang_frontend['TICKET_VIEW_DETAILS_LAST_UPDATE'] ?? 'Last Update:'; ?></strong>
                <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['updated_at'], DATETIME_FORMAT)); ?>">
                    <?php echo timeAgo($ticket['updated_at'], [
                        'just_now' => $lang_frontend['TIMEAGO_JUST_NOW'],
                        'minute_ago' => $lang_frontend['TIMEAGO_MINUTE_AGO'],
                        'minutes_ago' => $lang_frontend['TIMEAGO_MINUTES_AGO'],
                        'hour_ago' => $lang_frontend['TIMEAGO_HOUR_AGO'],
                        'hours_ago' => $lang_frontend['TIMEAGO_HOURS_AGO'],
                        'day_ago' => $lang_frontend['TIMEAGO_DAY_AGO'],
                        'days_ago' => $lang_frontend['TIMEAGO_DAYS_AGO'],
                        'week_ago' => $lang_frontend['TIMEAGO_WEEK_AGO'],
                        'weeks_ago' => $lang_frontend['TIMEAGO_WEEKS_AGO'],
                        'month_ago' => $lang_frontend['TIMEAGO_MONTH_AGO'],
                        'months_ago' => $lang_frontend['TIMEAGO_MONTHS_AGO'],
                        'year_ago' => $lang_frontend['TIMEAGO_YEAR_AGO'],
                        'years_ago' => $lang_frontend['TIMEAGO_YEARS_AGO'],
                    ]); ?>
                </span>
                <br><br>
                <strong><?php echo $lang_frontend['TABLE_HEADER_STATUS'] ?? 'Status:'; ?></strong>
                <span class="badge <?php echo $statusClasses[$ticket['status']]; ?>">
                    <?php echo $statusLabels[$ticket['status']]; ?>
                </span>
                <br><br>
                <strong><?php echo $lang_frontend['FORM_LABEL_CATEGORY'] ?? 'Category:'; ?></strong>
                <?php if (!empty($ticket['category_icon'])): ?>
                    <i class="bi bi-<?php echo htmlspecialchars($ticket['category_icon']); ?> text-primary"></i>
                <?php endif; ?>
                <?php echo $ticket['category_name'] ? htmlspecialchars($ticket['category_name']) : '<span class="text-muted">' . ($lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A') . '</span>'; ?>
                <br><br>
                <strong><?php echo $lang_frontend['FORM_LABEL_ASSIGN_TO'] ?? 'Assigned To:'; ?></strong>
                <?php echo $ticket['assigned_user_name'] ? htmlspecialchars($ticket['assigned_user_name']) : '<span class="text-muted">' . ($lang_frontend['TEXT_UNASSIGNED'] ?? 'Unassigned') . '</span>'; ?>
                <?php if (!empty($ticket['attachment'])): ?>
                    <br><br>
                    <strong><?php echo $lang_frontend['TICKET_VIEW_DETAILS_ATTACHMENT'] ?? 'Attachment:'; ?></strong>
                    <div>
                        <a href="<?php echo BASE_URL . '/uploads/tickets/' . htmlspecialchars($ticket['attachment'], ENT_COMPAT, 'UTF-8'); ?>"
                            target="_blank" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-file-earmark"></i>
                            <?php echo $lang_frontend['TICKET_VIEW_BUTTON_VIEW_ATTACHMENT'] ?? 'View Attachment'; ?>
                        </a>
                    </div>
                <?php endif; ?>
                <?php if (!empty($ticket['related_service'])): ?>
                    <br><br>
                    <strong><?php echo $lang_frontend['TICKET_FORM_LABEL_RELATED_SERVICE'] ?? 'Related product or service'; ?>:</strong>
                    <?php
                    // Try to fetch the product name for display
                    $related_service_name = '';
                    if (is_numeric($ticket['related_service'])) {
                        $stmt_rs = $pdo->prepare("SELECT name FROM products WHERE id = ?");
                        $stmt_rs->execute([$ticket['related_service']]);
                        $related_service_name = $stmt_rs->fetchColumn();
                    }
                    echo $related_service_name ? htmlspecialchars($related_service_name) : htmlspecialchars($ticket['related_service']);
                    ?>
                <?php endif; ?>
                <?php if (!empty($custom_field_values)): ?>
                    <hr>
                    <div class="mt-2">
                        <?php foreach ($custom_field_values as $cfv): ?>
                            <div class="mb-1">
                                <span class="fw-bold"><?php echo htmlspecialchars($cfv['name']); ?>:</span>
                                <?php
                                if (in_array($cfv['type'], ['checkboxes'])) {
                                    $vals = array_filter(array_map('trim', explode(',', $cfv['value'])));
                                    echo htmlspecialchars(implode(', ', $vals));
                                } else {
                                    echo htmlspecialchars($cfv['value']);
                                }
                                ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (isAdminOrStaff()): ?>
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?php echo $lang_frontend['TABLE_HEADER_ACTIONS'] ?? 'Actions'; ?></h5>
                </div>
                <div class="card-body">
                    <form
                        action="<?php echo getCleanUrl('ticket_view/' . $ticket_id, $is_guest_lookup ? ['email' => $email] : []); ?>"
                        method="post">
                        <?php echo get_csrf_input_field(); ?>
                        <label for="category_id_admin"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_CHANGE_CATEGORY'] ?? 'Change Category'; ?></label>
                        <select class="form-select mb-2" id="category_id_admin" name="category_id">
                            <option value="">
                                <?php echo $lang_frontend['FORM_SELECT_OPTION_NO_CATEGORY'] ?? '-- No Category --'; ?>
                            </option>
                            <?php
                            $stmtCategoriesAdmin = $pdo->query("SELECT id, name FROM ticket_categories ORDER BY name ASC");
                            while ($catAdmin = $stmtCategoriesAdmin->fetch(PDO::FETCH_ASSOC)) {
                                $selected = ($ticket['category_id'] == $catAdmin['id']) ? 'selected' : '';
                                echo '<option value="' . htmlspecialchars($catAdmin['id']) . '" ' . $selected . '>' . htmlspecialchars($catAdmin['name']) . '</option>';
                            }
                            ?>
                        </select>
                        <button type="submit" name="update_ticket_category"
                            class="btn btn-primary w-100"><?php echo $lang_frontend['BUTTON_UPDATE_CATEGORY'] ?? 'Update Category'; ?></button>
                    </form>
                    <hr>
                    <form
                        action="<?php echo getCleanUrl('ticket_view/' . $ticket_id, $is_guest_lookup ? ['email' => $email] : []); ?>"
                        method="post">
                        <?php echo get_csrf_input_field(); ?>
                        <label for="assigned_to_admin"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_ASSIGN_TO'] ?? 'Assign To'; ?></label>
                        <select class="form-select mb-2" id="assigned_to_admin" name="assigned_to">
                            <option value="">
                                <?php echo $lang_frontend['FORM_SELECT_OPTION_UNASSIGNED_STAFF'] ?? '-- Unassigned --'; ?>
                            </option>
                            <?php
                            $stmtUsersAdmin = $pdo->query("SELECT id, name, email FROM users WHERE role IN ('admin', 'staff') ORDER BY name ASC");
                            while ($userAdmin = $stmtUsersAdmin->fetch(PDO::FETCH_ASSOC)) {
                                $selected = ($ticket['assigned_to'] == $userAdmin['id']) ? 'selected' : '';
                                echo '<option value="' . htmlspecialchars($userAdmin['id']) . '" ' . $selected . '>' .
                                    htmlspecialchars($userAdmin['name']) . ' (' . htmlspecialchars($userAdmin['email']) . ')</option>';
                            }
                            ?>
                        </select>
                        <button type="submit" name="update_ticket_assignment"
                            class="btn btn-primary w-100"><?php echo $lang_frontend['BUTTON_UPDATE_ASSIGNMENT'] ?? 'Update Assignment'; ?></button>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modals -->
<div class="modal fade" id="closeTicketModal" tabindex="-1" aria-labelledby="closeTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="closeTicketModalLabel">
                    <?php echo $lang_frontend['TICKET_VIEW_BUTTON_CLOSE'] ?? 'Close Ticket'; ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"
                    aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
            </div>
            <form method="post"
                action="<?php echo getCleanUrl('ticket_view/' . $ticket_id, $is_guest_lookup ? ['email' => $email] : []); ?>">
                <?php echo get_csrf_input_field(); ?>
                <div class="modal-body">
                    <p><?php echo sprintf($lang_frontend['MODAL_TEXT_CONFIRM_CLOSE_TICKET'] ?? 'Are you sure you want to close ticket #%s?', $ticket['id']); ?>
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary"
                        data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                    <button type="submit" name="close_ticket"
                        class="btn btn-danger"><?php echo $lang_frontend['TICKET_VIEW_BUTTON_CLOSE'] ?? 'Close Ticket'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if (isLoggedIn() && isAdminOrStaff()): ?>
    <div class="modal fade" id="saveSnippetModal" tabindex="-1" aria-labelledby="saveSnippetModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saveSnippetModalLabel">
                        <?php echo $lang_frontend['BUTTON_SAVE_AS_SNIPPET'] ?? 'Save as Snippet'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="saveSnippetForm">
                    <div class="modal-body">
                        <div id="saveSnippetMessage"></div>
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="save_snippet" value="1">
                        <div class="mb-3">
                            <label for="snippet_subject" class="form-label">Snippet Subject</label>
                            <input type="text" class="form-control" id="snippet_subject" name="snippet_subject" required>
                        </div>
                        <div class="mb-3">
                            <label for="snippet_category" class="form-label">Category</label>
                            <input type="text" class="form-control" id="snippet_category" name="snippet_category"
                                placeholder="e.g., General, Billing">
                        </div>
                        <div class="mb-3">
                            <label for="snippet_content" class="form-label">Content</label>
                            <textarea class="form-control" id="snippet_content" name="snippet_content" rows="5"
                                readonly></textarea>
                            <div class="form-text">This is the content from the editor. It cannot be edited here.</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Snippet</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Pass PHP data to JavaScript -->
<script>
    <?php if (isAdminOrStaff()): ?>
        const snippetsData = <?php echo json_encode($snippets); ?>;
    <?php else: ?>
        const snippetsData = [];
    <?php endif; ?>
    const csrfToken = '<?php echo $_SESSION['csrf_token']; ?>';
    const lang = {
        insertSnippet: "<?php echo $lang_frontend['FORM_LABEL_INSERT_SNIPPET'] ?? 'Insert Snippet'; ?>",
        saveAsSnippet: "<?php echo $lang_frontend['BUTTON_SAVE_AS_SNIPPET'] ?? 'Save as Snippet'; ?>"
    };
</script>

<script>
    window.magicAIConfig = {
        AI_OPENAI: '<?php echo AI_OPENAI; ?>',
        AI_CLAUDE: '<?php echo AI_CLAUDE; ?>',
        AI_GEMINI: '<?php echo AI_GEMINI; ?>',
        AI_MISTRAL: '<?php echo AI_MISTRAL; ?>',
        AI_DEEPSEEK: '<?php echo AI_DEEPSEEK; ?>'
    };
</script>

<script>
    $(document).ready(function () {

        // --- Summernote Initialization with Custom Buttons ---
        // Only initialize if the user can reply
        if ($('#comment').length) {
            let summernoteToolbar = [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['para', ['ul', 'ol']],
                ['insert', ['link']],
                ['magic', ['SummernoteMagic']]
            ];

            let summernoteButtons = {};

            <?php if (isAdminOrStaff()): ?>
                // Build the HTML for the snippet dropdown
                function buildSnippetsDropdown(snippets) {
                    if (!snippets || snippets.length === 0) {
                        return '<a class="dropdown-item disabled" href="#">No snippets available</a>';
                    }

                    let categories = {};
                    snippets.forEach(s => {
                        if (!categories[s.category]) {
                            categories[s.category] = [];
                        }
                        categories[s.category].push(s);
                    });

                    let html = '';
                    for (const category in categories) {
                        html += `<li><h6 class="dropdown-header">${category}</h6></li>`;
                        categories[category].forEach(s => {
                            // Store content in a data attribute to avoid issues with special characters
                            html += `<li><a class="dropdown-item snippet-item" href="#" data-content="${encodeURIComponent(s.content)}">${s.subject}</a></li>`;
                        });
                        html += '<li><hr class="dropdown-divider"></li>';
                    }
                    return html;
                }

                // Define the "Insert Snippet" custom button
                summernoteButtons.insertSnippet = function (context) {
                    var ui = $.summernote.ui;
                    var button = ui.buttonGroup([
                        ui.button({
                            className: 'dropdown-toggle',
                            contents: '<i class="bi bi-journal-plus"></i> ' + lang.insertSnippet,
                            tooltip: lang.insertSnippet,
                            data: {
                                toggle: 'dropdown'
                            }
                        }),
                        ui.dropdown({
                            className: 'dropdown-menu',
                            items: buildSnippetsDropdown(snippetsData),
                            callback: function ($dropdown) {
                                $dropdown.find('.snippet-item').each(function () {
                                    $(this).on('click', function (e) {
                                        e.preventDefault();
                                        const content = decodeURIComponent($(this).data('content'));
                                        context.invoke('editor.pasteHTML', content);
                                    });
                                });
                            }
                        })
                    ]);
                    return button.render();
                };

                // Define the "Save as Snippet" custom button
                summernoteButtons.saveSnippet = function (context) {
                    var ui = $.summernote.ui;
                    var button = ui.button({
                        contents: '<i class="bi bi-bookmark-plus"></i> ' + lang.saveAsSnippet,
                        tooltip: lang.saveAsSnippet,
                        click: function () {
                            var content = context.invoke('code');
                            // Do not open if editor is empty
                            if (content.trim() === '' || content.trim() === '<p><br></p>') {
                                alert('Cannot save an empty snippet.');
                                return;
                            }
                            $('#snippet_content').val(content);
                            $('#saveSnippetModal').modal('show');
                        }
                    });
                    return button.render();
                };

                // Add the custom buttons to the toolbar
                summernoteToolbar.push(['snippets', ['insertSnippet', 'saveSnippet']]);
            <?php endif; ?>

            $('#comment').summernote({
                toolbar: summernoteToolbar,
                buttons: summernoteButtons,
                height: 300,
                minHeight: 150,
                maxHeight: null,
                dialogsFade: true,
                dialogsInBody: true,
                tabDisable: false,
                spellCheck: true
            });
        }

        // --- AJAX Form Submission for Ticket Reply ---
        var replyForm = document.getElementById('replyForm');
        if (replyForm) {
            replyForm.addEventListener('submit', function (e) {
                e.preventDefault();

                var submitButton = replyForm.querySelector('button[type="submit"]');
                var originalButtonHTML = submitButton.innerHTML;
                submitButton.disabled = true;
                submitButton.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Submitting...`;

                var replyMessage = document.getElementById('replyMessage');
                replyMessage.innerHTML = '';

                var formData = new FormData(replyForm);
                var summernoteContent = $('#comment').summernote('code');
                formData.set('comment', summernoteContent);
                formData.append('submit_comment', '1');

                fetch(replyForm.action, {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(response => response.json().catch(() => {
                        throw new Error('Invalid JSON response from server. Check server logs.');
                    }))
                    .then(data => {
                        if (data.success) {
                            replyMessage.innerHTML = `<div class="alert alert-success">${data.message} Reloading...</div>`;
                            setTimeout(() => { window.location.reload(); }, 1500);
                        } else {
                            replyMessage.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                            submitButton.disabled = false;
                            submitButton.innerHTML = originalButtonHTML;
                        }
                    })
                    .catch(error => {
                        console.error('Fetch Error:', error);
                        replyMessage.innerHTML = `<div class="alert alert-danger">An unexpected error occurred: ${error.message}</div>`;
                        submitButton.disabled = false;
                        submitButton.innerHTML = originalButtonHTML;
                    });
            });
        }

        // --- AJAX Form Submission for Save Snippet Modal ---
        var saveSnippetForm = document.getElementById('saveSnippetForm');
        if (saveSnippetForm) {
            saveSnippetForm.addEventListener('submit', function (e) {
                e.preventDefault();

                var submitButton = saveSnippetForm.querySelector('button[type="submit"]');
                var originalButtonHTML = submitButton.innerHTML;
                submitButton.disabled = true;
                submitButton.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...`;

                var saveMessage = document.getElementById('saveSnippetMessage');
                saveMessage.innerHTML = '';

                var formData = new FormData(saveSnippetForm);

                fetch(window.location.href, { // Post to the same page
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            saveMessage.innerHTML = `<div class="alert alert-success">${data.message}</div>`;
                            setTimeout(() => {
                                $('#saveSnippetModal').modal('hide');
                                saveMessage.innerHTML = ''; // Clear message
                                saveSnippetForm.reset(); // Reset form fields
                                // Optionally, you could reload the page to see the new snippet in the list
                                // window.location.reload();
                            }, 2000);
                        } else {
                            saveMessage.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                        }
                    })
                    .catch(error => {
                        console.error('Save Snippet Error:', error);
                        saveMessage.innerHTML = `<div class="alert alert-danger">An error occurred while saving the snippet.</div>`;
                    })
                    .finally(() => {
                        submitButton.disabled = false;
                        submitButton.innerHTML = originalButtonHTML;
                    });
            });
        }
    });
</script>

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