<?php
// team_leader/team_requests.php
session_start();
require_once '../config/database.php';

// Check if CSR is logged in
if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit();
}

if (($_SESSION['csr_role'] ?? 'csr') !== 'team_leader') {
    header('Location: ../login.php');
    exit();
}

$title = 'Team Requests';
$pageHeading = 'Team Requests';
$tableHeading = 'Team Tickets';
$emptyRequestMessage = 'No team tickets found';
ob_start();
?>

<style>
:root {
    --radius: 0.625rem;
    --font-display: "Space Grotesk", system-ui, sans-serif;
    --font-sans: "Inter", system-ui, sans-serif;
    --background: oklch(0.18 0.04 260);
    --foreground: oklch(0.98 0.005 250);
    --card: oklch(0.22 0.04 260);
    --card-foreground: oklch(0.98 0.005 250);
    --popover: oklch(0.22 0.04 260);
    --popover-foreground: oklch(0.98 0.005 250);
    --primary: oklch(0.62 0.22 255);
    --primary-foreground: oklch(0.99 0 0);
    --secondary: oklch(0.28 0.04 260);
    --secondary-foreground: oklch(0.98 0.005 250);
    --muted: oklch(0.28 0.04 260);
    --muted-foreground: oklch(0.72 0.02 260);
    --accent: oklch(0.62 0.22 255);
    --accent-foreground: oklch(0.99 0 0);
    --destructive: oklch(0.62 0.24 27);
    --destructive-foreground: oklch(0.98 0 0);
    --border: oklch(0.98 0.005 250 / 0.15);
    --input: oklch(0.98 0.005 250 / 0.1);
    --ring: oklch(0.62 0.22 255);
    --panel: oklch(0.98 0.005 250 / 0.08);
    --panel-border: oklch(0.98 0.005 250 / 0.15);
    --csr-bg-1: var(--background);
    --csr-bg-2: var(--secondary);
    --csr-card-1: var(--card);
    --csr-card-2: var(--secondary);
    --csr-border: var(--border);
    --csr-border-strong: var(--panel-border);
    --csr-cyan: var(--primary);
    --csr-blue: var(--primary);
    --csr-text: var(--foreground);
    --csr-muted: var(--muted-foreground);
    --csr-soft: var(--foreground);
}

body {
    background: radial-gradient(circle at top left, oklch(0.62 0.22 255 / 0.14), transparent 34%), linear-gradient(135deg, var(--background) 0%, oklch(0.14 0.035 260) 100%) !important;
    color: var(--foreground) !important;
    font-family: var(--font-sans) !important;
}

h1, h2, h3, h4, h5, h6, .requests-page-title {
    font-family: var(--font-display) !important;
}

.container-fluid,
.main-content,
.content-wrapper {
    background: transparent !important;
}

.requests-page-title {
    color: #ffffff !important;
    font-weight: 900 !important;
    letter-spacing: 0.2px;
}

.requests-page-title i {
    color: #dff7ff !important;
}

.card {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    border: 1px solid rgba(56, 189, 248, 0.28) !important;
    border-radius: 16px !important;
    color: var(--csr-text) !important;
    box-shadow:
        0 10px 24px rgba(0, 0, 0, 0.24),
        inset 0 0 0 1px rgba(255, 255, 255, 0.025) !important;
    overflow: hidden;
}

.card:hover {
    border-color: rgba(56, 189, 248, 0.38) !important;
}

.card-header,
.card-header.bg-white {
    background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
    border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
    color: var(--csr-text) !important;
    padding: 14px 16px !important;
}

.card-header h5 {
    color: #ffffff !important;
    font-weight: 900 !important;
}

.card-body {
    color: #ffffff !important;
}

.card-footer {
    background: rgba(8, 20, 48, 0.42) !important;
    border-top: 1px solid var(--csr-border) !important;
    color: var(--csr-soft) !important;
}

.form-label {
    color: #ffffff !important;
    font-weight: 800 !important;
}

.form-control,
.form-select {
    background-color: rgba(8, 20, 48, 0.70) !important;
    border: 1px solid rgba(96, 165, 250, 0.34) !important;
    color: #ffffff !important;
    border-radius: 10px !important;
    min-height: 42px;
}

.form-control::placeholder {
    color: #aebbd4 !important;
    opacity: 1 !important;
}

.form-control:focus,
.form-select:focus {
    border-color: rgba(56, 189, 248, 0.62) !important;
    box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
}

.form-select option {
    background: #102448 !important;
    color: #ffffff !important;
}

.form-text {
    color: var(--csr-muted) !important;
}

.form-check-label {
    color: #ffffff !important;
    font-weight: 700;
}

.form-check-input {
    background-color: rgba(8, 20, 48, 0.70) !important;
    border: 1px solid rgba(96, 165, 250, 0.44) !important;
}

.form-check-input:checked {
    background-color: var(--csr-cyan) !important;
    border-color: var(--csr-cyan) !important;
}

.btn {
    border-radius: 10px !important;
    font-weight: 800 !important;
}

.btn-primary,
.btn-info {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border: none !important;
    color: #ffffff !important;
}

.btn-success {
    background: linear-gradient(135deg, #16a34a 0%, #22c55e 100%) !important;
    border: none !important;
    color: #ffffff !important;
}

.btn-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #facc15 100%) !important;
    border: none !important;
    color: #111827 !important;
}

.btn-secondary {
    background: rgba(148, 163, 184, 0.22) !important;
    border: 1px solid rgba(148, 163, 184, 0.30) !important;
    color: #ffffff !important;
}

