<?php include __DIR__ . '/../includes/header.php'; ?>

<?php
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'] ?? 'You do not have permission to access this page', 'danger');
   redirectTo(getCleanUrl('index'));
}

// Handle bulk operations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    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(getCleanUrl('admin/tickets'));
        exit;
    }

    $bulk_action = $_POST['bulk_action'];
    $selected_tickets = $_POST['selected_tickets'] ?? [];

    if (empty($selected_tickets)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKETS_NO_BULK_SELECTION'] ?? 'No tickets selected for bulk action.', 'warning');
        redirectTo(getCleanUrl('admin/tickets'));
        exit;
    }

    $ticket_ids = array_map('intval', $selected_tickets);
    $placeholders = str_repeat('?,', count($ticket_ids) - 1) . '?';

    try {
        switch ($bulk_action) {
            case 'delete':
                foreach ($ticket_ids as $tid) {
                    deleteTicketAttachmentFilesFromDisk($pdo, (int) $tid);
                }
                $stmt = $pdo->prepare("DELETE FROM tickets WHERE id IN ($placeholders)");
                $stmt->execute($ticket_ids);
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKETS_BULK_DELETED_SUCCESS'] ?? '%d ticket(s) deleted successfully.', count($ticket_ids)), 'success');
                break;

            case 'close':
                $stmt = $pdo->prepare("UPDATE tickets SET status = 'closed' WHERE id IN ($placeholders)");
                $stmt->execute($ticket_ids);
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKETS_BULK_CLOSED_SUCCESS'] ?? '%d ticket(s) closed successfully.', count($ticket_ids)), 'success');
                break;

            case 'change_priority':
                $new_priority = $_POST['new_priority'] ?? 'medium';
                if (!in_array($new_priority, ['low', 'medium', 'high'])) {
                    $new_priority = 'medium';
                }
                // For display, get translated priority if possible
                $priority_display_key = 'TICKET_PRIORITY_' . strtoupper($new_priority);
                $priority_display_text = $lang_admin[$priority_display_key] ?? ucfirst($new_priority);

                $params = array_merge([$new_priority], $ticket_ids);
                $stmt = $pdo->prepare("UPDATE tickets SET priority = ? WHERE id IN ($placeholders)");
                $stmt->execute($params);
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKETS_BULK_PRIORITY_CHANGED_SUCCESS'] ?? '%d ticket(s) priority changed to %s successfully.', count($ticket_ids), $priority_display_text), 'success');
                break;

            default:
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKETS_INVALID_BULK_ACTION'] ?? 'Invalid bulk action.', 'danger');
                break;
        }
    } catch (PDOException $e) {
        $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKETS_BULK_ACTION_ERROR'] ?? 'Error performing bulk action: %s', $e->getMessage()), 'danger');
    }

    redirectTo(getCleanUrl('admin/tickets'));
    exit;
}

// Handle ticket deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_ticket'])) {
    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(getCleanUrl('admin/tickets'));
        exit;
    } else {
        $ticket_id = (int)$_POST['delete_ticket'];

        try {
            deleteTicketAttachmentFilesFromDisk($pdo, $ticket_id);
            // Delete ticket (cascading will handle ticket_replies)
            $stmt = $pdo->prepare("DELETE FROM tickets WHERE id = ?");
            $stmt->execute([$ticket_id]);

            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKET_DELETED_SUCCESS'] ?? 'Ticket #%d has been deleted successfully', $ticket_id), 'success');
            redirectTo(getCleanUrl('admin/tickets'));
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKET_DELETE_ERROR'] ?? 'Error deleting ticket: %s', $e->getMessage()), 'danger');
        }
    }
}

// Handle advanced search and filters
$status_filter = $_GET['status'] ?? 'all';
$priority_filter = $_GET['priority'] ?? 'all';
$user_filter = $_GET['user'] ?? '';
$search_query = isset($_GET['search']) ? trim(sanitizeInput($_GET['search'])) : '';

