<?php
// Include buffer controller (handles output buffering)
require_once 'includes/buffer_controller.php';

// Include header (which includes all dependencies)
include 'includes/header.php';

// Always check login first when guest tickets are disabled
if (!ALLOW_GUEST_TICKETS && !isLoggedIn()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_LOGIN_TO_VIEW_TICKETS'] ?? 'You must be logged in to view tickets', 'warning');
    redirectTo('login');
    exit;
}

// Add ticket lookup for guests by email only
$email = isset($_GET['email']) ? sanitizeInput($_GET['email']) : '';

// Pagination settings with cookie support
$items_per_page = isset($_GET['show']) ? (int)$_GET['show'] : (isset($_COOKIE['tickets_per_page']) ? (int)$_COOKIE['tickets_per_page'] : 25);
if ($items_per_page < 1 || $items_per_page > 100) {
    $items_per_page = 25; // Default fallback
}

// Set cookie if user changed the value
if (isset($_GET['show']) && (int)$_GET['show'] !== (isset($_COOKIE['tickets_per_page']) ? (int)$_COOKIE['tickets_per_page'] : 25)) {
    setcookie('tickets_per_page', $items_per_page, time() + (365 * 24 * 60 * 60), '/'); // 1 year expiry
}

// Handle "My tickets" filter for admin/staff
$my_tickets_filter = isset($_GET['my_tickets']) && $_GET['my_tickets'] === '1' && isAdminOrStaff();

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $items_per_page;

// Base SQL for user filtering
$baseSql = "SELECT t.*, u.name as user_name, tc.name as category_name, tc.icon as category_icon, au.name as assigned_user_name, (SELECT COUNT(*) FROM ticket_replies c WHERE c.ticket_id = t.id) AS comment_count
            FROM tickets t 
            LEFT JOIN users u ON t.user_id = u.id AND u.id IS NOT NULL
            LEFT JOIN ticket_categories tc ON t.category_id = tc.id
            LEFT JOIN users au ON t.assigned_to = au.id";

$baseParams = [];
// Build WHERE clause based on user type
// Security: All WHERE clause parts are hardcoded strings - no user input in SQL structure
// All user-provided values are passed as parameters to prevent SQL injection
$whereClause = "";
$baseParams = [];

if (!isLoggedIn() && !empty($email)) {
    // Guest lookup with email only - show all tickets for this email
    // Email is sanitized before use, and passed as parameter
    $whereClause = " WHERE (LOWER(t.email) = LOWER(?) OR (t.user_id IS NOT NULL AND EXISTS (SELECT 1 FROM users WHERE id = t.user_id AND LOWER(email) = LOWER(?))))";
    $baseParams = [$email, $email];
} else if (isLoggedIn() && !isAdminOrStaff()) {
    // Get the user's email from database (not from user input)
    $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'];
    }

    // Regular users see their own tickets AND any guest tickets with their email
    // user_id comes from session (validated), email from database
    $whereClause = " WHERE (t.user_id = ? OR t.email = ?)";
    $baseParams = [$_SESSION['user_id'], $user_email];
} else {
    // Admin/Staff users see all tickets - but filter by "My tickets" if enabled
    if ($my_tickets_filter) {
        // assigned_to filter uses session user_id (validated)
        $whereClause = " WHERE t.assigned_to = ?";
        $baseParams = [$_SESSION['user_id']];
    } else {
        // No filter for admin/staff viewing all tickets
        $whereClause = "";
        $baseParams = [];
    }
}

// Get total count for pagination
// Security: whereClause is built from hardcoded strings, baseParams are validated
$countSql = "SELECT COUNT(*) FROM tickets t" . $whereClause;
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($baseParams);
$total_tickets = $countStmt->fetchColumn();
$total_pages = ceil($total_tickets / $items_per_page);

// Get counts for open and closed tickets separately
// Security: Status values ('open', 'closed') are hardcoded strings, not user input
$statusOpen = 'open';
$statusClosed = 'closed';

if (empty($whereClause)) {
    $openCountSql = "SELECT COUNT(*) FROM tickets t WHERE t.status = ?";
    $openCountParams = [$statusOpen];
    $closedCountSql = "SELECT COUNT(*) FROM tickets t WHERE t.status = ?";
    $closedCountParams = [$statusClosed];
} else {
    $openCountSql = "SELECT COUNT(*) FROM tickets t" . $whereClause . " AND t.status = ?";
    $openCountParams = array_merge($baseParams, [$statusOpen]);
    $closedCountSql = "SELECT COUNT(*) FROM tickets t" . $whereClause . " AND t.status = ?";
    $closedCountParams = array_merge($baseParams, [$statusClosed]);
}

