<?php
/**
 * Tripper Records List Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/nepali_calendar.php';

$user = getCurrentUser();
$pdo  = getPDO();

// Handle delete
if (isset($_GET['delete']) && (hasRole('admin') || ($user['can_delete'] == 1))) {
    $deleteId = (int)$_GET['delete'];
    if ($deleteId > 0) {
        $pdo->prepare("DELETE FROM tripper_records WHERE id = ?")->execute([$deleteId]);
        showMessage('Record deleted successfully!', 'success');
    }
}

// Role-based project restriction
$roleProjectFilter = '';
$roleParams = [];
if ($user['role'] !== 'admin' && $user['role'] !== 'viewer' && $user['assigned_projects']) {
    $projectIds   = explode(',', $user['assigned_projects']);
    $placeholders = implode(',', array_fill(0, count($projectIds), '?'));
    $roleProjectFilter = " AND t.project_id IN ($placeholders)";
    $roleParams        = $projectIds;
}

// Dropdown data
$projects = [];
$stmt = $pdo->query("SELECT * FROM projects WHERE is_active = 1 ORDER BY project_name");
while ($row = $stmt->fetch()) $projects[$row['id']] = $row['project_name'];

$collectors = [];
$stmt = $pdo->query("SELECT id, full_name FROM users WHERE is_active = 1 ORDER BY full_name");
while ($row = $stmt->fetch()) $collectors[$row['id']] = $row['full_name'];

$vehicles_list = [];
$stmt = $pdo->query("SELECT id, vehicle_number FROM vehicles WHERE is_active = 1 ORDER BY vehicle_number");
while ($row = $stmt->fetch()) $vehicles_list[$row['id']] = $row['vehicle_number'];

// Filter parameters
$currentToday  = get_nepali_date_input_value();
$search        = sanitize($_GET['search']       ?? '');
$project_id    = sanitize($_GET['project_id']   ?? '');
$status        = sanitize($_GET['status']        ?? '');
$date_from     = sanitize($_GET['date_from']     ?? $currentToday);
$date_to       = sanitize($_GET['date_to']       ?? $currentToday);
$collector_id  = sanitize($_GET['collector_id']  ?? '');
$vehicle_id    = sanitize($_GET['vehicle_id']    ?? '');
$trip_no       = sanitize($_GET['trip_no']       ?? '');
$entity_type   = sanitize($_GET['entity_type']   ?? '');

$hasFilters = ($search || $project_id || $status || $collector_id || $vehicle_id || $trip_no || $entity_type
    || $date_from !== $currentToday || $date_to !== $currentToday);

// Build WHERE
$whereClause = "1=1" . $roleProjectFilter;
$params      = $roleParams;

if ($search) {
    $whereClause .= " AND (v.vehicle_number LIKE ? OR dr.full_name LIKE ? OR t.work_location LIKE ? OR t.loading_location LIKE ? OR t.unloading_place LIKE ? OR p.project_name LIKE ?)";
    array_push($params, "%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%");
}
if ($project_id)   { $whereClause .= " AND t.project_id = ?";  $params[] = $project_id; }
if ($status)       { $whereClause .= " AND t.status = ?";       $params[] = $status; }
if ($date_from)    { $whereClause .= " AND t.created_date >= ?"; $params[] = $date_from; }
if ($date_to)      { $whereClause .= " AND t.created_date <= ?"; $params[] = $date_to; }
if ($collector_id) { $whereClause .= " AND (t.loading_collector_id = ? OR t.unloading_collector_id = ?)"; $params[] = $collector_id; $params[] = $collector_id; }
if ($vehicle_id)   { $whereClause .= " AND t.vehicle_id = ?";   $params[] = $vehicle_id; }
if ($entity_type)  { $whereClause .= " AND df.entity_type = ?"; $params[] = $entity_type; }

// Max trip sequence
$maxTripSql = "SELECT MAX(trip_sequence) FROM (
    SELECT (SELECT COUNT(*) FROM tripper_records t2
            WHERE t2.vehicle_id = t.vehicle_id AND t2.created_date = t.created_date
            AND (t2.loading_time < t.loading_time OR (t2.loading_time = t.loading_time AND t2.id <= t.id))
           ) as trip_sequence
    FROM tripper_records t
    LEFT JOIN projects p ON t.project_id = p.id
    LEFT JOIN vehicles v ON t.vehicle_id = v.id
    LEFT JOIN drivers dr ON t.driver_id = dr.id
    LEFT JOIN deployed_from df ON t.deployed_from_id = df.id
    WHERE $whereClause) AS r";
$stmtMax = $pdo->prepare($maxTripSql);
$stmtMax->execute($params);
$maxTripCount = (int)$stmtMax->fetchColumn();

// Main query
$sql = "SELECT * FROM (
    SELECT t.*, p.project_name, v.vehicle_number, dr.full_name as driver_name,
           df.entity_name as deployed_name, df.entity_type as entity_type_val, g.group_name,
           (SELECT COUNT(*) FROM tripper_records t2
            WHERE t2.vehicle_id = t.vehicle_id AND t2.created_date = t.created_date
            AND (t2.loading_time < t.loading_time OR (t2.loading_time = t.loading_time AND t2.id <= t.id))
           ) as trip_sequence
    FROM tripper_records t
    LEFT JOIN projects p ON t.project_id = p.id
    LEFT JOIN vehicles v ON t.vehicle_id = v.id
    LEFT JOIN drivers dr ON t.driver_id = dr.id
    LEFT JOIN deployed_from df ON t.deployed_from_id = df.id
    LEFT JOIN groups g ON t.group_id = g.id
    WHERE $whereClause
) AS results";

$finalParams = $params;
if ($trip_no) {
    if (is_numeric($trip_no))      { $sql .= " WHERE trip_sequence = ?"; $finalParams[] = (int)$trip_no; }
    elseif ($trip_no === 'others') { $sql .= " WHERE trip_sequence > 3"; }
}
$sql .= " ORDER BY created_date DESC, loading_time DESC, id DESC";

$stmt    = $pdo->prepare($sql);
$stmt->execute($finalParams);
$records = $stmt->fetchAll();

// Summary stats
$totalKm        = 0;
$totalCompleted = 0;
$totalPending   = 0;
foreach ($records as $r) {
    $diff = $r['unloading_end_odometer'] - $r['loading_start_odometer'];
    if ($diff > 0) $totalKm += $diff;
    if ($r['status'] === 'completed')        $totalCompleted++;
    if ($r['status'] === 'pending_unloading') $totalPending++;
}

$pageTitle = "Tripper Records";
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
:root {
    --c-green:  #10b981;
    --c-blue:   #3b82f6;
    --c-grad:   linear-gradient(135deg,#10b981 0%,#3b82f6 100%);
    --c-dark:   #1e293b;
    --c-muted:  #64748b;
    --c-bg:     #f1f5f9;
    --c-card:   #ffffff;
    --radius:   16px;
}
body { font-family:'Plus Jakarta Sans',sans-serif!important; background:var(--c-bg); }

/* ── PAGE HEADER ── */
.page-hdr { padding:1.25rem 0 0.5rem; }
.page-hdr h1 { font-size:1.6rem; font-weight:800; background:var(--c-grad);
               -webkit-background-clip:text; -webkit-text-fill-color:transparent; margin:0; }