.btn-danger {
    background: linear-gradient(135deg, #ef4444 0%, #f87171 100%) !important;
    border: none !important;
    color: #ffffff !important;
}

.btn-outline-primary,
.btn-outline-info,
.btn-outline-success,
.btn-outline-warning,
.btn-outline-secondary,
.btn-outline-dark {
    border-radius: 10px !important;
    font-weight: 800 !important;
}

.btn-outline-primary,
.btn-outline-info {
    border-color: rgba(56, 189, 248, 0.42) !important;
    color: #dff7ff !important;
    background: rgba(56, 189, 248, 0.10) !important;
}

.btn-outline-primary:hover,
.btn-outline-info:hover {
    background: rgba(56, 189, 248, 0.24) !important;
    color: #ffffff !important;
}

.btn-outline-success {
    border-color: rgba(34, 197, 94, 0.42) !important;
    color: #bbf7d0 !important;
    background: rgba(34, 197, 94, 0.10) !important;
}

.btn-outline-success:hover {
    background: rgba(34, 197, 94, 0.24) !important;
    color: #ffffff !important;
}

.btn-outline-warning {
    border-color: rgba(245, 158, 11, 0.42) !important;
    color: #fde68a !important;
    background: rgba(245, 158, 11, 0.10) !important;
}

.btn-outline-warning:hover {
    background: rgba(245, 158, 11, 0.24) !important;
    color: #ffffff !important;
}

.btn-outline-secondary,
.btn-outline-dark {
    border-color: rgba(148, 163, 184, 0.42) !important;
    color: #e2e8f0 !important;
    background: rgba(148, 163, 184, 0.10) !important;
}

.btn-outline-secondary:hover,
.btn-outline-dark:hover {
    background: rgba(148, 163, 184, 0.24) !important;
    color: #ffffff !important;
}

.table-responsive {
    background: transparent !important;
}

.table {
    color: var(--csr-text) !important;
    margin-bottom: 0 !important;
}

.table thead,
.table-light {
    background: rgba(8, 20, 48, 0.58) !important;
    color: var(--csr-text) !important;
}

.table thead th,
.table-light th {
    background: rgba(8, 20, 48, 0.58) !important;
    color: var(--csr-text) !important;
    border-color: rgba(96, 165, 250, 0.22) !important;
    border-bottom: 1px solid rgba(56, 189, 248, 0.24) !important;
    font-size: 13px;
    font-weight: 900;
    white-space: nowrap;
}

.table tbody tr {
    background: rgba(8, 20, 48, 0.22) !important;
    transition: all 0.2s ease;
}

.table tbody tr:hover {
    background: rgba(56, 189, 248, 0.10) !important;
}

.table td,
.table th {
    color: var(--csr-text) !important;
    border-color: rgba(96, 165, 250, 0.20) !important;
    vertical-align: middle;
}

.table small {
    color: var(--csr-soft) !important;
}

.table strong {
    color: #ffffff !important;
}

.badge {
    border-radius: 999px !important;
    padding: 6px 11px !important;
    font-weight: 800 !important;
    font-size: 11px !important;
}

.text-muted {
    color: var(--csr-muted) !important;
}

.text-success {
    color: #bbf7d0 !important;
}

.text-danger {
    color: #fecaca !important;
}

.text-warning {
    color: #fde68a !important;
}

.text-primary,
.text-info {
    color: #dff7ff !important;
}

.alert-info {
    background: rgba(56, 189, 248, 0.12) !important;
    border: 1px solid rgba(56, 189, 248, 0.28) !important;
    color: #dff7ff !important;
    border-radius: 12px !important;
}

.alert-warning {
    background: rgba(245, 158, 11, 0.14) !important;
    border: 1px solid rgba(245, 158, 11, 0.32) !important;
    color: #fde68a !important;
    border-radius: 12px !important;
}

.loader {
    border: 3px solid rgba(255,255,255,0.12);
    border-radius: 50%;
    border-top: 3px solid var(--csr-cyan);
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.urgency-pulse {
    animation: urgencyPulse 1.4s infinite;
}

@keyframes urgencyPulse {
    0% { box-shadow: 0 0 0 0 rgba(248, 113, 113, .55); }
    70% { box-shadow: 0 0 0 8px rgba(248, 113, 113, 0); }
    100% { box-shadow: 0 0 0 0 rgba(248, 113, 113, 0); }
}

.request-checkbox {
    cursor: pointer;
}

#bulkAssignBtn {
    transition: all 0.3s ease;
}

/* Fixed aligned action buttons */
.request-actions {
    display: grid;
    grid-template-columns: 38px 108px 38px 38px;
    gap: 8px;
    align-items: center;
    justify-content: start;
    min-width: 215px;
}

.request-actions .action-slot {
    display: flex;
    align-items: center;
    justify-content: center;
}

.request-actions .action-placeholder {
    width: 100%;
    height: 34px;
    visibility: hidden;
    pointer-events: none;
}

.action-square {
    width: 38px !important;
    height: 34px !important;
    padding: 0 !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    border-radius: 10px !important;
}

.action-pill {
    width: 108px !important;
    height: 34px !important;
    padding: 0 10px !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    border-radius: 10px !important;
    white-space: nowrap !important;
    font-size: 12px !important;
}

.action-locked {
    width: 108px !important;
    height: 34px !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    border-radius: 10px !important;
    background: linear-gradient(135deg, #dc2626 0%, #f43f5e 100%) !important;
    color: #ffffff !important;
    font-size: 12px !important;
    font-weight: 900 !important;
}

.request-actions i {
    line-height: 1 !important;
}

.table th:last-child,
.table td:last-child {
    min-width: 230px;
    white-space: nowrap;
}

.pagination .page-link {
    background: rgba(8, 20, 48, 0.54) !important;
    border-color: rgba(96, 165, 250, 0.24) !important;
    color: #dff7ff !important;
    font-weight: 800;
}

.pagination .page-item.active .page-link {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border-color: transparent !important;
    color: #ffffff !important;
}

.pagination .page-item.disabled .page-link {
    background: rgba(8, 20, 48, 0.25) !important;
    color: #64748b !important;
}

.modal-content {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    border: 1px solid rgba(96, 165, 250, 0.30) !important;
    color: #ffffff !important;
    border-radius: 16px !important;
    overflow: hidden;
    box-shadow: 0 25px 70px rgba(0,0,0,0.45) !important;
}

.modal-header {
    background: rgba(56, 189, 248, 0.10) !important;
    border-bottom: 1px solid var(--csr-border) !important;
}

.modal-title {
    color: #ffffff !important;
    font-weight: 900 !important;
}

.modal-body {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    color: #ffffff !important;
}

.modal-footer {
    background: rgba(8, 20, 48, 0.52) !important;
    border-top: 1px solid var(--csr-border) !important;
}

.btn-close {
    filter: brightness(0) invert(1) !important;
    opacity: 1 !important;
}

#requestDetailsBody h6,
#requestDetailsBody h4,
#requestDetailsBody th,
#requestDetailsBody td,
#requestDetailsBody p,
#requestDetailsBody strong,
#requestDetailsBody small,
#requestDetailsBody div {
    color: #ffffff;
}

#requestDetailsBody h6 {
    color: #ffffff !important;
    font-weight: 900;
    border-bottom-color: rgba(96, 165, 250, 0.24) !important;
}

#requestDetailsBody .table th,
#requestDetailsBody .table td {
    color: var(--csr-text) !important;
    background: rgba(8, 20, 48, 0.20) !important;
    border-color: rgba(96, 165, 250, 0.22) !important;
}

#requestDetailsBody .bg-light,
#requestDetailsBody .card.bg-light,
#requestDetailsBody div.bg-light {
    background: rgba(8, 20, 48, 0.45) !important;
    color: #ffffff !important;
    border: 1px solid rgba(96, 165, 250, 0.24) !important;
}

#requestDetailsBody .card {
    background: rgba(8, 20, 48, 0.38) !important;
    border: 1px solid rgba(96, 165, 250, 0.22) !important;
}

#requestDetailsBody .card-body {
    background: transparent !important;
}

.timeline {
    max-height: 400px;
    overflow-y: auto;
    padding-right: 4px;
}

.timeline::-webkit-scrollbar {
    width: 6px;
}

.timeline::-webkit-scrollbar-thumb {
    background: rgba(96, 165, 250, 0.40);
    border-radius: 999px;
}

#zoomedImage {
    border-radius: 12px;
}


/* Strict requested OKLCH navy theme overrides */
.card,
.modal-content {
    background: var(--card) !important;
    border: 1px solid var(--panel-border) !important;
    border-radius: var(--radius) !important;
    color: var(--card-foreground) !important;
    box-shadow: 0 18px 48px oklch(0 0 0 / 0.30) !important;
}
.card-header,
.card-header.bg-white,
.modal-header {
    background: var(--panel) !important;
    border-bottom: 1px solid var(--panel-border) !important;
    color: var(--foreground) !important;
}
.modal-body {
    background: var(--card) !important;
}
.modal-footer,
.card-footer {
    background: var(--panel) !important;
    border-top: 1px solid var(--panel-border) !important;
}
.form-control,
.form-select {
    background: var(--input) !important;
    border: 1px solid var(--border) !important;
    color: var(--foreground) !important;
    border-radius: var(--radius) !important;
}
.form-control:focus,
.form-select:focus {
    border-color: var(--ring) !important;
    box-shadow: 0 0 0 0.18rem oklch(0.62 0.22 255 / 0.20) !important;
}
.table thead,
.table-light,
.table thead th,
.table-light th {
    background: var(--secondary) !important;
    color: var(--foreground) !important;
    border-color: var(--border) !important;
}
.table tbody tr,
#requestDetailsBody .table th,
#requestDetailsBody .table td {
    background: var(--panel) !important;
    border-color: var(--border) !important;
}
.table tbody tr:hover {
    background: oklch(0.62 0.22 255 / 0.13) !important;
}
.btn-primary,
.btn-info,
.btn-success {
    background: var(--primary) !important;
    border-color: var(--primary) !important;
    color: var(--primary-foreground) !important;
}
.btn-warning {
    background: oklch(0.82 0.17 85) !important;
    color: oklch(0.18 0.04 260) !important;
}
.btn-danger {
    background: var(--destructive) !important;
    color: var(--destructive-foreground) !important;
}
.btn-secondary {
    background: var(--secondary) !important;
    border-color: var(--border) !important;
    color: var(--secondary-foreground) !important;
}
.request-number-link {
    color: var(--foreground) !important;
    text-decoration: none !important;
    font-weight: 900 !important;
    cursor: pointer !important;
    border-bottom: 1px dashed transparent;
    background: transparent !important;
    border-radius: 0 !important;
}
.request-number-link:hover,
.request-number-link:focus {
    color: var(--primary) !important;
    text-decoration: underline !important;
    text-underline-offset: 3px;
    border-bottom-color: var(--primary);
    background: transparent !important;
}
.cx-complete-field label::after {
    content: " CSR can complete";
    color: var(--muted-foreground);
    font-size: 11px;
    font-weight: 500;
    margin-left: 6px;
}