$openCountStmt = $pdo->prepare($openCountSql);
$openCountStmt->execute($openCountParams);
$total_open_tickets = $openCountStmt->fetchColumn();

$closedCountStmt = $pdo->prepare($closedCountSql);
$closedCountStmt->execute($closedCountParams);
$total_closed_tickets = $closedCountStmt->fetchColumn();

// Get open tickets with pagination
$openStatusClause = empty($whereClause) ? " WHERE t.status = 'open'" : $whereClause . " AND t.status = 'open'";
$openSql = $baseSql . $openStatusClause . " ORDER BY t.created_at DESC LIMIT ? OFFSET ?";
$openParams = array_merge($baseParams, [$items_per_page, $offset]);
$openStmt = $pdo->prepare($openSql);
$openStmt->execute($openParams);
$openTickets = $openStmt->fetchAll();

// Get closed tickets with pagination  
$closedStatusClause = empty($whereClause) ? " WHERE t.status = 'closed'" : $whereClause . " AND t.status = 'closed'";
$closedSql = $baseSql . $closedStatusClause . " ORDER BY t.updated_at DESC LIMIT ? OFFSET ?";
$closedParams = array_merge($baseParams, [$items_per_page, $offset]);
$closedStmt = $pdo->prepare($closedSql);
$closedStmt->execute($closedParams);
$closedTickets = $closedStmt->fetchAll();

// Calculate actual displayed tickets for pagination info
$displayed_open = count($openTickets);
$displayed_closed = count($closedTickets);
$total_displayed = $displayed_open + $displayed_closed;

// Calculate the range being shown
$start_range = $total_displayed > 0 ? $offset + 1 : 0;
$end_range = min($offset + $total_displayed, $total_tickets);

// Combine for modal generation and other uses
$tickets = array_merge($openTickets, $closedTickets);

// Status mapping for display
$statusClasses = [
    'open' => 'bg-success text-white',
    'closed' => 'bg-secondary text-white'
];

$statusLabels = [
    'open' => $lang_frontend['STATUS_OPEN'] ?? 'Open',
    'closed' => $lang_frontend['STATUS_CLOSED'] ?? 'Closed'
];

// Handle search functionality for logged-in users
$searchQuery = isset($_GET['search']) ? trim(sanitizeInput($_GET['search'])) : '';
$searchResults = [];

if (isLoggedIn() && !empty($searchQuery)) {
    // Build search SQL for open tickets only
    // Security: All SQL structure is hardcoded, searchQuery is sanitized and passed as parameter
    // Status 'open' is a hardcoded string, not user input
    $baseSearchSql = "SELECT t.*, u.name as user_name, tc.name as category_name, tc.icon as category_icon, au.name as assigned_user_name, (SELECT COUNT(*) FROM ticket_replies c WHERE c.ticket_id = t.id) AS comment_count
                      FROM tickets t 
                      LEFT JOIN users u ON t.user_id = u.id AND u.id IS NOT NULL
                      LEFT JOIN ticket_categories tc ON t.category_id = tc.id
                      LEFT JOIN users au ON t.assigned_to = au.id
                      WHERE t.status = ? AND (t.subject LIKE ? OR t.message LIKE ?)";
    
    $statusOpen = 'open';
    $searchTerm = '%' . $searchQuery . '%';
    $searchParams = [$statusOpen, $searchTerm, $searchTerm];
    
    // Add user restrictions based on role
    // Security: All additional WHERE conditions are hardcoded strings
    if (!isAdminOrStaff()) {
        // Get the user's email for regular users (from database, not user input)
        $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'];
        }
        
        // Regular users can only search their own tickets
        // user_id from session (validated), email from database
        $baseSearchSql .= " AND (t.user_id = ? OR t.email = ?)";
        $searchParams[] = $_SESSION['user_id'];
        $searchParams[] = $user_email;
    } else if ($my_tickets_filter) {
        // Admin/staff with "My tickets" filter enabled
        // user_id from session (validated)
        $baseSearchSql .= " AND t.assigned_to = ?";
        $searchParams[] = $_SESSION['user_id'];
    }
    
    $baseSearchSql .= " ORDER BY t.created_at DESC";
    
    try {
        $searchStmt = $pdo->prepare($baseSearchSql);
        $searchStmt->execute($searchParams);
        $searchResults = $searchStmt->fetchAll();
    } catch (PDOException $e) {
        error_log("Search error: " . $e->getMessage());
        $searchResults = [];
    }
}
?>