.page-hdr p  { color:var(--c-muted); font-size:0.85rem; margin:0.15rem 0 0; }
.btn-add { background:var(--c-grad); color:#fff; border:none; border-radius:12px;
           padding:0.6rem 1.2rem; font-weight:700; font-size:0.9rem; white-space:nowrap;
           box-shadow:0 6px 16px rgba(16,185,129,.3); transition:transform .2s,box-shadow .2s; }
.btn-add:hover { transform:translateY(-2px); box-shadow:0 10px 24px rgba(16,185,129,.4); color:#fff; }

/* ── FILTER PANEL ── */
.filter-panel { background:#fff; border-radius:var(--radius); padding:1rem 1.25rem;
                box-shadow:0 2px 12px rgba(0,0,0,.06); margin-bottom:1rem; }
.filter-panel.collapsed .filter-body { display:none; }
.filter-toggle { display:none; }
.filter-label { font-size:0.68rem; font-weight:700; text-transform:uppercase;
                letter-spacing:.8px; color:var(--c-muted); margin-bottom:4px; display:block; }
.f-input { border-radius:10px; border:1.5px solid #e2e8f0; font-size:0.88rem;
           padding:0.55rem 0.75rem; transition:border-color .2s,box-shadow .2s; width:100%; }
.f-input:focus { outline:none; border-color:var(--c-green);
                 box-shadow:0 0 0 3px rgba(16,185,129,.12); }
.btn-search { background:var(--c-dark); color:#fff; border:none; border-radius:10px;
              padding:0.55rem 1rem; font-weight:700; font-size:0.9rem; transition:background .2s; }
.btn-search:hover { background:#334155; }
.btn-clear { background:#fee2e2; color:#dc2626; border:none; border-radius:10px;
             padding:0.55rem 0.75rem; font-weight:700; font-size:0.9rem; transition:background .2s; }
.btn-clear:hover { background:#fca5a5; }

/* Active filter chips */
.filter-chips { display:flex; flex-wrap:wrap; gap:0.4rem; margin-top:0.75rem; }
.chip { background:#eff6ff; color:#2563eb; border-radius:20px; padding:3px 10px;
        font-size:0.75rem; font-weight:600; display:inline-flex; align-items:center; gap:4px; }
.chip.green { background:#ecfdf5; color:#059669; }
.chip.orange { background:#fff7ed; color:#d97706; }

/* ── TRIP TABS ── */
.trip-tabs { display:flex; gap:0.5rem; flex-wrap:wrap; margin-bottom:1rem; }
.trip-tab { background:#fff; border:1.5px solid #e2e8f0; color:var(--c-muted);
            padding:0.45rem 1rem; border-radius:10px; font-size:0.8rem; font-weight:700;
            text-decoration:none; transition:all .2s; white-space:nowrap; }
.trip-tab:hover { background:#f8fafc; color:var(--c-dark); border-color:#cbd5e1; }
.trip-tab.active { background:var(--c-dark); color:#fff; border-color:var(--c-dark);
                   box-shadow:0 3px 10px rgba(0,0,0,.15); }

/* ── SUMMARY BAR ── */
.summary-bar { background:#fff; border-radius:var(--radius); padding:0.75rem 1.25rem;
               margin-bottom:1rem; box-shadow:0 2px 8px rgba(0,0,0,.05);
               display:flex; gap:1.5rem; flex-wrap:wrap; align-items:center; }
.s-stat { display:flex; align-items:center; gap:0.5rem; }
.s-stat .s-num { font-size:1.1rem; font-weight:800; color:var(--c-dark); }
.s-stat .s-lbl { font-size:0.75rem; color:var(--c-muted); font-weight:600; }

/* ── RECORD CARDS ── */
.records-wrap { display:flex; flex-direction:column; gap:0.75rem; }

.rec-card { background:#fff; border-radius:var(--radius); border:1.5px solid #f1f5f9;
            box-shadow:0 2px 8px rgba(0,0,0,.04); overflow:hidden;
            transition:box-shadow .25s, transform .25s; }
.rec-card:hover { box-shadow:0 8px 24px rgba(0,0,0,.09); transform:translateY(-1px); }

/* Desktop: grid row */
.rec-grid { display:grid;
            grid-template-columns: 130px 140px 1fr 1fr 110px 130px;
            align-items:center; padding:0.9rem 1.1rem; gap:1rem; }
.rec-accent { width:4px; background:var(--c-grad); border-radius:4px 0 0 4px;
              position:absolute; left:0; top:0; bottom:0; display:none; }
.rec-card:hover .rec-accent { display:block; }

.fld-lbl { font-size:0.65rem; font-weight:700; text-transform:uppercase;
           letter-spacing:.8px; color:var(--c-muted); margin-bottom:3px; }
.fld-val { font-size:0.9rem; font-weight:700; color:var(--c-dark); }
.fld-sub { font-size:0.78rem; color:var(--c-muted); margin-top:2px; }

.loc-badge { display:inline-flex; align-items:center; gap:5px; border-radius:8px;
             padding:4px 10px; font-size:0.78rem; font-weight:700; }
.loc-load   { background:#ecfdf5; color:#059669; }
.loc-unload { background:#eff6ff; color:#2563eb; }

.km-badge { font-size:0.72rem; font-weight:700; border-radius:8px; padding:3px 8px; display:inline-block; margin-top:3px; }
.km-ok  { background:#dcfce7; color:#16a34a; }
.km-err { background:#fee2e2; color:#dc2626; }
.km-na  { background:#f1f5f9; color:#64748b; }

.status-pill { border-radius:20px; padding:5px 12px; font-size:0.75rem; font-weight:700;
               display:inline-flex; align-items:center; gap:6px; }
.pill-pending   { background:#fef3c7; color:#d97706; }
.pill-completed { background:#dcfce7; color:#16a34a; }
.pill-cancelled { background:#fee2e2; color:#dc2626; }

.act-btn { width:34px; height:34px; border-radius:9px; border:none; background:#f1f5f9;
           color:#475569; display:inline-flex; align-items:center; justify-content:center;
           transition:all .2s; text-decoration:none; font-size:0.82rem; }
.act-btn:hover { transform:translateY(-1px); }
.act-btn.view:hover   { background:#dbeafe; color:#2563eb; }
.act-btn.edit:hover   { background:#fef3c7; color:#d97706; }
.act-btn.comp:hover   { background:#dcfce7; color:#16a34a; }
.act-btn.del:hover    { background:#fee2e2; color:#dc2626; }
.act-btns { display:flex; gap:0.35rem; }

/* Entity dot */
.entity-dot { width:8px; height:8px; border-radius:50%; display:inline-block; margin-right:4px; }
.dot-kmc     { background:#3b82f6; }
.dot-private { background:#8b5cf6; }
.dot-other   { background:#10b981; }

/* ── MOBILE ── */
@media (max-width:767px) {
    .filter-toggle { display:flex; align-items:center; justify-content:space-between;
                     width:100%; background:none; border:none; padding:0; cursor:pointer; }
    .filter-toggle .ft-left { font-weight:700; font-size:0.95rem; color:var(--c-dark); }
    .filter-toggle .ft-badge { background:var(--c-grad); color:#fff; border-radius:20px;
                                font-size:0.7rem; padding:2px 8px; font-weight:700; }
    .filter-panel { padding:0.9rem 1rem; }
    .filter-panel .filter-body { padding-top:0.9rem; }
    .page-hdr h1 { font-size:1.3rem; }

    /* Mobile card — stacked */
    .rec-grid { display:none; }
    .rec-mobile { display:block; padding:0.9rem 1rem; }
    .rm-top { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:0.6rem; }
    .rm-mid { display:grid; grid-template-columns:1fr 1fr; gap:0.6rem; margin-bottom:0.6rem; }
    .rm-bot { display:flex; justify-content:space-between; align-items:center;
              border-top:1px solid #f1f5f9; padding-top:0.6rem; }
    .rm-vehicle { font-size:1rem; font-weight:800; color:var(--c-dark); }
    .rm-date    { font-size:0.78rem; color:var(--c-muted); font-weight:600; }
    .rm-trip-badge { background:var(--c-grad); color:#fff; border-radius:8px;
                     padding:3px 9px; font-size:0.72rem; font-weight:700; }

    .summary-bar { gap:1rem; padding:0.6rem 1rem; }
    .s-stat .s-num { font-size:0.95rem; }

    .trip-tab { padding:0.4rem 0.8rem; font-size:0.75rem; }
    .btn-add { padding:0.5rem 0.9rem; font-size:0.82rem; }
}

@media (min-width:768px) {
    .rec-mobile { display:none; }
}

/* Empty state */
.empty-state { text-align:center; padding:3rem 1rem; background:#fff;
               border-radius:var(--radius); box-shadow:0 2px 8px rgba(0,0,0,.04); }
</style>

<?php displayMessage(); ?>

<div class="container-fluid px-3 px-md-4 py-3">

<!-- ── PAGE HEADER ── -->
<div class="d-flex align-items-center justify-content-between page-hdr mb-3">
    <div>
        <h1>Tripper Records</h1>
        <p>Fleet operations · <?php echo count($records); ?> records</p>
    </div>
    <?php if (hasRole('admin') || hasAccess('tripper_loading_only') || hasAccess('all_modules')): ?>
    <a href="add_loading.php" class="btn-add">
        <i class="fas fa-plus me-1"></i> New Loading
    </a>
    <?php endif; ?>
</div>

<!-- ── FILTER PANEL ── -->
<div class="filter-panel <?php echo !$hasFilters ? 'collapsed' : ''; ?>" id="filterPanel">
    <button type="button" class="filter-toggle" onclick="toggleFilter()">
        <span class="ft-left"><i class="fas fa-sliders-h me-2 text-muted"></i>Filters</span>
        <span class="ft-badge" id="filterBadge" style="<?php echo $hasFilters ? '' : 'display:none'; ?>">
            Active
        </span>
        <i class="fas fa-chevron-down text-muted" id="filterChevron" style="transition:transform .3s;<?php echo $hasFilters ? 'transform:rotate(180deg)' : ''; ?>"></i>
    </button>
    <div class="filter-body">
        <form method="GET" action="" id="filterForm">
            <div class="row g-2 mt-1">
                <!-- Search -->
                <div class="col-12 col-md-4 col-lg-3">
                    <label class="filter-label">Search</label>
                    <input type="text" name="search" class="f-input" placeholder="Vehicle, driver, location..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <!-- Entity -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Entity</label>
                    <select name="entity_type" class="f-input">
                        <option value="">All Entities</option>
                        <option value="kmc"     <?php echo $entity_type==='kmc'     ?'selected':''; ?>>KMC</option>
                        <option value="private" <?php echo $entity_type==='private' ?'selected':''; ?>>Private</option>
                        <option value="other"   <?php echo $entity_type==='other'   ?'selected':''; ?>>Other</option>
                    </select>
                </div>
                <!-- Vehicle -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Vehicle</label>
                    <select name="vehicle_id" class="f-input">
                        <option value="">All Vehicles</option>
                        <?php foreach ($vehicles_list as $id => $num): ?>
                        <option value="<?php echo $id; ?>" <?php echo $vehicle_id==$id?'selected':''; ?>><?php echo htmlspecialchars($num); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Collector -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Collector</label>
                    <select name="collector_id" class="f-input">
                        <option value="">All Collectors</option>
                        <?php foreach ($collectors as $id => $name): ?>
                        <option value="<?php echo $id; ?>" <?php echo $collector_id==$id?'selected':''; ?>><?php echo htmlspecialchars($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Project -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Project</label>
                    <select name="project_id" class="f-input">
                        <option value="">All Projects</option>
                        <?php foreach ($projects as $id => $name): ?>
                        <option value="<?php echo $id; ?>" <?php echo $project_id==$id?'selected':''; ?>><?php echo htmlspecialchars($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Status -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Status</label>
                    <select name="status" class="f-input">
                        <option value="">All Status</option>
                        <option value="pending_unloading" <?php echo $status==='pending_unloading'?'selected':''; ?>>Pending</option>
                        <option value="completed"         <?php echo $status==='completed'        ?'selected':''; ?>>Completed</option>
                    </select>
                </div>
                <!-- Date From -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Date From</label>
                    <?php echo nepali_date_picker('date_from', $date_from, '', 'f-input', false); ?>
                </div>
                <!-- Date To -->
                <div class="col-6 col-md-3 col-lg-2">
                    <label class="filter-label">Date To</label>
                    <?php echo nepali_date_picker('date_to', $date_to, '', 'f-input', false); ?>
                </div>
                <!-- Buttons -->
                <div class="col-12 col-md-auto d-flex align-items-end gap-2">
                    <button type="submit" class="btn-search"><i class="fas fa-search me-1"></i>Search</button>
                    <?php if ($hasFilters): ?>
                    <a href="index.php" class="btn-clear"><i class="fas fa-times"></i></a>
                    <?php endif; ?>
                </div>
            </div>
        </form>

        <?php if ($hasFilters): ?>
        <div class="filter-chips">
            <?php if ($entity_type): ?><span class="chip"><?php echo ucfirst($entity_type); ?></span><?php endif; ?>
            <?php if ($vehicle_id && isset($vehicles_list[$vehicle_id])): ?><span class="chip"><?php echo htmlspecialchars($vehicles_list[$vehicle_id]); ?></span><?php endif; ?>
            <?php if ($collector_id && isset($collectors[$collector_id])): ?><span class="chip"><?php echo htmlspecialchars($collectors[$collector_id]); ?></span><?php endif; ?>
            <?php if ($project_id && isset($projects[$project_id])): ?><span class="chip green"><?php echo htmlspecialchars($projects[$project_id]); ?></span><?php endif; ?>
            <?php if ($status): ?><span class="chip orange"><?php echo $status==='pending_unloading'?'Pending':'Completed'; ?></span><?php endif; ?>
            <?php if ($search): ?><span class="chip">"<?php echo htmlspecialchars($search); ?>"</span><?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── TRIP TABS ── -->
<div class="trip-tabs">
    <?php
    $baseUrl     = "index.php?" . http_build_query(array_diff_key($_GET, ['trip_no' => '']));
    $displayMax  = max(3, $maxTripCount);
    $tabDefs     = ['' => ['All', 'fas fa-list-ul']];
    for ($i = 1; $i <= $displayMax; $i++) {
        $sfx = $i==1?'st':($i==2?'nd':($i==3?'rd':'th'));
        $ico = ['fas fa-dice-one','fas fa-dice-two','fas fa-dice-three','fas fa-dice-four','fas fa-dice-five','fas fa-dice-six'][$i-1] ?? 'fas fa-dice';
        $tabDefs[$i] = [$i.$sfx, $ico];
    }
    foreach ($tabDefs as $key => [$label, $icon]):
        $active = ($trip_no === (string)$key);
        $url    = $baseUrl . ($key !== '' ? "&trip_no=$key" : "");
    ?>
    <a href="<?php echo $url; ?>" class="trip-tab <?php echo $active?'active':''; ?>">
        <i class="<?php echo $icon; ?> me-1"></i><?php echo $label; ?>
    </a>
    <?php endforeach; ?>
</div>

<!-- ── SUMMARY BAR ── -->
<div class="summary-bar">
    <div class="s-stat">
        <div>
            <div class="s-num"><?php echo count($records); ?></div>
            <div class="s-lbl">Total Trips</div>
        </div>
    </div>
    <div class="s-stat">
        <div>
            <div class="s-num text-success"><?php echo $totalCompleted; ?></div>
            <div class="s-lbl">Completed</div>
        </div>
    </div>
    <div class="s-stat">
        <div>
            <div class="s-num text-warning"><?php echo $totalPending; ?></div>
            <div class="s-lbl">Pending</div>
        </div>
    </div>
    <div class="s-stat ms-auto">
        <div>
            <div class="s-num"><?php echo number_format($totalKm, 1); ?> KM</div>
            <div class="s-lbl">Total Distance</div>
        </div>
    </div>
</div>

<!-- ── RECORDS ── -->
<div class="records-wrap">
<?php if (empty($records)): ?>
    <div class="empty-state">
        <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
        <h5 class="fw-bold text-muted">No Records Found</h5>
        <p class="text-muted small mb-0">Adjust filters or add a new loading entry.</p>
    </div>
<?php else: ?>
<?php foreach ($records as $i => $r):
    $seq   = $r['trip_sequence'];
    $sfx   = $seq==1?'st':($seq==2?'nd':($seq==3?'rd':'th'));
    $et    = $r['entity_type_val'] ?? '';
    $dotCl = $et==='kmc'?'dot-kmc':($et==='private'?'dot-private':'dot-other');

    $kmDiff  = $r['unloading_end_odometer'] - $r['loading_start_odometer'];
    $meterNA = ($r['loading_start_odometer'] <= 1 && $r['unloading_end_odometer'] <= 1);
    if ($meterNA)       { $kmHtml = '<span class="km-badge km-na">Meter N/A</span>'; }
    elseif ($kmDiff > 0){ $kmHtml = '<span class="km-badge km-ok">'.number_format($kmDiff,1).' KM</span>'; }
    else                { $kmHtml = '<span class="km-badge km-err"><i class="fas fa-exclamation-triangle"></i> Error</span>'; }

    $statusHtml = match($r['status']) {
        'pending_unloading' => '<span class="status-pill pill-pending"><i class="fas fa-clock"></i> Pending</span>',
        'completed'         => '<span class="status-pill pill-completed"><i class="fas fa-check-circle"></i> Done</span>',
        default             => '<span class="status-pill pill-cancelled"><i class="fas fa-ban"></i> Cancelled</span>',
    };
?>
<div class="rec-card position-relative" style="animation:fadeUp .4s ease both;animation-delay:<?php echo min($i*0.04,.4); ?>s">
    <div class="rec-accent"></div>

    <!-- DESKTOP ROW -->
    <div class="rec-grid">
        <!-- Date & Entity -->
        <div>
            <div class="fld-lbl">Date</div>
            <div class="fld-val"><?php echo date_to_nepali($r['created_date']); ?></div>
            <div class="fld-sub">
                <span class="entity-dot <?php echo $dotCl; ?>"></span>
                <?php echo htmlspecialchars($r['deployed_name'] ?? '-'); ?>
            </div>
        </div>
        <!-- Vehicle -->
        <div>
            <div class="fld-lbl">Vehicle · Trip</div>
            <div class="fld-val"><?php echo htmlspecialchars($r['vehicle_number'] ?? '-'); ?></div>
            <div class="fld-sub">
                <span style="background:var(--c-grad);color:#fff;border-radius:6px;padding:1px 7px;font-size:.7rem;font-weight:700;"><?php echo $seq.$sfx; ?></span>
                &nbsp;<?php echo htmlspecialchars($r['driver_name'] ?? '-'); ?>
            </div>
        </div>
        <!-- Loading -->
        <div>
            <div class="fld-lbl">Loading</div>
            <span class="loc-badge loc-load"><i class="fas fa-truck-loading"></i> <?php echo htmlspecialchars($r['loading_location'] ?? '-'); ?></span>
            <div class="fld-sub mt-1">
                <i class="far fa-clock me-1"></i><?php echo $r['loading_time'] ? date('h:i A', strtotime($r['loading_time'])) : '-'; ?>
                &nbsp;·&nbsp;<?php echo number_format($r['loading_start_odometer'],1); ?> KM
            </div>
        </div>
        <!-- Unloading -->
        <div>
            <div class="fld-lbl">Unloading</div>
            <?php if ($r['unloading_place']): ?>
            <span class="loc-badge loc-unload"><i class="fas fa-truck"></i> <?php echo htmlspecialchars($r['unloading_place']); ?></span>
            <div class="fld-sub mt-1">
                <i class="far fa-clock me-1"></i><?php echo date('h:i A', strtotime($r['unloading_time'])); ?>
                &nbsp;·&nbsp;<?php echo number_format($r['unloading_end_odometer'],1); ?> KM
            </div>
            <?php else: ?>
            <div class="fld-sub" style="color:#d97706;font-weight:600;"><i class="fas fa-spinner fa-spin me-1"></i>Awaiting</div>
            <?php endif; ?>
            <?php echo $kmHtml; ?>
        </div>
        <!-- Status -->
        <div><?php echo $statusHtml; ?></div>
        <!-- Actions -->
        <div class="act-btns">
            <a href="view.php?id=<?php echo $r['id']; ?>" class="act-btn view" title="View"><i class="fas fa-eye"></i></a>
            <a href="edit.php?id=<?php echo $r['id']; ?>" class="act-btn edit" title="Edit"><i class="fas fa-pen"></i></a>
            <?php if ($r['status']==='pending_unloading' && (hasRole('admin')||hasAccess('tripper_unloading_only')||hasAccess('all_modules'))): ?>
            <a href="add_unloading.php?id=<?php echo $r['id']; ?>" class="act-btn comp" title="Complete"><i class="fas fa-check"></i></a>
            <?php endif; ?>
            <?php if (hasRole('admin') || ($user['can_delete']==1)): ?>
            <a href="index.php?delete=<?php echo $r['id']; ?>" class="act-btn del" title="Delete" onclick="return confirm('Delete this record?')"><i class="fas fa-trash"></i></a>
            <?php endif; ?>
        </div>
    </div>

    <!-- MOBILE CARD -->
    <div class="rec-mobile">
        <div class="rm-top">
            <div>
                <div class="rm-vehicle"><?php echo htmlspecialchars($r['vehicle_number'] ?? '-'); ?></div>
                <div class="rm-date">
                    <span class="entity-dot <?php echo $dotCl; ?>"></span>
                    <?php echo date_to_nepali($r['created_date']); ?> · <?php echo htmlspecialchars($r['driver_name'] ?? '-'); ?>
                </div>
            </div>
            <div class="d-flex flex-column align-items-end gap-1">
                <span class="rm-trip-badge"><?php echo $seq.$sfx; ?> Trip</span>
                <?php echo $statusHtml; ?>
            </div>
        </div>
        <div class="rm-mid">
            <div>
                <div class="fld-lbl">Loading</div>
                <div style="font-size:.82rem;font-weight:600;color:#059669;"><?php echo htmlspecialchars($r['loading_location'] ?? '-'); ?></div>
                <div class="fld-sub"><?php echo $r['loading_time'] ? date('h:i A', strtotime($r['loading_time'])) : '-'; ?></div>
            </div>
            <div>
                <div class="fld-lbl">Unloading</div>
                <?php if ($r['unloading_place']): ?>
                <div style="font-size:.82rem;font-weight:600;color:#2563eb;"><?php echo htmlspecialchars($r['unloading_place']); ?></div>
                <div class="fld-sub"><?php echo date('h:i A', strtotime($r['unloading_time'])); ?></div>
                <?php else: ?>
                <div class="fld-sub" style="color:#d97706;font-weight:600;">Awaiting</div>
                <?php endif; ?>
            </div>
        </div>
        <div class="rm-bot">
            <?php echo $kmHtml; ?>
            <div class="act-btns">
                <a href="view.php?id=<?php echo $r['id']; ?>" class="act-btn view"><i class="fas fa-eye"></i></a>
                <a href="edit.php?id=<?php echo $r['id']; ?>" class="act-btn edit"><i class="fas fa-pen"></i></a>
                <?php if ($r['status']==='pending_unloading' && (hasRole('admin')||hasAccess('tripper_unloading_only')||hasAccess('all_modules'))): ?>
                <a href="add_unloading.php?id=<?php echo $r['id']; ?>" class="act-btn comp"><i class="fas fa-check"></i></a>
                <?php endif; ?>
                <?php if (hasRole('admin') || ($user['can_delete']==1)): ?>
                <a href="index.php?delete=<?php echo $r['id']; ?>" class="act-btn del" onclick="return confirm('Delete?')"><i class="fas fa-trash"></i></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>

</div><!-- /container -->

<style>
@keyframes fadeUp { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }
</style>

<script>
function toggleFilter() {
    const panel   = document.getElementById('filterPanel');
    const chevron = document.getElementById('filterChevron');
    panel.classList.toggle('collapsed');
    chevron.style.transform = panel.classList.contains('collapsed') ? '' : 'rotate(180deg)';
}
</script>

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