@media (max-width: 768px) {
    .requests-page-title {
        font-size: 22px;
    }

    .card-header {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 10px;
    }

    .card-footer .d-flex {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start !important;
    }

    .table {
        font-size: 13px;
    }

    .request-actions {
        grid-template-columns: 34px 96px 34px 34px;
        gap: 6px;
        min-width: 198px;
    }

    .action-square {
        width: 34px !important;
        height: 32px !important;
    }

    .action-pill,
    .action-locked {
        width: 96px !important;
        height: 32px !important;
        font-size: 11px !important;
    }

    .table th:last-child,
    .table td:last-child {
        min-width: 205px;
    }
}
</style>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <h2 class="requests-page-title mb-0">
                    <i class="fas fa-clipboard-list me-2"></i><?php echo $pageHeading; ?>
                </h2>

                <div>
                    <button class="btn btn-success me-2" onclick="openBulkAssignModal()" id="bulkAssignBtn" style="display: none;">
                        <i class="fas fa-users me-2"></i>Bulk Assign
                    </button>

                    <a class="btn btn-success me-2" href="manual_ticket.php">
                        <i class="fas fa-plus me-2"></i>Create Manual Ticket
                    </a>

                    <button class="btn btn-primary" onclick="window.location.reload()">
                        <i class="fas fa-sync-alt me-2"></i>Refresh
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-header bg-white">
            <h5 class="mb-0">
                <i class="fas fa-filter me-2"></i>Filter Requests
            </h5>
        </div>

        <div class="card-body">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="form-label">Ticket Source</label>
                    <select class="form-select" id="filterSource">
                        <option value="all">All Tickets</option>
                        <option value="cx_online">Customer Online Request</option>
                        <option value="csr_manual">Manual Ticket</option>
                        <option value="chat_followup">Chat Follow-Up Request</option>
                        <option value="assigned_me">Assigned to Me</option>
                        <option value="unclaimed">Unclaimed / Queue</option>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="form-label">Queue View</label>
                    <select class="form-select" id="filterTicketView">
                        <option value="active" selected>Active Tickets</option>
                        <option value="all">All Tickets</option>
                        <option value="new">New Request</option>
                        <option value="assigned">Assigned</option>
                        <option value="in_progress">In Progress</option>
                        <option value="completed">Completed</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                    <small class="form-text">Default keeps completed/cancelled tickets lower and out of the working queue.</small>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="form-label">Status</label>
                    <select class="form-select" id="filterStatus">
                        <option value="">All Statuses</option>
                        <option value="1">New Request</option>
                        <option value="2">Assigned</option>
                        <option value="3">In Progress</option>
                        <option value="4">Repair Completed</option>
                        <option value="5">Cancelled</option>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="form-label">Urgency Level</label>
                    <select class="form-select" id="filterUrgency">
                        <option value="">All</option>
                        <option value="1">Normal</option>
                        <option value="2">Urgent</option>
                        <option value="3">Emergency</option>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="form-label">Date Range</label>
                    <select class="form-select" id="filterDate">
                        <option value="">All Time</option>
                        <option value="today">Today</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="form-label">Search</label>
                    <input type="text" class="form-control" id="searchInput" placeholder="Request #, Name, Phone...">
                </div>
            </div>

            <div class="row">
                <div class="col-12 d-flex gap-2 flex-wrap">
                    <button class="btn btn-primary" onclick="loadRequests()">
                        <i class="fas fa-search me-2"></i>Apply Filters
                    </button>

                    <button class="btn btn-secondary" onclick="resetFilters()">
                        <i class="fas fa-undo me-2"></i>Reset
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Requests Table -->
    <div class="card">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <div>
                <h5 class="mb-0">
                    <i class="fas fa-tasks me-2"></i><?php echo $tableHeading; ?>
                </h5>
            </div>

            <div class="d-flex align-items-center flex-wrap gap-2">
                <span id="requestCount" class="badge bg-secondary">0 requests</span>

                <div class="form-check form-check-inline ms-2">
                    <input class="form-check-input" type="checkbox" id="selectAllCheckbox" onclick="toggleSelectAll()">
                    <label class="form-check-label" for="selectAllCheckbox">
                        Select All
                    </label>
                </div>
            </div>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="40px"><input type="checkbox" id="selectAllHeader" onclick="toggleSelectAll()"></th>
                            <th>ID</th>
                            <th>Request #</th>
                            <th>Source</th>
                            <th>Customer</th>
                            <th>Phone</th>
                            <th>Appliance</th>
                            <th>Urgency</th>
                            <th>Status</th>
                            <th>Ticket Age</th>
                            <th>Last Updated (CST)</th>
                            <th>Actions</th>
                        </tr>
                    </thead>

                    <tbody id="requestsTableBody">
                        <tr>
                            <td colspan="12" class="text-center py-5">
                                <div class="loader mx-auto"></div>
                                <p class="text-muted mt-3">Loading requests...</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    Showing <span id="showingStart">0</span> - <span id="showingEnd">0</span> of <span id="totalRecords">0</span>
                </div>

                <nav>
                    <ul class="pagination mb-0" id="pagination"></ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<!-- Request Details Modal with Notes -->
<div class="modal fade" id="requestDetailsModal" tabindex="-1" aria-labelledby="requestDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="requestDetailsModalLabel">
                    <i class="fas fa-clipboard-list me-2"></i>Request Details
                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body" id="requestDetailsBody">
                <div class="text-center py-5">
                    <div class="loader mx-auto"></div>
                    <p class="text-muted mt-3">Loading details...</p>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

                <button type="button" class="btn btn-info" id="editDetailsBtn" onclick="openEditDetailsModal()">
                    <i class="fas fa-edit me-2"></i>Edit Details
                </button>

                <button type="button" class="btn btn-primary" id="addNoteBtn" onclick="openAddNoteModal()">
                    <i class="fas fa-plus me-2"></i>Add Note
                </button>

                <button type="button" class="btn btn-warning" id="updateStatusBtn" style="display: none;" onclick="openUpdateStatusModal()">
                    <i class="fas fa-edit me-2"></i>Update Status
                </button>

                <button type="button" class="btn btn-success" id="assignTechBtn" style="display: none;" onclick="openAssignTechnicianModal()">
                    <i class="fas fa-user-plus me-2"></i>Assign Technician
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Details Modal -->
<div class="modal fade" id="editDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Request Details</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="editDetailsForm">
                <div class="modal-body">
                    <input type="hidden" name="request_id" id="editRequestId">
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">Customer Name</label><input class="form-control" name="full_name" id="editFullName" required></div>
                        <div class="col-md-4"><label class="form-label">Primary Phone</label><input class="form-control" name="phone_number" id="editPhone" required></div>
                        <div class="col-md-4 cx-complete-field"><label class="form-label">Secondary Phone</label><input class="form-control" name="secondary_phone" id="editSecondaryPhone" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-4"><label class="form-label">Email</label><input class="form-control" name="customer_email" id="editEmail"></div>
                        <div class="col-md-8"><label class="form-label">Address</label><input class="form-control" name="service_address" id="editAddress" required></div>
                        <div class="col-md-4 cx-complete-field"><label class="form-label">Address Note</label><input class="form-control" name="service_address_2" id="editAddress2" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-2"><label class="form-label">ZIP</label><input class="form-control" name="zip_code" id="editZip" maxlength="5" required></div>
                        <div class="col-md-3"><label class="form-label">Region</label><input class="form-control" name="region" id="editRegion"></div>
                        <div class="col-md-3"><label class="form-label">City</label><input class="form-control" name="city" id="editCity"></div>
                        <div class="col-md-2"><label class="form-label">State</label><input class="form-control" name="state" id="editState"></div>
                        <div class="col-md-2"><label class="form-label">Landmark</label><input class="form-control" name="landmark" id="editLandmark"></div>
                        <div class="col-md-3"><label class="form-label">Brand</label><input class="form-control" name="brand" id="editBrand"></div>
                        <div class="col-md-3"><label class="form-label">Appliance</label><input class="form-control" name="appliance_type" id="editAppliance"></div>
                        <div class="col-md-3 cx-complete-field"><label class="form-label">Model</label><input class="form-control" name="model_number" id="editModel" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-3 cx-complete-field"><label class="form-label">Serial</label><input class="form-control" name="serial_number" id="editSerial" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-3 cx-complete-field"><label class="form-label">Model Version</label><input class="form-control" name="product_model_version" id="editModelVersion" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-3 cx-complete-field"><label class="form-label">Purchase Date</label><input type="date" class="form-control" name="purchase_date" id="editPurchaseDate"></div>
                        <div class="col-md-3 cx-complete-field"><label class="form-label">Warranty Type</label><input class="form-control" name="warranty_type" id="editWarrantyType" placeholder="Please complete this field if needed"></div>
                        <div class="col-md-3"><label class="form-label">Preferred Date</label><input type="date" class="form-control" name="preferred_date" id="editPreferredDate"></div>
                        <div class="col-12"><label class="form-label">Issue Description</label><textarea class="form-control" name="issue_description" id="editIssue" rows="4"></textarea></div>
                        <div class="col-12"><label class="form-label">Special Request</label><textarea class="form-control" name="special_request" id="editSpecial" rows="3"></textarea></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"><i class="fas fa-save me-1"></i>Save Details</button></div>
            </form>
        </div>
    </div>
</div>