<?php
// Process ticket actions based on POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle reopen ticket process
    if (isset($_POST['reopen_ticket'])) {
        // Validate CSRF token first
        if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
            redirectTo('tickets');
            exit;
        }
        
        $ticket_id = (int)$_POST['ticket_id'];

        try {
            // Permission check: only admin/staff or owner can reopen
            $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) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_NOT_FOUND_OR_NO_PERMISSION'] ?? 'Ticket not found or you do not have permission to reopen it.', 'danger');
                redirectTo('tickets');
                exit;
            }

            // Update ticket status to 'open'
            $stmt = $pdo->prepare("UPDATE tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$ticket_id]);

            // Log the reopening action as a system comment
            $reopenMessage = $lang_email['TICKET_SYSTEM_COMMENT_REOPENED_BY_USER'] ?? "Ticket reopened by user.";
            $stmt = $pdo->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message) VALUES (?, ?, ?)");
            $stmt->execute([$ticket_id, $_SESSION['user_id'], $reopenMessage]);

            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKET_REOPENED_SUCCESSFULLY_ID'] ?? 'Ticket #%d has been reopened successfully.', $ticket_id));
            redirectTo('tickets');
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_ERROR_REOPENING_TICKET'] ?? 'Error reopening ticket: %s', $e->getMessage()), 'danger');
        }
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><?php echo $lang_frontend['TICKETS_HEADING'] ?? 'Tickets'; ?></h2>
    <div class="d-flex flex-column flex-lg-row gap-3 align-items-start align-items-lg-center">
        <?php if (isLoggedIn()): ?>
        
        <?php if (isAdminOrStaff()): ?>
        <!-- My Tickets Toggle for Admin/Staff -->
        <div class="d-flex align-items-center">
            <div class="form-check form-switch mb-0">
                <input class="form-check-input" type="checkbox" id="myTicketsToggle" 
                       <?php echo $my_tickets_filter ? 'checked' : ''; ?>
                       onchange="toggleMyTickets(this.checked)">
                <label class="form-check-label" for="myTicketsToggle">
                    <?php echo $lang_frontend['TICKETS_LABEL_MY_TICKETS'] ?? 'My tickets'; ?>
                </label>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Controls Container for consistent sizing -->
        <div class="d-flex flex-column flex-sm-row gap-2 align-items-start align-items-sm-center">
            <!-- Items per page selector -->
            <form method="get" action="<?php echo getCleanUrl('tickets'); ?>" class="d-none d-lg-flex align-items-center">
                <?php if (!empty($email)): ?>
                    <input type="hidden" name="email" value="<?php echo htmlspecialchars($email); ?>">
                <?php endif; ?>
                <?php if (!empty($searchQuery)): ?>
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($searchQuery); ?>">
                <?php endif; ?>
                <?php if ($my_tickets_filter): ?>
                    <input type="hidden" name="my_tickets" value="1">
                <?php endif; ?>
                <label for="show" class="form-label me-2 mb-0 text-nowrap small"><?php echo $lang_frontend['LABEL_SHOW'] ?? 'Show:'; ?></label>
                <select name="show" id="show" class="form-select form-select-sm" style="width: auto; min-width: 70px;" onchange="this.form.submit()">
                    <option value="10" <?php echo $items_per_page == 10 ? 'selected' : ''; ?>>10</option>
                    <option value="25" <?php echo $items_per_page == 25 ? 'selected' : ''; ?>>25</option>
                    <option value="50" <?php echo $items_per_page == 50 ? 'selected' : ''; ?>>50</option>
                    <option value="100" <?php echo $items_per_page == 100 ? 'selected' : ''; ?>>100</option>
                </select>
            </form>
            
            <!-- Search Form for Logged-in Users -->
            <form method="get" action="<?php echo getCleanUrl('tickets'); ?>" class="d-none d-lg-flex">
                <?php if (!empty($email)): ?>
                    <input type="hidden" name="email" value="<?php echo htmlspecialchars($email); ?>">
                <?php endif; ?>
                <input type="hidden" name="show" value="<?php echo $items_per_page; ?>">
                <?php if ($my_tickets_filter): ?>
                    <input type="hidden" name="my_tickets" value="1">
                <?php endif; ?>
                <div class="input-group input-group-sm">
                    <input type="text" 
                           class="form-control" 
                           name="search" 
                           placeholder="<?php echo $lang_frontend['TICKETS_SEARCH_PLACEHOLDER'] ?? 'Search...'; ?>"
                           value="<?php echo htmlspecialchars($searchQuery); ?>"
                           style="min-width: 180px;">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i>
                    </button>
                    <?php if (!empty($searchQuery)): ?>
                    <a href="<?php echo getCleanUrl('tickets'); ?>" class="btn btn-outline-secondary" title="<?php echo $lang_frontend['FAQ_SEARCH_CLEAR_TITLE'] ?? 'Clear search'; ?>">
                        <i class="bi bi-x"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <a href="<?php echo getCleanUrl('ticket_create'); ?>" class="btn btn-primary text-white btn-sm">
            <i class="bi bi-plus"></i> <span class="d-none d-sm-inline"><?php echo $lang_frontend['TICKETS_BUTTON_NEW_TICKET'] ?? 'New Ticket'; ?></span><span class="d-sm-none"><?php echo $lang_frontend['TICKETS_BUTTON_NEW_TICKET_SHORT'] ?? 'New'; ?></span>
        </a>
    </div>