// Pagination settings with cookie support
$items_per_page = isset($_GET['show']) ? (int)$_GET['show'] : (isset($_COOKIE['admin_tickets_per_page']) ? (int)$_COOKIE['admin_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['admin_tickets_per_page']) ? (int)$_COOKIE['admin_tickets_per_page'] : 25)) {
    setcookie('admin_tickets_per_page', $items_per_page, time() + (365 * 24 * 60 * 60), '/'); // 1 year expiry
}

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

// Get all users for the dropdown
$user_stmt = $pdo->prepare("SELECT id, name, email FROM users ORDER BY name ASC");
$user_stmt->execute();
$all_users = $user_stmt->fetchAll();

// Build query
$query = "
    SELECT t.*, u.name as user_name, tc.name as category_name 
    FROM tickets t 
    LEFT JOIN users u ON t.user_id = u.id 
    LEFT JOIN ticket_categories tc ON t.category_id = tc.id
    WHERE 1=1 
";

$params = [];

// Add search filters
if (!empty($search_query)) {
    $query .= " AND (t.subject LIKE ? OR t.message LIKE ? OR t.email LIKE ? OR u.name LIKE ? OR u.email LIKE ?) ";
    $search_param = '%' . $search_query . '%';
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
}

if ($status_filter !== 'all') {
    $query .= " AND t.status = ? ";
    $params[] = $status_filter;
}

if ($priority_filter !== 'all') {
    $query .= " AND t.priority = ? ";
    $params[] = $priority_filter;
}

if (!empty($user_filter)) {
    if ($user_filter === 'guest') {
        $query .= " AND t.user_id IS NULL ";
    } else {
        $query .= " AND t.user_id = ? ";
        $params[] = (int)$user_filter;
    }
}

$query .= " ORDER BY t.created_at DESC";

// Get total count for pagination
$countQuery = str_replace("SELECT t.*, u.name as user_name, tc.name as category_name", "SELECT COUNT(*)", $query);
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$total_tickets = $countStmt->fetchColumn();
$total_pages = ceil($total_tickets / $items_per_page);

// Add pagination to main query
$query .= " LIMIT ? OFFSET ?";
$params[] = $items_per_page;
$params[] = $offset;

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$tickets = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h4><?php echo $lang_admin['ADMIN_TICKETS_PAGE_TITLE'] ?? 'Manage Tickets'; ?></h4>
    <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
        <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD'] ?? 'Back to Dashboard'; ?>
    </a>
</div>

<!-- Advanced Search Section -->
<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 $lang_admin['ADMIN_TICKETS_SEARCH_ADVANCED_TITLE'] ?? 'Advanced Search'; ?>
            <?php if (!empty($search_query) || $status_filter !== 'all' || $priority_filter !== 'all' || !empty($user_filter)): ?>
                <span class="badge bg-light text-dark ms-2"><?php echo sprintf($lang_admin['ADMIN_TICKETS_SEARCH_RESULTS_BADGE'] ?? '%s results', $total_tickets); ?></span>
            <?php endif; ?>
        </h5>
    </div>
    <div class="card-body">
        <form action="tickets" method="get" class="row g-3">
            <!-- Text Search -->
            <div class="col-md-6">
                <label for="search" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_SEARCH_TEXT'] ?? 'Search Text'; ?></label>
                <div class="input-group">
                    <input type="text" 
                           class="form-control" 
                           id="search" 
                           name="search" 
                           placeholder="<?php echo $lang_admin['ADMIN_TICKETS_PLACEHOLDER_SEARCH'] ?? 'Search in subject, message, user name, or email...'; ?>"
                           value="<?php echo htmlspecialchars($search_query); ?>">
                    <?php if (!empty($search_query)): ?>
                    <a href="<?php echo getCleanUrl('admin/tickets'); ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-x"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- User Filter -->
            <div class="col-md-6">
                <label for="user" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_USER'] ?? 'User'; ?></label>
                <select class="form-select" id="user" name="user">
                    <option value="" <?php echo empty($user_filter) ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_TICKETS_USER_ALL'] ?? 'All Users'; ?></option>
                    <option value="guest" <?php echo $user_filter === 'guest' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_TICKETS_USER_GUEST'] ?? 'Guest Users'; ?></option>
                    <?php foreach ($all_users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $user_filter == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['name']); ?> (<?php echo htmlspecialchars($user['email']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <!-- Status Filter -->
            <div class="col-md-3">
                <label for="status" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_STATUS'] ?? 'Status'; ?></label>
                <select class="form-select" id="status" name="status">
                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_TICKETS_STATUS_ALL'] ?? 'All Statuses'; ?></option>
                    <option value="open" <?php echo $status_filter === 'open' ? 'selected' : ''; ?>><?php echo $lang_admin['TICKET_STATUS_OPEN'] ?? 'Open'; ?></option>
                    <option value="closed" <?php echo $status_filter === 'closed' ? 'selected' : ''; ?>><?php echo $lang_admin['TICKET_STATUS_CLOSED'] ?? 'Closed'; ?></option>
                </select>
            </div>
            
            <!-- Priority Filter -->
            <div class="col-md-3">
                <label for="priority" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_PRIORITY'] ?? 'Priority'; ?></label>
                <select class="form-select" id="priority" name="priority">
                    <option value="all" <?php echo $priority_filter === 'all' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_TICKETS_PRIORITY_ALL'] ?? 'All Priorities'; ?></option>
                    <option value="low" <?php echo $priority_filter === 'low' ? 'selected' : ''; ?>><?php echo $lang_admin['TICKET_PRIORITY_LOW'] ?? 'Low'; ?></option>
                    <option value="medium" <?php echo $priority_filter === 'medium' ? 'selected' : ''; ?>><?php echo $lang_admin['TICKET_PRIORITY_MEDIUM'] ?? 'Medium'; ?></option>
                    <option value="high" <?php echo $priority_filter === 'high' ? 'selected' : ''; ?>><?php echo $lang_admin['TICKET_PRIORITY_HIGH'] ?? 'High'; ?></option>
                </select>
            </div>
            
            <!-- Search Buttons -->
            <div class="col-md-6 d-flex align-items-end gap-2">
                <!-- Items per page selector -->
                <div class="d-flex align-items-center me-3">
                    <label for="show" class="form-label me-2 mb-0"><?php echo $lang_admin['ADMIN_TICKETS_LBL_SHOW'] ?? 'Show:'; ?></label>
                    <select name="show" id="show" class="form-select form-select-sm" style="width: auto;">
                        <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>
                </div>
                
                <button type="submit" class="btn btn-info text-white">
                    <i class="bi bi-search"></i> <?php echo $lang_admin['ADMIN_TICKETS_BTN_SEARCH_ADVANCED'] ?? 'Search'; ?>
                </button>
                <a href="<?php echo getCleanUrl('admin/tickets'); ?>" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise"></i> <?php echo $lang_admin['ADMIN_TICKETS_BTN_RESET_FILTERS'] ?? 'Reset'; ?>
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Pagination Info and Controls -->
<?php if ($total_tickets > 0): ?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <div class="text-muted">
        <?php echo sprintf($lang_admin['ADMIN_TICKETS_PAGINATION_SHOWING_OF'] ?? 'Showing %d-%d of %d tickets', min($offset + 1, $total_tickets), min($offset + $items_per_page, $total_tickets), $total_tickets); ?>
    </div>
    
    <?php if ($total_pages > 1): ?>
    <nav aria-label="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('admin/tickets', array_filter(['search' => $search_query, 'status' => $status_filter !== 'all' ? $status_filter : '', 'priority' => $priority_filter !== 'all' ? $priority_filter : '', 'user' => $user_filter, 'show' => $items_per_page, '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('admin/tickets', array_filter(['search' => $search_query, 'status' => $status_filter !== 'all' ? $status_filter : '', 'priority' => $priority_filter !== 'all' ? $priority_filter : '', 'user' => $user_filter, 'show' => $items_per_page, 'page' => 1])); ?>">1</a>
                </li>
                <?php if ($start_page > 2): ?>
                    <li class="page-item disabled"><span class="page-link">...</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('admin/tickets', array_filter(['search' => $search_query, 'status' => $status_filter !== 'all' ? $status_filter : '', 'priority' => $priority_filter !== 'all' ? $priority_filter : '', 'user' => $user_filter, 'show' => $items_per_page, '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">...</span></li>
                <?php endif; ?>
                <li class="page-item">
                    <a class="page-link" href="<?php echo getCleanUrl('admin/tickets', array_filter(['search' => $search_query, 'status' => $status_filter !== 'all' ? $status_filter : '', 'priority' => $priority_filter !== 'all' ? $priority_filter : '', 'user' => $user_filter, 'show' => $items_per_page, '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('admin/tickets', array_filter(['search' => $search_query, 'status' => $status_filter !== 'all' ? $status_filter : '', 'priority' => $priority_filter !== 'all' ? $priority_filter : '', 'user' => $user_filter, 'show' => $items_per_page, 'page' => $page + 1])); ?>">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Bulk Operations Controls -->
<div class="card mb-4" id="bulkControls" style="display: none;">
    <div class="card-header bg-secondary text-white">
        <h5 class="mb-0"><?php echo $lang_admin['ADMIN_TICKETS_BULK_OPERATIONS_TITLE'] ?? 'Bulk Operations'; ?></h5>
    </div>
    <div class="card-body">
        <form id="bulkForm" action="tickets" method="post">
            <?php echo get_csrf_input_field(); ?>
            <div class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label for="bulk_action" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_BULK_ACTION'] ?? 'Action'; ?></label>
                    <select class="form-select" id="bulk_action" name="bulk_action" required>
                        <option value=""><?php echo $lang_admin['ADMIN_TICKETS_BULK_ACTION_CHOOSE'] ?? 'Choose action...'; ?></option>
                        <option value="delete"><?php echo $lang_admin['ADMIN_TICKETS_BULK_ACTION_DELETE'] ?? 'Delete Tickets'; ?></option>
                        <option value="close"><?php echo $lang_admin['ADMIN_TICKETS_BULK_ACTION_CLOSE'] ?? 'Close Tickets'; ?></option>
                        <option value="change_priority"><?php echo $lang_admin['ADMIN_TICKETS_BULK_ACTION_CHANGE_PRIORITY'] ?? 'Change Priority'; ?></option>
                    </select>
                </div>
                <div class="col-md-3" id="prioritySelector" style="display: none;">
                    <label for="new_priority" class="form-label"><?php echo $lang_admin['ADMIN_TICKETS_LBL_NEW_PRIORITY'] ?? 'New Priority'; ?></label>
                    <select class="form-select" id="new_priority" name="new_priority">
                        <option value="low"><?php echo $lang_admin['TICKET_PRIORITY_LOW'] ?? 'Low'; ?></option>
                        <option value="medium"><?php echo $lang_admin['TICKET_PRIORITY_MEDIUM'] ?? 'Medium'; ?></option>
                        <option value="high"><?php echo $lang_admin['TICKET_PRIORITY_HIGH'] ?? 'High'; ?></option>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="button" class="btn btn-primary" id="executeBulk">
                        <i class="bi bi-check-circle"></i> <?php echo $lang_admin['ADMIN_TICKETS_BTN_EXECUTE_BULK'] ?? 'Execute Action'; ?>
                    </button>
                    <span class="text-muted ms-2" id="selectedCount"><?php echo sprintf($lang_admin['ADMIN_TICKETS_BULK_SELECTED_COUNT'] ?? '%d selected', 0); ?></span>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><?php echo $lang_admin['ADMIN_TICKETS_TABLE_TITLE_ALL'] ?? 'All Tickets'; ?></h5>
    </div>
    <div class="card-body">
        <?php if (count($tickets) > 0): ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" class="form-check-input" id="selectAll" title="<?php echo $lang_admin['ADMIN_TICKETS_TH_SELECT_ALL_TOOLTIP'] ?? 'Select all tickets'; ?>">
                            </th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_ID'] ?? 'ID'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_SUBJECT'] ?? 'Subject'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_CATEGORY'] ?? 'Category'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_USER'] ?? 'User'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_PRIORITY'] ?? 'Priority'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_STATUS'] ?? 'Status'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_TICKETS_TH_CREATED'] ?? 'Created'; ?></th>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_ACTIONS'] ?? 'Actions'; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($tickets as $ticket): ?>
                            <tr>
                                <td>
                                    <input type="checkbox" class="form-check-input ticket-checkbox" name="ticket_ids[]" value="<?php echo $ticket['id']; ?>">
                                </td>
                                <td>#<?php echo $ticket['id']; ?></td>
                                <td>
                                    <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id']); ?>"><?php echo $ticket['subject']; ?></a>
                                    <?php if (!empty($ticket['attachment'])): ?>
                                        <i class="bi bi-paperclip ms-1" title="<?php echo $lang_admin['ADMIN_TICKETS_TOOLTIP_HAS_ATTACHMENT'] ?? 'Has attachment'; ?>"></i>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $ticket['category_name'] ? htmlspecialchars($ticket['category_name']) : '<span class="text-muted">' . ($lang_admin['ADMIN_TICKETS_TEXT_NA_CATEGORY'] ?? 'N/A') . '</span>'; ?></td>
                                <td><?php echo $ticket['user_name'] ?? htmlspecialchars($ticket['email']); ?></td>
                                <td>
                                    <?php
                                    $priority_key = 'TICKET_PRIORITY_' . strtoupper($ticket['priority']);
                                    $priority_text = $lang_admin[$priority_key] ?? ucfirst($ticket['priority']);
                                    $priority_class = 'bg-info text-dark'; // Default for Low
                                    if ($ticket['priority'] === 'high') $priority_class = 'bg-danger';
                                    elseif ($ticket['priority'] === 'medium') $priority_class = 'bg-warning text-dark';
                                    ?>
                                    <span class="badge <?php echo $priority_class; ?>"><?php echo $priority_text; ?></span>
                                </td>
                                <td>
                                    <?php
                                    $status_key = 'TICKET_STATUS_' . strtoupper($ticket['status']);
                                    $status_text = $lang_admin[$status_key] ?? ucfirst($ticket['status']);
                                    $status_class = $ticket['status'] === 'open' ? 'bg-success' : 'bg-secondary';
                                    ?>
                                    <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                </td>
                                <td><?php echo getFormattedDate($ticket['created_at'], DATE_FORMAT); ?></td>
                                <td>
                                    <div class="btn-group">
                                        <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id']); ?>" class="btn btn-sm btn-primary">
                                            <i class="bi bi-eye"></i> <?php echo $lang_admin['ADMIN_TICKETS_BTN_VIEW'] ?? 'View'; ?>
                                        </a>
                                        <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']); ?>">
                                            <i class="bi bi-trash"></i> <?php echo $lang_admin['ADMIN_TICKETS_BTN_DELETE'] ?? 'Delete'; ?>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i> <?php echo $lang_admin['ADMIN_TICKETS_NO_MATCHING_CRITERIA'] ?? 'No tickets found matching your criteria.'; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- 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_admin['ADMIN_TICKETS_MODAL_DELETE_TITLE'] ?? 'Confirm Deletion'; ?></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 id="deleteTicketConfirmationText"><?php /* Populated by JS */ ?></p>
                <p class="text-danger mt-2"><?php echo $lang_admin['ADMIN_TICKETS_MODAL_DELETE_WARNING_UNDONE'] ?? 'This action cannot be undone and will remove all associated replies.'; ?></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 action="tickets" method="post" style="display: inline;" id="deleteTicketForm">
                    <?php echo get_csrf_input_field(); ?>
                    <input type="hidden" name="delete_ticket" id="deleteTicketId" value="">
                    <button type="submit" class="btn btn-danger"><?php echo $lang_admin['ADMIN_TICKETS_MODAL_BTN_DELETE_CONFIRM'] ?? 'Delete Ticket'; ?></button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Confirmation Modals -->
<div class="modal fade" id="bulkConfirmModal" tabindex="-1" aria-labelledby="bulkConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkConfirmModalLabel"><?php echo $lang_admin['ADMIN_TICKETS_MODAL_BULK_CONFIRM_TITLE'] ?? 'Confirm Bulk Action'; ?></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 id="bulkConfirmText"></p>
                <p class="text-warning mt-2" id="bulkWarning" style="display: none;">
                    <i class="bi bi-exclamation-triangle"></i> <?php echo $lang_admin['ADMIN_PRODUCTS_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>
                <button type="button" class="btn btn-danger" id="confirmBulkAction"><?php echo $lang_admin['ADMIN_TICKETS_MODAL_BTN_BULK_CONFIRM'] ?? 'Confirm'; ?></button>
            </div>
        </div>
    </div>
</div>

<script>
const lang_tickets_js = {
    alert_select_one_ticket: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_JS_ALERT_SELECT_ONE_TICKET'] ?? 'Please select at least one ticket.'); ?>',
    alert_select_action: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_JS_ALERT_SELECT_ACTION'] ?? 'Please select an action.'); ?>',
    confirm_delete_count: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_JS_CONFIRM_DELETE_COUNT'] ?? 'Are you sure you want to delete %d ticket(s)?'); ?>',
    confirm_close_count: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_JS_CONFIRM_CLOSE_COUNT'] ?? 'Are you sure you want to close %d ticket(s)?'); ?>',
    confirm_change_priority_count: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_JS_CONFIRM_CHANGE_PRIORITY_COUNT'] ?? 'Are you sure you want to change the priority of %d ticket(s) to %s?'); ?>',
    delete_modal_text: '<?php echo addslashes($lang_admin['ADMIN_TICKETS_MODAL_CONFIRM_DELETE_TEXT'] ?? 'Are you sure you want to delete ticket #%s: <strong>%s</strong>?'); ?>'
};

document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const ticketCheckboxes = document.querySelectorAll('.ticket-checkbox');
    const bulkControls = document.getElementById('bulkControls');
    const selectedCount = document.getElementById('selectedCount');
    const bulkActionSelect = document.getElementById('bulk_action');
    const prioritySelector = document.getElementById('prioritySelector');
    const executeBulkBtn = document.getElementById('executeBulk');
    const bulkForm = document.getElementById('bulkForm');
    const bulkConfirmModal = new bootstrap.Modal(document.getElementById('bulkConfirmModal'));

    // Update count and show/hide bulk controls
    function updateBulkControls() {
        const selectedTickets = document.querySelectorAll('.ticket-checkbox:checked');
        const count = selectedTickets.length;
        
        selectedCount.textContent = count + ' ' + ('<?php echo $lang_admin['ADMIN_TICKETS_BULK_SELECTED_COUNT_TEXT_ONLY'] ?? 'selected'; ?>'.replace('%d', count)); // A bit hacky for plural if needed
        
        if (count > 0) {
            bulkControls.style.display = 'block';
        } else {
            bulkControls.style.display = 'none';
        }
        
        // Update select all checkbox state
        if (count === 0) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = false;
        } else if (count === ticketCheckboxes.length) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = true;
        } else {
            selectAllCheckbox.indeterminate = true;
        }
    }

    // Select all functionality
    selectAllCheckbox.addEventListener('change', function() {
        ticketCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBulkControls();
    });

    // Individual checkbox change
    ticketCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkControls);
    });

    // Show/hide priority selector when changing bulk action
    bulkActionSelect.addEventListener('change', function() {
        if (this.value === 'change_priority') {
            prioritySelector.style.display = 'block';
        } else {
            prioritySelector.style.display = 'none';
        }
    });

    // Execute bulk action with confirmation
    executeBulkBtn.addEventListener('click', function() {
        const selectedTickets = document.querySelectorAll('.ticket-checkbox:checked');
        const action = bulkActionSelect.value;
        
        if (selectedTickets.length === 0) {
            alert(lang_tickets_js.alert_select_one_ticket);
            return;
        }
        
        if (!action) {
            alert(lang_tickets_js.alert_select_action);
            return;
        }

        // Set up confirmation text
        const count = selectedTickets.length;
        let confirmText = '';
        let showWarning = false;
        
        switch (action) {
            case 'delete':
                confirmText = lang_tickets_js.confirm_delete_count.replace('%d', count);
                showWarning = true;
                break;
            case 'close':
                confirmText = lang_tickets_js.confirm_close_count.replace('%d', count);
                break;
            case 'change_priority':
                const newPriorityInput = document.getElementById('new_priority');
                const newPriorityValue = newPriorityInput.options[newPriorityInput.selectedIndex].text; // Get text of selected option
                confirmText = lang_tickets_js.confirm_change_priority_count.replace('%d', count).replace('%s', newPriorityValue);
                break;
        }
        
        document.getElementById('bulkConfirmText').textContent = confirmText;
        document.getElementById('bulkWarning').style.display = showWarning ? 'block' : 'none';
        
        bulkConfirmModal.show();
    });

    // Confirm bulk action
    document.getElementById('confirmBulkAction').addEventListener('click', function() {
        // Add selected ticket IDs to form
        const selectedTickets = document.querySelectorAll('.ticket-checkbox:checked');
        
        // Remove any existing hidden inputs
        bulkForm.querySelectorAll('input[name="selected_tickets[]"]').forEach(input => input.remove());
        
        // Add selected ticket IDs as hidden inputs
        selectedTickets.forEach(checkbox => {
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'selected_tickets[]';
            hiddenInput.value = checkbox.value;
            bulkForm.appendChild(hiddenInput);
        });
        
        bulkConfirmModal.hide();
        bulkForm.submit();
    });

    // Initial update
    updateBulkControls();
});

// Delete Ticket Modal
document.addEventListener('DOMContentLoaded', function() {
    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');
            const modalTextElement = this.querySelector('#deleteTicketConfirmationText');

            // Update modal content
            if (modalTextElement) {
                 modalTextElement.innerHTML = lang_tickets_js.delete_modal_text.replace('%s', ticketId).replace('%s', `<strong>${ticketSubject}</strong>`);
            }
            this.querySelector('#deleteTicketId').value = ticketId;
        });
    }
});
</script>

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