<!-- Add Note Modal -->
<div class="modal fade" id="addNoteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-sticky-note me-2"></i>Add Note to Request
                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <form id="addNoteForm">
                <div class="modal-body">
                    <input type="hidden" id="noteRequestId" name="request_id">

                    <div class="mb-3">
                        <label class="form-label">Note Type</label>

                        <select class="form-select" name="note_type" id="noteType" required>
                            <option value="internal">Internal Notes</option>
                            <option value="customer">Customer Updates</option>
                        </select>

                        <div class="form-text">
                            <i class="fas fa-info-circle"></i>
                            Internal Notes: visible only to CSR/Admin for private tracking<br>
                            Customer Updates: visible to the customer through My Requests / chat
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Follow-Up Reminder (Optional)</label>
                        <select class="form-select mb-2" name="follow_up_reminder" id="followUpReminder">
                            <option value="">No reminder</option>
                            <option value="Call customer tomorrow">Call customer tomorrow</option>
                            <option value="Follow up technician">Follow up technician</option>
                            <option value="Waiting for parts">Waiting for parts</option>
                            <option value="Waiting for customer response">Waiting for customer response</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Note Content</label>
                        <textarea class="form-control" name="note_content" id="noteContent" rows="5" required placeholder="Enter your notes here..."></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Notify Customer (for Customer Updates only)</label>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="notifyCustomer" name="notify_customer" value="1">

                            <label class="form-check-label" for="notifyCustomer">
                                Send notification to Customer
                            </label>
                        </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">
                        <i class="fas fa-save me-2"></i>Save Note
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="updateStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit me-2"></i>Update Request Status
                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <form id="updateStatusForm">
                <div class="modal-body">
                    <input type="hidden" id="statusRequestId" name="request_id">

                    <div class="mb-3">
                        <label class="form-label">New Status</label>

                        <select class="form-select" name="job_status_id" id="newStatus" required>
                            <option value="1">New Request</option>
                            <option value="2">Assigned</option>
                            <option value="3">In Progress</option>
                            <option value="4">Repair Completed</option>
                            <option value="5">Cancelled</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Status Notes (Optional)</label>
                        <textarea class="form-control" name="status_notes" id="statusNotes" rows="3" placeholder="Add any notes about this status change..."></textarea>
                    </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-warning">
                        <i class="fas fa-save me-2"></i>Update Status
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Assign Technician Modal -->
<div class="modal fade" id="assignTechnicianModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus me-2"></i>Assign Technician
                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <form id="assignTechnicianForm">
                <div class="modal-body">
                    <input type="hidden" id="assignRequestId" name="request_id">
                    <input type="hidden" id="isBulkAssign" name="is_bulk_assign" value="0">
                    
                    <div id="existingAssignmentsInfo" style="display: none;" class="mb-3">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <span id="existingAssignmentsText"></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Select Technician <span class="text-danger">*</span></label>

                        <select class="form-select" name="technician_id" id="technicianSelect" required>
                            <option value="">Loading technicians...</option>
                        </select>

                        <div class="form-text">
                            <i class="fas fa-info-circle"></i> Only available technicians are shown
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Estimated Arrival Time</label>
                        <input type="date" name="estimated_arrival_date" id="estimatedArrivalDate" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Estimated Arrival Period</label>

                        <select name="estimated_arrival_period" id="estimatedArrivalPeriod" class="form-select" required>
                            <option value="">Select</option>
                            <option value="AM">Morning (AM)</option>
                            <option value="PM">Afternoon (PM)</option>
                        </select>
                    </div>                 
                    
                    <div class="mb-3">
                        <label class="form-label">Assignment Notes</label>
                        <textarea class="form-control" name="assignment_notes" id="assignmentNotes" rows="3" placeholder="Add instructions for the technician..."></textarea>
                    </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-success" id="assignSubmitBtn">
                        <i class="fas fa-check me-2"></i>Assign Technician
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Assign Modal -->
<div class="modal fade" id="bulkAssignModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-users me-2"></i>Bulk Assign Technicians
                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    Select requests and assign technicians in bulk.
                </div>

                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Request #</th>
                                <th>Customer</th>
                                <th>Appliance</th>
                                <th>Current Status</th>
                            </tr>
                        </thead>

                        <tbody id="bulkSelectRequestsBody"></tbody>
                    </table>
                </div>

                <div class="mt-3">
                    <label class="form-label">Assign to all selected:</label>

                    <select class="form-select" id="bulkTechnicianSelect">
                        <option value="">Select Technician</option>
                    </select>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                <button type="button" class="btn btn-success" onclick="confirmBulkAssign()">
                    <i class="fas fa-check me-2"></i>Assign to Selected
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Image Zoom Modal -->
<div class="modal fade" id="imageZoomModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Image Preview</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body text-center">
                <img src="" id="zoomedImage" class="img-fluid" style="max-height: 70vh;">
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
let currentPage = 1;
let currentRequestId = null;
let selectedRequests = [];
let currentRequestData = null;

$(document).ready(function() {
    const urlSource = new URLSearchParams(window.location.search).get('source');
    if(urlSource) $('#filterSource').val(urlSource);
    loadRequests();
    
    $('#filterSource, #filterTicketView, #filterStatus, #filterUrgency, #filterDate, #searchInput').on('change keyup', function() {
        currentPage = 1;
        loadRequests();
    });
    
    $('#addNoteForm').on('submit', function(e) {
        e.preventDefault();
        saveNote();
    });
    
    $('#updateStatusForm').on('submit', function(e) {
        e.preventDefault();
        updateRequestStatus();
    });
    
    $('#assignTechnicianForm').on('submit', function(e) {
        e.preventDefault();
        if($('#isBulkAssign').val() == '1') {
            confirmBulkAssign();
        } else {
            assignTechnician();
        }
    });

    $('#editDetailsForm').on('submit', function(e) {
        e.preventDefault();
        saveRequestDetails();
    });

    $('#editZip').on('input', function(){
        const zip = $(this).val().trim();
        if(zip.length === 5) {
            $.post('../customer/check_zip.php', {zip_code: zip}, function(r){
                if(r && r.serviceable) {
                    if(r.region) $('#editRegion').val(r.region);
                    if(r.city_name) $('#editCity').val(r.city_name);
                    if(r.state) $('#editState').val(r.state);
                }
            }, 'json');
        }
    });
});

const emptyRequestMessage = '<?php echo addslashes($emptyRequestMessage); ?>';

function loadRequests() {
    const filters = {
        page: currentPage,
        status: $('#filterStatus').val(),
        urgency: $('#filterUrgency').val(),
        date_range: $('#filterDate').val(),
        search: $('#searchInput').val(),
        source_filter: $('#filterSource').val(),
        ticket_view: $('#filterTicketView').val(),
        portal_scope: 'team_leader_main_tickets'
    };
    
    $('#requestsTableBody').html(`
        <tr>
            <td colspan="12" class="text-center py-5">
                <div class="loader mx-auto"></div>
                <p class="text-muted mt-3">Loading requests...</p>
            </td>
        </tr>
    `);
    
    $.ajax({
        url: '../csr/ajax/get_requests_list.php',
        method: 'POST',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                displayRequests(response.requests);
                updatePagination(response.pagination);
                $('#requestCount').text(response.total + ' requests');
            } else {
                showError(response.message);
            }
        },
        error: function() {
            showError('Error loading requests. Please try again.');
        }
    });
}