</div>

<?php if (!isLoggedIn() && ALLOW_GUEST_TICKETS): ?>
<div class="card mb-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><?php echo $lang_frontend['TICKETS_GUEST_LOOKUP_HEADER'] ?? 'Guest Ticket Lookup'; ?></h5>
    </div>
    <div class="card-body">
    <form method="get" action="<?php echo getCleanUrl('tickets'); ?>" class="row align-items-center">
        <div class="col-12 col-md-2 mb-2 mb-md-0">
            <label for="email" class="form-label text-md-end"><?php echo $lang_frontend['FORM_LABEL_EMAIL_ADDRESS'] ?? 'Email'; ?></label>
        </div>
        <div class="col-12 col-md-7 mb-2 mb-md-0">
            <input type="email" class="form-control" id="email" name="email" required value="<?php echo htmlspecialchars($email); ?>">
        </div>
        <div class="col-12 col-md-3">
            <button type="submit" class="btn btn-primary w-100">
                <i class="bi bi-search"></i> <?php echo $lang_frontend['TICKETS_BUTTON_FIND_TICKETS'] ?? 'Find Tickets'; ?>
            </button>
        </div>
    </form>
</div>

</div>
<?php endif; ?>

<?php if (isLoggedIn() && !empty($searchQuery)): ?>
<!-- Search Results Table -->
<div class="card mb-4">
    <div class="card-header bg-info text-white">
        <h5 class="mb-0">
            <i class="bi bi-search"></i> <?php echo sprintf($lang_frontend['SEARCH_RESULTS_FOR_QUERY'] ?? 'Search Results for "%s"', htmlspecialchars($searchQuery)); ?>
            <span class="badge bg-light text-dark ms-2"><?php echo sprintf($lang_frontend['SEARCH_RESULTS_COUNT_FOUND'] ?? '%d found', count($searchResults)); ?></span>
        </h5>
    </div>
    <div class="card-body p-0">
        <?php if (empty($searchResults)): ?>
        <div class="p-3">
            <div class="alert alert-info mb-0">
                <i class="bi bi-info-circle"></i> <?php echo $lang_frontend['TICKETS_NO_OPEN_TICKETS_SEARCH_RESULTS'] ?? 'No open tickets found matching your search criteria.'; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-striped table-hover mb-0">
                <thead>
                    <tr>
                        <th><?php echo $lang_frontend['TABLE_HEADER_ID'] ?? 'ID'; ?></th>
                        <th><?php echo $lang_frontend['TABLE_HEADER_SUBJECT'] ?? 'Subject'; ?></th>
                        <th><?php echo $lang_frontend['TABLE_HEADER_CATEGORY'] ?? 'Category'; ?></th>
                        <?php if (isAdminOrStaff()): ?>
                        <th><?php echo $lang_frontend['TABLE_HEADER_USER'] ?? 'User'; ?></th>
                        <th><?php echo $lang_frontend['TABLE_HEADER_ASSIGNED_TO'] ?? 'For'; ?></th>
                        <?php endif; ?>
                        <th><?php echo $lang_frontend['TABLE_HEADER_STATUS'] ?? 'Status'; ?></th>
                        <th class="d-none d-lg-table-cell"><?php echo $lang_frontend['TABLE_HEADER_CREATED'] ?? 'Created'; ?></th>
                        <th class="d-none d-lg-table-cell"><?php echo $lang_frontend['TABLE_HEADER_LAST_UPDATE'] ?? 'Last Update'; ?></th>
                        <th><?php echo $lang_frontend['TABLE_HEADER_ACTIONS'] ?? 'Actions'; ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($searchResults as $ticket): ?>
                    <tr>
                        <td>#<?php echo $ticket['id']; ?></td>
                        <td>
                            <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id']); ?>">
                                <?php echo $ticket['subject']; ?>
                                <?php if ($ticket['comment_count'] > 0): ?>
                                    <span class="badge rounded-pill bg-secondary ms-1"><?php echo $ticket['comment_count']; ?></span>
                                <?php endif; ?>
                                <?php if (!empty($ticket['attachment'])): ?>
                                    <i class="bi bi-paperclip ms-1" title="<?php echo $lang_frontend['TOOLTIP_HAS_ATTACHMENT'] ?? 'Has attachment'; ?>"></i>
                                <?php endif; ?>
                            </a>
                        </td>
                        <td>
                            <?php if (!empty($ticket['category_icon'])): ?>
                                <i class="bi bi-<?php echo htmlspecialchars($ticket['category_icon']); ?> text-primary"></i>
                            <?php elseif (!empty($ticket['category_name'])): ?>
                                <?php echo htmlspecialchars($ticket['category_name']); ?>
                            <?php else: ?>
                                <span class="text-muted"><?php echo $lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A'; ?></span>
                            <?php endif; ?>
                        </td>
                        <?php if (isAdminOrStaff()): ?>
                        <td>
                            <?php 
                            if (!empty($ticket['user_name'])) {
                                echo htmlspecialchars($ticket['user_name']);
                            } elseif (!empty($ticket['email'])) {
                                echo htmlspecialchars($ticket['email']) . ' ' . ($lang_frontend['TEXT_GUEST_SUFFIX'] ?? '(Guest)');
                            } else {
                                echo $lang_frontend['TEXT_GUEST_USER'] ?? 'Guest';
                            }
                            ?>
                        </td>
                        <td>
                            <?php 
                            if (!empty($ticket['assigned_user_name'])) {
                                echo htmlspecialchars($ticket['assigned_user_name']);
                            } else {
                                echo '<span class="text-muted">' . ($lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A') . '</span>';
                            }
                            ?>
                        </td>
                        <?php endif; ?>
                        <td>
                            <span class="badge <?php echo $statusClasses[$ticket['status']]; ?>">
                                <?php echo $statusLabels[$ticket['status']]; ?>
                            </span>
                        </td>
                        <td class="d-none d-lg-table-cell">
                            <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['created_at'])); ?>">
                                <?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>
                        </td>
                        <td class="d-none d-lg-table-cell">
                            <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['updated_at'])); ?>">
                                <?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>
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id']); ?>" class="btn btn-sm btn-primary text-white" title="<?php echo $lang_frontend['ACTION_BUTTON_VIEW_TOOLTIP'] ?? 'View'; ?>">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <?php if (isAdmin()): ?>
                                <button type="button" class="btn btn-sm btn-danger delete-ticket-btn" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#deleteTicketModal"
                                        data-ticket-id="<?php echo $ticket['id']; ?>"
                                        data-ticket-subject="<?php echo htmlspecialchars($ticket['subject']); ?>"
                                        title="<?php echo $lang_frontend['ACTION_BUTTON_DELETE_TOOLTIP'] ?? 'Delete'; ?>">
                                    <i class="bi bi-trash"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Pagination Info and Controls -->