function displayRequests(requests) {
    if(!requests || requests.length === 0) {
        $('#requestsTableBody').html(`
            <tr>
                <td colspan="12" class="text-center py-5">
                    <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                    <p class="text-muted">${emptyRequestMessage}</p>
                </td>
            </tr>
        `);
        return;
    }
    
    let html = '';

    requests.forEach(function(request) {
        const urgencyId = parseInt(request.urgency_id || request.urgency_level_id || 1, 10);
        const urgencyName = request.urgency_name || (urgencyId === 3 ? 'Emergency' : (urgencyId === 2 ? 'Urgent' : 'Normal'));

        let urgencyBadge = '';

        if(urgencyId === 3) {
            urgencyBadge = `<span class="badge bg-danger urgency-pulse"><i class="fas fa-exclamation-triangle me-1"></i>${escapeHtml(urgencyName)}</span>`;
        } else if(urgencyId === 2) {
            urgencyBadge = `<span class="badge bg-warning text-dark"><i class="fas fa-clock me-1"></i>${escapeHtml(urgencyName)}</span>`;
        } else {
            urgencyBadge = `<span class="badge bg-info">${escapeHtml(urgencyName)}</span>`;
        }
        
        let isLockedByOtherCSR = request.managing_csr_id && request.managing_csr_id != <?= $_SESSION['csr_id'] ?>;
        let isManagedByMe = request.managing_csr_id && request.managing_csr_id == <?= $_SESSION['csr_id'] ?>;

        let viewButton = `
            <button class="btn btn-sm btn-outline-primary action-square" onclick="viewRequestDetails(${request.id})" title="View Details">
                <i class="fas fa-eye"></i>
            </button>
        `;

        let manageSlot = '';

        if(!request.managing_csr_id) {
            manageSlot = `
                <button class="btn btn-sm btn-outline-info action-pill" onclick="manageRequest(${request.id})" title="Manage This Ticket">
                    <i class="fas fa-hand-paper me-1"></i>Manage
                </button>
            `;
        } else if(isLockedByOtherCSR) {
            manageSlot = `
                <span class="action-locked">
                    <i class="fas fa-lock me-1"></i>Locked
                </span>
            `;
        } else {
            manageSlot = `<span class="action-placeholder"></span>`;
        }

        let canAssign = (request.job_status_id == 1 && !isLockedByOtherCSR);

        let assignSlot = '';

        if(canAssign) {
            assignSlot = `
                <button class="btn btn-sm btn-success action-square" onclick="openAssignTechnicianModalForRequest(${request.id})" title="Assign Technician">
                    <i class="fas fa-user-plus"></i>
                </button>
            `;
        } else if((request.job_status_id == 2 || request.job_status_id == 3) && !isLockedByOtherCSR) {
            assignSlot = `
                <button class="btn btn-sm btn-info action-square" onclick="openAssignTechnicianModalForRequest(${request.id})" title="Add Another Technician">
                    <i class="fas fa-user-friends"></i>
                </button>
            `;
        } else {
            assignSlot = `<span class="action-placeholder"></span>`;
        }

        let noteSlot = '';

        if(!isLockedByOtherCSR) {
            noteSlot = `
                <button class="btn btn-sm btn-outline-success action-square" onclick="quickAddNote(${request.id})" title="Add Note">
                    <i class="fas fa-sticky-note"></i>
                </button>
            `;
        } else {
            noteSlot = `<span class="action-placeholder"></span>`;
        }
        
        let statusDisplay = `
            <span class="badge" style="background-color: ${request.status_color}; color: white;">
                ${escapeHtml(request.status_name)}
            </span>
        `;
        
        if(request.managing_csr) {
            if(isManagedByMe) {
                statusDisplay += `<div class="small text-success mt-1"><i class="fas fa-user-check"></i> Managed by: ${escapeHtml(request.managing_csr)} (You)</div>`;
            } else {
                statusDisplay += `<div class="small text-danger mt-1"><i class="fas fa-lock"></i> Managed by: ${escapeHtml(request.managing_csr)}</div>`;
            }
        }

        if(request.technician_count >= 2) {
            statusDisplay += ` 
                <span class="badge bg-warning text-dark mt-1" title="${request.technician_count} technicians assigned">
                    <i class="fas fa-users"></i> Double Job (${request.technician_count})
                </span>
            `;
        } else if(request.technician_count == 1 && (request.job_status_id == 2 || request.job_status_id == 3)) {
            statusDisplay += ` 
                <span class="badge bg-info mt-1" title="1 technician assigned">
                    <i class="fas fa-user"></i> ${request.technician_count}
                </span>
            `;
        }
        
        html += `
            <tr>
                <td>
                    <input type="checkbox" class="request-checkbox" value="${request.id}" data-status="${request.job_status_id}" onchange="updateSelectedRequests()">
                </td>

                <td>${request.id}</td>

                <td>
                    <a href="team_requests.php?view=${request.id}" class="request-number-link" onclick="event.preventDefault(); viewRequestDetails(${request.id}, true);" title="View record only">
                        ${escapeHtml(request.request_number)}
                    </a>
                </td>

                <td>${sourceBadge(request.ticket_source_label || request.ticket_source)}</td>
                <td>${escapeHtml(request.full_name)}</td>
                <td>${escapeHtml(request.phone_number)}</td>
                <td>${escapeHtml(request.appliance_type || 'N/A')}</td>
                <td>${urgencyBadge}</td>
                <td>${statusDisplay}</td>

                <td><small>${formatDuration(request.ticket_age_minutes)}</small></td>
                <td><small>${formatDate(request.last_updated_at || request.requested_at)}</small></td>

                <td>
                    <div class="request-actions">
                        <div class="action-slot">${viewButton}</div>
                        <div class="action-slot">${manageSlot}</div>
                        <div class="action-slot">${assignSlot}</div>
                        <div class="action-slot">${noteSlot}</div>
                    </div>
                </td>
            </tr>
        `;
    });
    
    $('#requestsTableBody').html(html);
}

function manageRequest(requestId) {
    if(!confirm('Manage this ticket? Other CSRs will still be able to view it, but only you can update it.')) {
        return;
    }

    $.ajax({
        url: '../csr/ajax/manage_request.php',
        method: 'POST',
        data: { request_id: requestId },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                showSuccess(response.message || 'Ticket claimed.');
                loadRequests();
                if(currentRequestId == requestId) {
                    viewRequestDetails(requestId);
                }
            } else {
                showError(response.message || 'Unable to manage this ticket.');
            }
        },
        error: function() {
            showError('Error claiming ticket. Please try again.');
        }
    });
}

function updateSelectedRequests() {
    selectedRequests = [];

    $('.request-checkbox:checked').each(function() {
        let requestId = $(this).val();
        let status = $(this).data('status');

        if(status == 1) {
            selectedRequests.push(requestId);
        }
    });
    
    if(selectedRequests.length > 0) {
        $('#bulkAssignBtn').show();
    } else {
        $('#bulkAssignBtn').hide();
    }
}

function toggleSelectAll() {
    let isChecked = $('#selectAllHeader').is(':checked');

    $('.request-checkbox').each(function() {
        let status = $(this).data('status');

        if(status == 1) {
            $(this).prop('checked', isChecked);
        }
    });

    $('#selectAllCheckbox').prop('checked', isChecked);
    updateSelectedRequests();
}

function openBulkAssignModal() {
    if(selectedRequests.length === 0) {
        alert('Please select at least one request to assign.');
        return;
    }
    
    loadTechniciansForBulk();
    
    let html = '';

    selectedRequests.forEach(function(requestId) {
        let row = $(`.request-checkbox[value="${requestId}"]`).closest('tr');
        let requestNumber = row.find('td:eq(2)').text();
        let customerName = row.find('td:eq(4)').text();
        let appliance = row.find('td:eq(6)').text();
        
        html += `
            <tr>
                <td>${escapeHtml(requestNumber)}</td>
                <td>${escapeHtml(customerName)}</td>
                <td>${escapeHtml(appliance)}</td>
                <td><span class="badge bg-info">New Request</span></td>
            </tr>
        `;
    });
    
    $('#bulkSelectRequestsBody').html(html);
    $('#bulkAssignModal').modal('show');
}

function loadTechniciansForBulk() {
    $.ajax({
        url: '../csr/ajax/get_available_technicians.php',
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if(response.success && response.technicians) {
                let options = '<option value="">Select Technician</option>';

                response.technicians.forEach(function(tech) {
                    options += `<option value="${tech.id}">${escapeHtml(tech.full_name)} - ${escapeHtml(tech.specialization || 'General')}</option>`;
                });

                $('#bulkTechnicianSelect').html(options);
            } else {
                $('#bulkTechnicianSelect').html('<option value="">No technicians available</option>');
            }
        },
        error: function() {
            $('#bulkTechnicianSelect').html('<option value="">Error loading technicians</option>');
        }
    });
}

function confirmBulkAssign() {
    let technicianId = $('#bulkTechnicianSelect').val();
    let assignmentNotes = $('#assignmentNotes').val();
    
    if(!technicianId) {
        alert('Please select a technician to assign.');
        return;
    }
    
    if(selectedRequests.length === 0) {
        alert('No requests selected for assignment.');
        return;
    }
    
    if(confirm(`Are you sure you want to assign ${selectedRequests.length} request(s) to this technician?`)) {
        $.ajax({
            url: '../csr/ajax/bulk_assign_technician.php',
            method: 'POST',
            data: {
                request_ids: selectedRequests,
                technician_id: technicianId,
                assignment_notes: assignmentNotes
            },
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    alert(`Successfully assigned ${response.assigned_count} request(s)!`);
                    $('#bulkAssignModal').modal('hide');
                    loadRequests();
                    selectedRequests = [];
                    $('#bulkAssignBtn').hide();
                    $('#selectAllHeader').prop('checked', false);
                    $('#selectAllCheckbox').prop('checked', false);
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function() {
                alert('Error assigning requests. Please try again.');
            }
        });
    }
}

function openAssignTechnicianModalForRequest(requestId) {
    currentRequestId = requestId;
    $('#assignRequestId').val(requestId);
    $('#isBulkAssign').val('0');
    $('#singleAssignSection').show();
    $('#bulkAssignSection').hide();
    
    $.ajax({
        url: '../csr/ajax/get_request_details.php',
        method: 'GET',
        data: { request_id: requestId },
        dataType: 'json',
        success: function(response) {
            if(response.success && response.request.current_assignments) {
                let count = response.request.current_assignments.length;

                if(count > 0) {
                    let techNames = response.request.current_assignments.map(a => a.technician_name).join(', ');
                    let message = `This request already has ${count} technician(s) assigned: ${escapeHtml(techNames)}`;

                    if(count >= 2) {
                        message += ` <strong class="text-warning">(Double Job)</strong>`;
                    }

                    message += `<br>Adding another technician will make it a team job.`;

                    $('#existingAssignmentsText').html(message);
                    $('#existingAssignmentsInfo').show();
                } else {
                    $('#existingAssignmentsInfo').hide();
                }
            } else {
                $('#existingAssignmentsInfo').hide();
            }
        }
    });
    
    loadTechnicians();
    $('#assignTechnicianModal').modal('show');
}

function openAssignTechnicianModal() {
    if(currentRequestId) {
        openAssignTechnicianModalForRequest(currentRequestId);
    }
}

function updatePagination(pagination) {
    if(!pagination) return;
    
    $('#showingStart').text(pagination.start);
    $('#showingEnd').text(pagination.end);
    $('#totalRecords').text(pagination.total);
    
    let paginationHtml = '';
    
    if(pagination.current_page > 1) {
        paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${pagination.current_page - 1})">Previous</a></li>`;
    }
    
    for(let i = pagination.start_page; i <= pagination.end_page; i++) {
        paginationHtml += `
            <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>
        `;
    }
    
    if(pagination.current_page < pagination.total_pages) {
        paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${pagination.current_page + 1})">Next</a></li>`;
    }
    
    $('#pagination').html(paginationHtml);
}

function changePage(page) {
    currentPage = page;
    loadRequests();
}

function resetFilters() {
    $('#filterSource').val('all');
    $('#filterTicketView').val('active');
    $('#filterStatus').val('');
    $('#filterUrgency').val('');
    $('#filterDate').val('');
    $('#searchInput').val('');
    currentPage = 1;
    loadRequests();
}

function viewRequestDetails(requestId, readOnlyView = false) {
    currentRequestId = requestId;

    $('#requestDetailsModal').modal('show');

    $('#requestDetailsBody').html(`
        <div class="text-center py-5">
            <div class="loader mx-auto"></div>
            <p class="text-muted mt-3">Loading details...</p>
        </div>
    `);
    
    $('#addNoteBtn, #updateStatusBtn, #assignTechBtn, #editDetailsBtn').hide();
    
    $.ajax({
        url: '../csr/ajax/get_request_details.php',
        method: 'GET',
        data: { request_id: requestId },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                currentRequestData = response.request;
                displayRequestDetails(response.request);

                if(readOnlyView || response.request.is_locked_by_other_csr == 1) {
                    $('#addNoteBtn, #updateStatusBtn, #assignTechBtn, #editDetailsBtn').hide();
                } else {
                    if(response.request.job_status_id == 1) {
                        $('#assignTechBtn').show();
                        $('#updateStatusBtn').show();
                    } else if(response.request.job_status_id == 2 || response.request.job_status_id == 3) {
                        $('#updateStatusBtn').show();
                    }

                    $('#addNoteBtn, #editDetailsBtn').show();
                }
            } else {
                showErrorInModal(response.message);
            }
        },
        error: function() {
            showErrorInModal('Error loading request details');
        }
    });
}