<?php if ($total_tickets > 0 && empty($searchQuery) && !((!isLoggedIn() && empty($email)))): ?>
<div class="d-flex flex-column flex-lg-row justify-content-between align-items-start align-items-lg-center mb-3 gap-3">
    <div class="text-muted">
        <span class="d-block d-sm-inline"><?php echo sprintf($lang_frontend['TEXT_PAGINATION_SHOWING_TICKETS'] ?? 'Showing %d-%d of %d tickets', $start_range, $end_range, $total_tickets); ?></span>
        <?php if ($total_open_tickets > 0 || $total_closed_tickets > 0): ?>
            <small class="d-block">
                <?php echo sprintf($lang_frontend['TEXT_PAGINATION_TICKETS_SUB_INFO'] ?? '(%d of %d open, %d of %d closed on this page)', $displayed_open, $total_open_tickets, $displayed_closed, $total_closed_tickets); ?>
            </small>
        <?php endif; ?>
    </div>
    
    <?php if ($total_pages > 1): ?>
    <nav aria-label="<?php echo $lang_frontend['ARIA_LABEL_TICKETS_PAGINATION'] ?? 'Tickets pagination'; ?>">
        <ul class="pagination pagination-sm mb-0">
            <!-- Previous button -->
            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                <a class="page-link" href="<?php echo getCleanUrl('tickets', array_filter(['email' => $email, 'show' => $items_per_page, 'my_tickets' => $my_tickets_filter ? '1' : null, 'page' => $page - 1])); ?>">
                    <i class="bi bi-chevron-left"></i>
                </a>
            </li>
            
            <?php
            // Calculate page range to show
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            // Show first page if not in range
            if ($start_page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="<?php echo getCleanUrl('tickets', array_filter(['email' => $email, 'show' => $items_per_page, 'my_tickets' => $my_tickets_filter ? '1' : null, 'page' => 1])); ?>">1</a>
                </li>
                <?php if ($start_page > 2): ?>
                    <li class="page-item disabled"><span class="page-link"><?php echo $lang_frontend['TEXT_PAGINATION_ELLIPSIS'] ?? '...'; ?></span></li>
                <?php endif; ?>
            <?php endif; ?>
            
            <!-- Page numbers -->
            <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                    <a class="page-link" href="<?php echo getCleanUrl('tickets', array_filter(['email' => $email, 'show' => $items_per_page, 'my_tickets' => $my_tickets_filter ? '1' : null, 'page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
            <?php endfor; ?>
            
            <!-- Show last page if not in range -->
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <li class="page-item disabled"><span class="page-link"><?php echo $lang_frontend['TEXT_PAGINATION_ELLIPSIS'] ?? '...'; ?></span></li>
                <?php endif; ?>
                <li class="page-item">
                    <a class="page-link" href="<?php echo getCleanUrl('tickets', array_filter(['email' => $email, 'show' => $items_per_page, 'my_tickets' => $my_tickets_filter ? '1' : null, 'page' => $total_pages])); ?>"><?php echo $total_pages; ?></a>
                </li>
            <?php endif; ?>
            
            <!-- Next button -->
            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                <a class="page-link" href="<?php echo getCleanUrl('tickets', array_filter(['email' => $email, 'show' => $items_per_page, 'my_tickets' => $my_tickets_filter ? '1' : null, 'page' => $page + 1])); ?>">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>
<?php endif; ?>

<div class="row">
    <?php if (!isLoggedIn() && empty($email)): ?>
    <div class="col-12">
        <div class="alert alert-success">
            <i class="bi bi-info-circle"></i> <?php echo $lang_frontend['TICKETS_GUEST_ENTER_EMAIL_PROMPT'] ?? 'Please enter your email address above to view your tickets.'; ?>
        </div>
    </div>
    <?php elseif (empty($tickets) && empty($searchQuery)): ?>
    <div class="col-12">
        <div class="alert alert-info">
           <i class="bi bi-info-circle"></i> <?php echo $lang_frontend['TICKETS_NO_TICKETS_PROMPT_CREATE'] ?? 'No tickets found. Click the "New Ticket" button to create your first support ticket.'; ?>
        </div>
    </div>
    <?php else: ?>
    <!-- Open Tickets -->
    <div class="col-12 mb-4">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['TICKETS_OPEN_HEADER'] ?? 'Open'; ?></h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($openTickets)): ?>
                <div class="p-3">
                    <div class="alert alert-info mb-0">
                        <i class="bi bi-info-circle"></i> <?php echo $lang_frontend['TICKETS_NO_OPEN_TICKETS'] ?? 'No open tickets found.'; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead>
                            <tr>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ID'] ?? 'ID'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_SUBJECT'] ?? 'Subject'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_CATEGORY'] ?? 'Category'; ?></th>
                                <?php if (isAdminOrStaff()): ?>
                                <th><?php echo $lang_frontend['TABLE_HEADER_USER'] ?? 'User'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ASSIGNED_TO'] ?? 'For'; ?></th>
                                <?php endif; ?>
                               
                                <th class="d-none d-lg-table-cell"><?php echo $lang_frontend['TABLE_HEADER_CREATED'] ?? 'Created'; ?></th>
                                <th class="d-none d-lg-table-cell"><?php echo $lang_frontend['TABLE_HEADER_LAST_UPDATE'] ?? 'Last Update'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ACTIONS'] ?? 'Actions'; ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($openTickets as $ticket): ?>
                            <tr>
                                <td>#<?php echo $ticket['id']; ?></td>
                                <td>
                                    <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id'], !isLoggedIn() && !empty($email) ? ['email' => $email] : []); ?>">
                                        <?php echo $ticket['subject']; ?>
                                        <?php if ($ticket['comment_count'] > 0): ?>
                                            <span class="badge rounded-pill bg-secondary ms-1"><?php echo $ticket['comment_count']; ?></span>
                                        <?php endif; ?>
                                        <?php if (!empty($ticket['attachment'])): ?>
                                            <i class="bi bi-paperclip ms-1" title="<?php echo $lang_frontend['TOOLTIP_HAS_ATTACHMENT'] ?? 'Has attachment'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td>
                                    <?php if (!empty($ticket['category_icon'])): ?>
                                        <i class="bi bi-<?php echo htmlspecialchars($ticket['category_icon']); ?> text-primary"></i>
                                    <?php elseif (!empty($ticket['category_name'])): ?>
                                        <?php echo htmlspecialchars($ticket['category_name']); ?>
                                    <?php else: ?>
                                        <span class="text-muted"><?php echo $lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A'; ?></span>
                                    <?php endif; ?>
                                </td>
                                <?php if (isAdminOrStaff()): ?>
                                <td>
                                    <?php 
                                    if (!empty($ticket['user_name'])) {
                                        echo htmlspecialchars($ticket['user_name']);
                                    } elseif (!empty($ticket['email'])) {
                                        echo htmlspecialchars($ticket['email']) . ' ' . ($lang_frontend['TEXT_GUEST_SUFFIX'] ?? '(Guest)');
                                    } else {
                                        echo $lang_frontend['TEXT_GUEST_USER'] ?? 'Guest';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    if (!empty($ticket['assigned_user_name'])) {
                                        echo htmlspecialchars($ticket['assigned_user_name']);
                                    } else {
                                        echo '<span class="text-muted">' . ($lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A') . '</span>';
                                    }
                                    ?>
                                </td>
                                <?php endif; ?>
                                
                                <td class="d-none d-lg-table-cell">
                                    <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['created_at'])); ?>">
                                        <?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>
                                </td>
                                <td class="d-none d-lg-table-cell">
                                    <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['updated_at'])); ?>">
                                        <?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>
                                </td>
                                <td>
                                    <div class="btn-group">
                                        <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id'], !isLoggedIn() && !empty($email) ? ['email' => $email] : []); ?>" class="btn btn-sm btn-primary text-white" title="<?php echo $lang_frontend['ACTION_BUTTON_VIEW_TOOLTIP'] ?? 'View'; ?>">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <?php if (isAdmin()): ?>
                                        <button type="button" class="btn btn-sm btn-danger delete-ticket-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#deleteTicketModal"
                                                data-ticket-id="<?php echo $ticket['id']; ?>"
                                                data-ticket-subject="<?php echo htmlspecialchars($ticket['subject']); ?>"
                                                title="<?php echo $lang_frontend['ACTION_BUTTON_DELETE_TOOLTIP'] ?? 'Delete'; ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Closed Tickets -->
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['TICKETS_CLOSED_HEADER'] ?? 'Closed'; ?></h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($closedTickets)): ?>
                <div class="p-3">
                    <div class="alert alert-info mb-0">
                        <i class="bi bi-info-circle"></i> <?php echo $lang_frontend['TICKETS_NO_CLOSED_TICKETS'] ?? 'No closed tickets found.'; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead>
                            <tr>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ID'] ?? 'ID'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_SUBJECT'] ?? 'Subject'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_CATEGORY'] ?? 'Category'; ?></th>
                                <?php if (isAdminOrStaff()): ?>
                                <th><?php echo $lang_frontend['TABLE_HEADER_USER'] ?? 'User'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ASSIGNED_TO'] ?? 'For'; ?></th>
                                <?php endif; ?>
                                
                                
                                <th class="d-none d-lg-table-cell"><?php echo $lang_frontend['TABLE_HEADER_LAST_UPDATE'] ?? 'Last Update'; ?></th>
                                <th><?php echo $lang_frontend['TABLE_HEADER_ACTIONS'] ?? 'Actions'; ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($closedTickets as $ticket): ?>
                            <tr>
                                <td>#<?php echo $ticket['id']; ?></td>
                                <td>
                                    <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id'], !isLoggedIn() && !empty($email) ? ['email' => $email] : []); ?>">
                                        <?php echo $ticket['subject']; ?>
                                        <?php if ($ticket['comment_count'] > 0): ?>
                                            <span class="badge rounded-pill bg-secondary ms-1"><?php echo $ticket['comment_count']; ?></span>
                                        <?php endif; ?>
                                        <?php if (!empty($ticket['attachment'])): ?>
                                            <i class="bi bi-paperclip ms-1" title="<?php echo $lang_frontend['TOOLTIP_HAS_ATTACHMENT'] ?? 'Has attachment'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td>
                                    <?php if (!empty($ticket['category_icon'])): ?>
                                        <i class="bi bi-<?php echo htmlspecialchars($ticket['category_icon']); ?> text-primary"></i>
                                    <?php elseif (!empty($ticket['category_name'])): ?>
                                        <?php echo htmlspecialchars($ticket['category_name']); ?>
                                    <?php else: ?>
                                        <span class="text-muted"><?php echo $lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A'; ?></span>
                                    <?php endif; ?>
                                </td>
                                <?php if (isAdminOrStaff()): ?>
                                <td>
                                    <?php 
                                    if (!empty($ticket['user_name'])) {
                                        echo htmlspecialchars($ticket['user_name']);
                                    } elseif (!empty($ticket['email'])) {
                                        echo htmlspecialchars($ticket['email']) . ' ' . ($lang_frontend['TEXT_GUEST_SUFFIX'] ?? '(Guest)');
                                    } else {
                                        echo $lang_frontend['TEXT_GUEST_USER'] ?? 'Guest';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    if (!empty($ticket['assigned_user_name'])) {
                                        echo htmlspecialchars($ticket['assigned_user_name']);
                                    } else {
                                        echo '<span class="text-muted">' . ($lang_frontend['TEXT_NA_NOT_APPLICABLE'] ?? 'N/A') . '</span>';
                                    }
                                    ?>
                                </td>
                                <?php endif; ?>
                                
                                
                                <td class="d-none d-lg-table-cell">
                                    <span title="<?php echo htmlspecialchars(getFormattedDate($ticket['updated_at'])); ?>">
                                        <?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>
                                </td>
                                <td>
                                   <div class="d-inline">
    <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id'], !isLoggedIn() && !empty($email) ? ['email' => $email] : []); ?>" class="btn btn-sm btn-primary text-white" title="<?php echo $lang_frontend['ACTION_BUTTON_VIEW_TOOLTIP'] ?? 'View'; ?>">
        <i class="bi bi-eye"></i>
    </a>

    <?php if(isLoggedIn()): ?>
    
        <form method="post" action="" class="d-inline">
            <?php echo get_csrf_input_field(); ?>
            <input type="hidden" name="ticket_id" value="<?php echo $ticket['id']; ?>">
            <button type="submit" name="reopen_ticket" class="btn btn-outline-primary btn-sm text-primary">
                <i class="bi bi-arrow-counterclockwise"></i> <?php echo $lang_frontend['BUTTON_REOPEN'] ?? 'Reopen'; ?>
            </button>
        </form>
  
    <?php endif; ?>

    <?php if (isAdmin()): ?>
    <button type="button" class="btn btn-sm btn-danger delete-ticket-btn" 
            data-bs-toggle="modal" 
            data-bs-target="#deleteTicketModal"
            data-ticket-id="<?php echo $ticket['id']; ?>"
            data-ticket-subject="<?php echo htmlspecialchars($ticket['subject']); ?>"
            title="<?php echo $lang_frontend['ACTION_BUTTON_DELETE_TOOLTIP'] ?? 'Delete'; ?>">
        <i class="bi bi-trash"></i>
    </button>
    <?php endif; ?>
</div>

                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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

<!-- Delete Ticket Modal -->
<div class="modal fade" id="deleteTicketModal" tabindex="-1" aria-labelledby="deleteTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteTicketModalLabel"><?php echo $lang_frontend['MODAL_TITLE_DELETE_TICKET'] ?? 'Delete Ticket'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
            </div>
            <div class="modal-body">
                <p><?php echo sprintf($lang_frontend['MODAL_TEXT_CONFIRM_DELETE_TICKET_ID'] ?? 'Are you sure you want to delete ticket #%s?', '<span id="ticketIdToDelete"></span>'); ?></p>
                <p><strong><?php echo $lang_frontend['MODAL_TEXT_SUBJECT_LABEL'] ?? 'Subject:'; ?></strong> <span id="ticketSubjectToDelete"></span></p>
                <p class="text-danger"><?php echo $lang_frontend['MODAL_TEXT_ACTION_CANNOT_BE_UNDONE'] ?? 'This action cannot be undone.'; ?></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>
                <form method="post" action="<?php echo getCleanUrl('ticket_delete'); ?>">
                    <?php echo get_csrf_input_field(); ?>
                    <input type="hidden" name="id" id="ticketIdInput" value="">
                    <button type="submit" class="btn btn-danger"><?php echo $lang_frontend['BUTTON_DELETE'] ?? 'Delete'; ?></button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Delete Ticket Modal
    const deleteTicketModal = document.getElementById('deleteTicketModal');
    if (deleteTicketModal) {
        deleteTicketModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const ticketId = button.getAttribute('data-ticket-id');
            const ticketSubject = button.getAttribute('data-ticket-subject');

            // Update modal content
            this.querySelector('#ticketIdToDelete').textContent = ticketId;
            this.querySelector('#ticketSubjectToDelete').textContent = ticketSubject;
            this.querySelector('#ticketIdInput').value = ticketId;
        });
    }
});

// Function to handle My Tickets toggle
function toggleMyTickets(checked) {
    const url = new URL(window.location);
    
    if (checked) {
        url.searchParams.set('my_tickets', '1');
    } else {
        url.searchParams.delete('my_tickets');
    }
    
    // Reset to first page when toggling filter
    url.searchParams.delete('page');
    
    window.location.href = url.toString();
}
</script>