function displayRequestDetails(request) {
    let statusBadge = `
        <span class="badge" style="background-color: ${request.status_color}; color: white; padding: 5px 10px;">
            ${escapeHtml(request.status_name)}
        </span>
    `;

    if(request.managing_csr) {
        if(request.managing_csr_id == <?= $_SESSION['csr_id'] ?>) {
            statusBadge += `<div class="small text-success mt-1"><i class="fas fa-user-check"></i> Managed by: ${escapeHtml(request.managing_csr)} (You)</div>`;
        } else {
            statusBadge += `<div class="small text-danger mt-1"><i class="fas fa-lock"></i> Managed by: ${escapeHtml(request.managing_csr)}</div>`;
        }
    }
    
    const urgencyId = parseInt(request.urgency_id || request.urgency_level_id || 1, 10);
    const urgencyName = request.urgency_name || (urgencyId === 3 ? 'Emergency' : (urgencyId === 2 ? 'Urgent' : 'Normal'));

    let urgencyBadge = '';

    if(urgencyId === 3) {
        urgencyBadge = `<span class="badge bg-danger urgency-pulse"><i class="fas fa-exclamation-triangle me-1"></i>${escapeHtml(urgencyName)}</span>`;
    } else if(urgencyId === 2) {
        urgencyBadge = `<span class="badge bg-warning text-dark"><i class="fas fa-clock me-1"></i>${escapeHtml(urgencyName)}</span>`;
    } else {
        urgencyBadge = `<span class="badge bg-info">${escapeHtml(urgencyName)}</span>`;
    }
    
    let brandDisplay = ticketValue(request, request.brand, true);

    if (request.is_manual_brand == 1) {
        brandDisplay += ' <span class="badge bg-warning text-dark"><i class="fas fa-pencil-alt"></i> manual</span>';
    }
    
    let applianceDisplay = ticketValue(request, request.appliance_type, true);

    if (request.is_manual_appliance == 1) {
        applianceDisplay += ' <span class="badge bg-warning text-dark"><i class="fas fa-pencil-alt"></i> manual</span>';
    }
    
    let preferredTimeDisplay = request.preferred_time === 'AM'
        ? 'AM'
        : request.preferred_time === 'PM'
            ? 'PM'
            : (
                request.preferred_time === '08:00:00' ||
                request.preferred_time === '09:00:00' ||
                request.preferred_time === '10:00:00' ||
                request.preferred_time === '11:00:00'
            )
                ? 'AM'
                : 'PM';

    const isManualTicket = (request.ticket_source === 'csr_manual' || request.created_by_csr_id || request.manual_ticket_number);
    const sourceDisplay = request.ticket_source_label || normalizeSourceLabel(request.ticket_source);
    const ticketAgeDisplay = formatDuration(request.ticket_age_minutes);
    const inProgressDisplay = request.in_progress_minutes ? formatDuration(request.in_progress_minutes).replace(' old','') : '';
    const manualCreator = request.created_by_csr_name || request.managing_csr || 'N/A';
    const secondaryPhone = request.secondary_phone || '';
    const addressNote = request.service_address_2 || request.landmark || '';

    let manualInfoHtml = '';
    if(isManualTicket) {
        manualInfoHtml = `
            <div class="row mt-3">
                <div class="col-12">
                    <h6 class="border-bottom pb-2"><i class="fas fa-headset me-2"></i>Manual Ticket / Call Information</h6>
                    <table class="table table-sm table-bordered">
                        <tr>
                            <th width="25%">Ticket No:</th>
                            <td>${escapeHtml(request.manual_ticket_number || request.request_number || 'Auto generated')}</td>
                            <th width="25%">Ticket Source:</th>
                            <td>${escapeHtml(sourceDisplay)}</td>
                        </tr>
                        <tr>
                            <th>Call Source:</th>
                            <td>${escapeHtml(readSpecialField(request.special_request, 'Source') || 'N/A')}</td>
                            <th>Call Received Date:</th>
                            <td>${escapeHtml(formatPlainDate(request.call_received_date) || 'N/A')}</td>
                        </tr>
                        <tr>
                            <th>Created / Inputted By:</th>
                            <td>${escapeHtml(manualCreator)}</td>
                            <th>Fake Ticket:</th>
                            <td>${parseInt(request.is_fake_ticket || 0, 10) === 1 ? '<span class="badge bg-warning text-dark">Yes - excluded statistically</span>' : '<span class="badge bg-success">No</span>'}</td>
                        </tr>
                    </table>
                </div>
            </div>
        `;
    }

    let html = `
        <div class="row">
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Request Information</h6>

                <table class="table table-sm">
                    <tr><th width="40%">Request Number:</th><td><strong>${escapeHtml(request.request_number)}</strong></td></tr>
                    <tr><th>Request Type:</th><td>${sourceBadge(sourceDisplay)}</td></tr>
                    <tr><th>Status:</th><td>${statusBadge}</td></tr>
                    <tr><th>Urgency:</th><td>${urgencyBadge}</td></tr>
                    <tr><th>Requested Date:</th><td>${formatDate(request.requested_at)}</td></tr>
                    <tr><th>Ticket Aging:</th><td>${ticketAgeDisplay}</td></tr>
                    ${request.job_status_id == 3 ? `<tr><th>In Progress Timer:</th><td>${inProgressDisplay}</td></tr>` : ''}
                    <tr><th>Last Updated:</th><td>${formatDate(request.last_updated_at || request.requested_at)}</td></tr>
                    <tr><th>Call Received Date:</th><td>${escapeHtml(request.call_received_date || 'N/A')}</td></tr>
                    <tr><th>Source:</th><td>${sourceBadge(sourceDisplay)}</td></tr>
                    <tr><th>CX Preferred Date:</th><td>${escapeHtml(formatPlainDate(request.preferred_date) || 'Not specified')}</td></tr>
                    <tr><th>Preferred Time:</th><td>${preferredTimeDisplay}</td></tr>
                </table>
            </div>
            
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Customer Information</h6>

                <table class="table table-sm">
                    <tr><th width="40%">Name:</th><td><strong>${escapeHtml(request.full_name)}</strong></td></tr>
                    <tr><th>Primary Phone:</th><td>${ticketValue(request, request.phone_number)}</td></tr>
                    <tr><th>Secondary Phone:</th><td>${ticketValue(request, secondaryPhone, true)}</td></tr>
                    <tr><th>Email:</th><td>${ticketValue(request, request.email || request.customer_email, true)}</td></tr>
                </table>
            </div>
        </div>
        
        ${manualInfoHtml}

        ${request.is_locked_by_other_csr == 1 ? `
            <div class="alert alert-warning mt-3 mb-0">
                <i class="fas fa-lock me-2"></i>
                This request is currently being handled by <strong>${escapeHtml(request.managing_csr)}</strong>. You can view it, but updates are disabled for your account.
            </div>
        ` : ''}

        <div class="row mt-3">
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Product / Appliance Details</h6>

                <table class="table table-sm">
                    <tr><th width="40%">Brand:</th><td>${brandDisplay}</td></tr>
                    <tr><th>Product Category:</th><td>${applianceDisplay}</td></tr>
                    <tr><th>Model:</th><td>${ticketValue(request, request.model_number, true)}</td></tr>
                    <tr><th>Serial:</th><td>${ticketValue(request, request.serial_number, true)}</td></tr>
                    <tr><th>Model Version:</th><td>${ticketValue(request, request.product_model_version, true)}</td></tr>
                    <tr><th>Purchase Date:</th><td>${ticketValue(request, formatPlainDate(request.purchase_date), true)}</td></tr>
                    <tr><th>Warranty Type:</th><td>${ticketValue(request, request.warranty_type, true)}</td></tr>
                </table>
            </div>
            
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Service Address</h6>
                <table class="table table-sm">
                    <tr><th width="40%">Address:</th><td>${ticketValue(request, request.service_address)}</td></tr>
                    <tr><th>City:</th><td>${ticketValue(request, request.city_name)}</td></tr>
                    <tr><th>State:</th><td>${ticketValue(request, request.service_state || request.state)}</td></tr>
                    <tr><th>Zip Code:</th><td>${ticketValue(request, request.zip_code)}</td></tr>
                    <tr><th>Address Note:</th><td>${ticketValue(request, addressNote, true)}</td></tr>
                </table>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="border-bottom pb-2">Problem / Issue Description</h6>

                <div class="p-3 bg-light rounded">
                    <p class="mb-0">${ticketValue(request, request.issue_description)}</p>
                </div>
            </div>
        </div>

        ${request.follow_up_reminder ? `
            <div class="row mt-3">
                <div class="col-12">
                    <div class="alert alert-info mb-0"><i class="fas fa-bell me-2"></i><strong>Follow-Up Reminder:</strong> ${escapeHtml(request.follow_up_reminder)}</div>
                </div>
            </div>` : ''}
    `;
    

    if(request.activity_logs && request.activity_logs.length > 0) {
        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <h6 class="border-bottom pb-2"><i class="fas fa-history me-2"></i>Activity Logs</h6>
                    <div class="timeline">
        `;
        request.activity_logs.forEach(function(log) {
            html += `
                <div class="card mb-2 border-start border-3 border-info">
                    <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-start gap-2">
                            <div><strong>${escapeHtml(log.actor_name || log.updated_by_name || 'Account not recorded')}</strong> <span class="text-muted">${escapeHtml(log.action_label || log.action || 'updated ticket')}</span></div>
                            <small class="text-muted">${formatDate(log.created_at || log.changed_at)}</small>
                        </div>
                        ${log.notes ? `<p class="mb-0 mt-1">${escapeHtml(log.notes)}</p>` : ''}
                    </div>
                </div>
            `;
        });
        html += `</div></div></div>`;
    }

    if(request.notes && request.notes.length > 0) {
        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <h6 class="border-bottom pb-2">
                        <i class="fas fa-sticky-note me-2"></i>Notes & Activity (${request.notes.length})
                    </h6>

                    <div class="timeline">
        `;
        
        request.notes.forEach(function(note) {
            let noteTypeClass = '';
            let noteTypeIcon = '';

            switch(note.note_type) {
                case 'csr_note':
                case 'internal':
                    noteTypeClass = 'border-info';
                    noteTypeIcon = '<i class="fas fa-lock text-info"></i>';
                    break;
                case 'customer':
                    noteTypeClass = 'border-success';
                    noteTypeIcon = '<i class="fas fa-bullhorn text-success"></i>';
                    break;
                default:
                    noteTypeClass = 'border-secondary';
                    noteTypeIcon = '<i class="fas fa-sticky-note text-secondary"></i>';
            }
            
            html += `
                <div class="card mb-2 ${noteTypeClass} border-start border-3">
                    <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-start gap-2">
                            <div>
                                ${noteTypeIcon} <strong>${escapeHtml(note.note_type_label)}</strong> - ${escapeHtml(note.created_by_name || 'CSR')}
                            </div>

                            <small class="text-muted">${formatDate(note.created_at)}</small>
                        </div>

                        <p class="mb-0 mt-1">${escapeHtml(note.note_content)}</p>

                        ${note.notified_customer == 1 ? '<small class="text-success"><i class="fas fa-envelope"></i> Customer notified</small>' : ''}
                    </div>
                </div>
            `;
        });
        
        html += `
                    </div>
                </div>
            </div>
        `;
    }
    
    if(request.current_assignments && request.current_assignments.length > 0) {
        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <h6 class="border-bottom pb-2">
                        <i class="fas fa-users me-2"></i>
                        Assigned Technicians (${request.current_assignments.length})
                        ${request.current_assignments.length >= 2 ? '<span class="badge bg-warning text-dark ms-2">Double Job</span>' : ''}
                    </h6>

                    <div class="table-responsive">
                        <table class="table table-sm table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th>Role</th>
                                    <th>Technician Name</th>
                                    <th>Phone</th>
                                    <th>Status</th>
                                    <th>Assigned At</th>
                                    <th>Notes</th>
                                </tr>
                            </thead>

                            <tbody>
        `;
        
        request.current_assignments.forEach(function(assignment) {
            let roleClass = '';

            if(assignment.assignment_type == 'primary') {
                roleClass = 'bg-primary text-white';
            } else if(assignment.assignment_type == 'secondary') {
                roleClass = 'bg-info text-white';
            } else {
                roleClass = 'bg-secondary text-white';
            }
            
            html += `
                <tr>
                    <td><span class="badge ${roleClass}">${escapeHtml(assignment.role_display)}</span></td>
                    <td><strong>${escapeHtml(assignment.technician_name)}</strong></td>
                    <td>${escapeHtml(assignment.technician_phone || 'N/A')}</td>
                    <td><span class="badge bg-info">${escapeHtml(assignment.status.replace('_', ' '))}</span></td>
                    <td><small>${formatDate(assignment.assigned_at)}</small></td>
                    <td><small>${escapeHtml(assignment.csr_notes || '')}</small></td>
                </tr>
            `;
        });
        
        html += `
                            </tbody>
                        </table>
                    </div>

                    ${request.is_locked_by_other_csr == 1 ? '' : `
                        <div class="mt-2">
                            <button class="btn btn-sm btn-info" onclick="openAssignTechnicianModalForRequest(${request.id})">
                                <i class="fas fa-user-plus me-1"></i> Add Another Technician
                            </button>
                        </div>
                    `}
                </div>
            </div>
        `;
    }
    
    if(request.images && request.images.length > 0) {
        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <h6 class="border-bottom pb-2">Uploaded Images (${request.images.length})</h6>

                    <div class="row">
        `;
        
        request.images.forEach(function(image) {
            let imagePath = image.image_path;

            if (imagePath.indexOf('../') === -1 && imagePath.indexOf('uploads/') !== -1) {
                imagePath = '../' + imagePath;
            }
            
            html += `
                <div class="col-4 col-md-3 mb-3">
                    <img src="${imagePath}" 
                         class="img-fluid rounded" 
                         style="height: 100px; width: 100%; object-fit: cover; cursor: pointer; border: 1px solid rgba(96,165,250,.35);" 
                         onclick="zoomImage('${imagePath}')">
                </div>
            `;
        });
        
        html += `
                    </div>
                </div>
            </div>
        `;
    }
    
    $('#requestDetailsBody').html(html);
}


function openEditDetailsModal() {
    if(!currentRequestData) return;
    const r = currentRequestData;
    $('#editRequestId').val(r.id || currentRequestId);
    $('#editFullName').val(r.full_name || '');
    $('#editPhone').val(r.phone_number || '');
    $('#editSecondaryPhone').val(r.secondary_phone || '');
    $('#editEmail').val(r.manual_customer_email || r.email || '');
    $('#editAddress').val(r.service_address || '');
    $('#editAddress2').val(r.service_address_2 || '');
    $('#editZip').val(r.zip_code || '');
    $('#editRegion').val(r.region || '');
    $('#editCity').val(r.city_name || '');
    $('#editState').val(r.state || r.service_state || '');
    $('#editLandmark').val(r.landmark || '');
    $('#editBrand').val(r.brand || '');
    $('#editAppliance').val(r.appliance_type || '');
    $('#editModel').val(r.model_number || '');
    $('#editSerial').val(r.serial_number || '');
    $('#editModelVersion').val(r.product_model_version || '');
    $('#editPurchaseDate').val(r.purchase_date || '');
    $('#editWarrantyType').val(r.warranty_type || '');
    $('#editPreferredDate').val(r.preferred_date || '');
    $('#editIssue').val(r.issue_description || '');
    $('#editSpecial').val(r.special_request || '');
    $('#editDetailsModal').modal('show');
}

function saveRequestDetails() {
    $.ajax({
        url: '../csr/ajax/update_request_details.php',
        method: 'POST',
        data: $('#editDetailsForm').serialize(),
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#editDetailsModal').modal('hide');
                alert(response.message || 'Request details updated.');
                viewRequestDetails(currentRequestId);
                loadRequests();
            } else {
                alert('Error: ' + (response.message || 'Unable to update request details.'));
            }
        },
        error: function() { alert('Error updating request details.'); }
    });
}

function openAddNoteModal() {
    if(currentRequestId) {
        $('#noteRequestId').val(currentRequestId);
        $('#noteContent').val('');
        $('#noteType').val('internal');
        $('#followUpReminder').val('');
        $('#notifyCustomer').prop('checked', false);
        $('#addNoteModal').modal('show');
    }
}

function quickAddNote(requestId) {
    currentRequestId = requestId;
    openAddNoteModal();
}

function saveNote() {
    const formData = {
        request_id: $('#noteRequestId').val(),
        note_type: $('#noteType').val(),
        note_content: $('#noteContent').val(),
        follow_up_reminder: $('#followUpReminder').val(),
        notify_customer: $('#notifyCustomer').is(':checked') ? 1 : 0
    };
    
    $.ajax({
        url: '../csr/ajax/add_note.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#addNoteModal').modal('hide');
                alert('Note added successfully!');
                viewRequestDetails(currentRequestId);
                loadRequests();
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function() {
            alert('Error saving note. Please try again.');
        }
    });
}

function openUpdateStatusModal() {
    if(currentRequestId) {
        $('#statusRequestId').val(currentRequestId);
        $('#statusNotes').val('');
        $('#updateStatusModal').modal('show');
    }
}

function updateRequestStatus() {
    const selectedStatus = $('#newStatus').val();
    const selectedStatusText = $('#newStatus option:selected').text().trim();

    if(selectedStatus == '4' || selectedStatus == '5') {
        const actionText = selectedStatus == '4' ? 'complete' : 'cancel';

        if(!confirm(`Are you sure this ticket is ${selectedStatusText}? This will ${actionText} the request and update technician assignment status.`)) {
            return;
        }
    }

    const formData = {
        request_id: $('#statusRequestId').val(),
        job_status_id: selectedStatus,
        status_notes: $('#statusNotes').val()
    };
    
    $.ajax({
        url: '../csr/ajax/update_request_status.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#updateStatusModal').modal('hide');
                alert('Status updated successfully!');
                viewRequestDetails(currentRequestId);
                loadRequests();
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function() {
            alert('Error updating status. Please try again.');
        }
    });
}

function loadTechnicians() {
    $.ajax({
        url: '../csr/ajax/get_available_technicians.php',
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if(response.success && response.technicians) {
                let options = '<option value="">Select Technician</option>';

                response.technicians.forEach(function(tech) {
                    options += `<option value="${tech.id}">${escapeHtml(tech.full_name)} - ${escapeHtml(tech.specialization || 'General')}</option>`;
                });

                $('#technicianSelect').html(options);
            } else {
                $('#technicianSelect').html('<option value="">No technicians available</option>');
            }
        },
        error: function() {
            $('#technicianSelect').html('<option value="">Error loading technicians</option>');
        }
    });
}

function assignTechnician() {
    const formData = {
        request_id: $('#assignRequestId').val(),
        technician_id: $('#technicianSelect').val(),
        estimated_arrival_date: $('#estimatedArrivalDate').val(),
        estimated_arrival_period: $('#estimatedArrivalPeriod').val(),
        assignment_notes: $('#assignmentNotes').val()
    };
    
    if(!formData.technician_id) {
        alert('Please select a technician');
        return;
    }

    if(!formData.estimated_arrival_date || !formData.estimated_arrival_period) {
        alert('Please select estimated arrival date and AM/PM period');
        return;
    }
    
    $.ajax({
        url: '../csr/ajax/assign_technician.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#assignTechnicianModal').modal('hide');
                alert('Technician assigned successfully!');
                viewRequestDetails(currentRequestId);
                loadRequests();

                $('#estimatedArrivalDate').val('');
                $('#estimatedArrivalPeriod').val('');
                $('#assignmentNotes').val('');
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function() {
            alert('Error assigning technician. Please try again.');
        }
    });
}

function zoomImage(src) {
    $('#zoomedImage').attr('src', src);
    $('#imageZoomModal').modal('show');
}

function readSpecialField(text, label) {
    if(!text || !label) return '';
    const lines = String(text).split(/\r?\n/);
    const prefix = String(label).toLowerCase() + ':';

    for(let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if(line.toLowerCase().indexOf(prefix) === 0) {
            return line.substring(prefix.length).trim();
        }
    }

    return '';
}

function formatPlainDate(dateString) {
    if(!dateString || dateString === '0000-00-00') return '';

    try {
        const date = new Date(String(dateString) + 'T00:00:00');
        if(isNaN(date.getTime())) return dateString;

        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    } catch(e) {
        return dateString;
    }
}

function formatDate(dateString) {
    if(!dateString) return 'N/A';

    try {
        let date = new Date(dateString);

        if(isNaN(date.getTime())) return dateString;

        return date.toLocaleString('en-US', { 
            timeZone: 'America/Chicago',
            year: 'numeric', 
            month: 'short', 
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            timeZoneName: 'short'
        });
    } catch(e) {
        return dateString;
    }
}


function sourceBadge(source) {
    const label = normalizeSourceLabel(source);
    let cls = 'bg-info';
    let icon = 'fa-globe';
    if(label === 'Manual Ticket') { cls = 'bg-warning text-dark'; icon = 'fa-headset'; }
    if(label === 'Chat Follow-Up Request') { cls = 'bg-success'; icon = 'fa-comments'; }
    return `<span class="badge ${cls}"><i class="fas ${icon} me-1"></i>${escapeHtml(label)}</span>`;
}

function normalizeSourceLabel(source) {
    const s = String(source || '').toLowerCase();
    if(s === 'csr_manual' || s === 'csr manual ticket') return 'Manual Ticket';
    if(s === 'chat_followup' || s === 'chat follow-up request') return 'Chat Follow-Up Request';
    return 'Customer Online Request';
}

function formatDuration(minutes) {
    const total = parseInt(minutes || 0, 10);
    if(total < 60) return total <= 1 ? '1 minute old' : `${total} minutes old`;
    const hours = Math.floor(total / 60);
    if(hours < 24) return hours === 1 ? '1 hour old' : `${hours} hours old`;
    const days = Math.floor(hours / 24);
    return days === 1 ? '1 day old' : `${days} days old`;
}

function ticketValue(request, value, csrOnly = false) {
    if(value !== null && value !== undefined && String(value).trim() !== '') return escapeHtml(value);
    const source = String(request.ticket_source || '').toLowerCase();
    const isCx = !source || source === 'customer' || source === 'cx_online';
    if(isCx && csrOnly) return '<span class="text-muted fst-italic">Please complete this field if needed</span>';
    return '<span class="text-muted">Not specified</span>';
}

function escapeHtml(text) {
    if(!text) return '';

    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function showError(message) {
    $('#requestsTableBody').html(`
        <tr>
            <td colspan="12" class="text-center py-5 text-danger">
                <i class="fas fa-exclamation-triangle fa-3x mb-3"></i>
                <p>${escapeHtml(message)}</p>
                <button class="btn btn-sm btn-primary" onclick="loadRequests()">Retry</button>
            </td>
        </tr>
    `);
}

function showSuccess(message) {
    if (typeof window.showToast === 'function') {
        window.showToast(message, 'success');
    } else {
        alert(message);
    }
}

function showErrorInModal(message) {
    $('#requestDetailsBody').html(`
        <div class="text-center py-5 text-danger">
            <i class="fas fa-exclamation-triangle fa-3x mb-3"></i>
            <p>${escapeHtml(message)}</p>
        </div>
    `);
}
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>