<?php
// admin/calendar.php - Versioni i rregulluar
require_once '../includes/config.php';
if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

// ============================================
// PËRCAKTO MODIN E KALENDARIT
// ============================================
$calendar_mode = isset($_GET['mode']) ? $_GET['mode'] : 'today';
$month_offset = isset($_GET['month_offset']) ? (int)$_GET['month_offset'] : 0;

$today_date = date('Y-m-d');
$current_month = (int)date('m');
$current_year = (int)date('Y');

if($calendar_mode == 'month_start') {
    // Llogarit muajin e synuar bazuar në offset
    $target_month = $current_month + $month_offset;
    $target_year = $current_year;
    
    // Rregullo kur muaji kalon 12 ose bie nën 1
    while($target_month > 12) {
        $target_month -= 12;
        $target_year++;
    }
    while($target_month < 1) {
        $target_month += 12;
        $target_year--;
    }
    
    // TREGO VETËM MUAJIN E SYNUAR (jo muajin tjetër)
    $start_date = date('Y-m-d', strtotime("$target_year-$target_month-01"));
    $end_date = date('Y-m-d', strtotime("$target_year-$target_month-01 + 1 month - 1 day"));
    
    $selected_month = $target_month;
    $selected_year = $target_year;
} else {
    // TODAY VIEW: Dje + Sot + 31 ditët e ardhshme
    $start_date = date('Y-m-d', strtotime('-1 day'));
    $end_date = date('Y-m-d', strtotime('+31 days'));
    $selected_month = $current_month;
    $selected_year = $current_year;
}

// ============================================
// HANDLE AJAX REQUESTS
// ============================================
if(isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    
    if(isset($_GET['car_id']) && isset($_GET['date'])) {
        $car_id = (int)$_GET['car_id'];
        $date = $_GET['date'];
        
        $stmt = $pdo->prepare("
            SELECT r.*, c.brand, c.model 
            FROM reservations r 
            LEFT JOIN cars c ON r.car_id = c.id 
            WHERE r.car_id = ? 
            AND r.status != 'cancelled'
            AND r.pickup_date <= ? 
            AND r.dropoff_date >= ?
            ORDER BY r.pickup_date
        ");
        $stmt->execute([$car_id, $date, $date]);
        $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['reservations' => $reservations]);
        exit;
    }
    
    if(isset($_GET['get_car'])) {
        $car_id = (int)$_GET['get_car'];
        
        $stmt = $pdo->prepare("SELECT id, brand, model, license_plate FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $car = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($car) {
            echo json_encode(['id' => $car['id'], 'brand' => $car['brand'], 'model' => $car['model'], 'license_plate' => $car['license_plate']]);
        } else {
            echo json_encode(['error' => 'Car not found', 'brand' => 'Unknown', 'model' => '', 'license_plate' => '']);
        }
        exit;
    }
    
    echo json_encode(['error' => 'Invalid AJAX request']);
    exit;
}

// Generate all dates in range
$dates = [];
$current = new DateTime($start_date);
$end = new DateTime($end_date);
while($current <= $end) {
    $dates[] = [
        'date' => $current->format('Y-m-d'),
        'day' => $current->format('j'),
        'month' => $current->format('M'),
        'day_name' => $current->format('D'),
        'is_today' => ($current->format('Y-m-d') == date('Y-m-d')),
        'is_yesterday' => ($current->format('Y-m-d') == date('Y-m-d', strtotime('-1 day'))),
        'is_past' => ($current->format('Y-m-d') < date('Y-m-d'))
    ];
    $current->modify('+1 day');
}

// ============================================
// PAGINATION & SORTING FOR CARS
// ============================================
$cars_per_page = isset($_GET['cars_per_page']) ? (int)$_GET['cars_per_page'] : 25;
$cars_page = isset($_GET['cars_page']) ? max(1, (int)$_GET['cars_page']) : 1;
$sort_by = isset($_GET['sort_by']) ? $_GET['sort_by'] : 'brand';

// Get all cars first (for sorting)
$all_cars = $pdo->query("SELECT id, brand, model, license_plate FROM cars ORDER BY brand")->fetchAll();

$today = date('Y-m-d');

// Calculate availability for today (for sorting "available_today")
$booked_today_ids = [];
$stmt = $pdo->prepare("
    SELECT DISTINCT car_id 
    FROM reservations 
    WHERE status NOT IN ('cancelled', 'completed')
    AND pickup_date <= ? AND dropoff_date >= ?
");
$stmt->execute([$today, $today]);
while($row = $stmt->fetch()) {
    $booked_today_ids[] = $row['car_id'];
}

// Sort cars based on selection
if($sort_by == 'available_today') {
    usort($all_cars, function($a, $b) use ($booked_today_ids) {
        $a_avail = !in_array($a['id'], $booked_today_ids);
        $b_avail = !in_array($b['id'], $booked_today_ids);
        if($a_avail && !$b_avail) return -1;
        if(!$a_avail && $b_avail) return 1;
        return strcmp($a['brand'], $b['brand']);
    });
} elseif($sort_by == 'brand_desc') {
    usort($all_cars, function($a, $b) {
        return strcmp($b['brand'], $a['brand']);
    });
}

// Apply pagination
$total_cars = count($all_cars);
$total_cars_pages = ($cars_per_page == 999999) ? 1 : ceil($total_cars / $cars_per_page);
$offset = ($cars_page - 1) * $cars_per_page;
$cars = ($cars_per_page == 999999) ? $all_cars : array_slice($all_cars, $offset, $cars_per_page);

// Get reservations for date range (only for displayed cars)
$car_ids = array_column($cars, 'id');
$reservations = [];
if(!empty($car_ids)) {
    $placeholders = implode(',', array_fill(0, count($car_ids), '?'));
    $stmt = $pdo->prepare("
        SELECT car_id, pickup_date, dropoff_date, pickup_time, dropoff_time, 
               status, id, customer_name, customer_phone, reservation_code, total_price
        FROM reservations 
        WHERE status != 'cancelled'
        AND car_id IN ($placeholders)
        AND pickup_date <= ? AND dropoff_date >= ?
        ORDER BY car_id, pickup_date
    ");
    $params = array_merge($car_ids, [$end_date, $start_date]);
    $stmt->execute($params);
    $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

list($fully_booked, $pickup_days, $dropoff_days) = buildCalendarAvailability($cars, $reservations, $start_date, $end_date);

// ============================================
// NDERTO PILLS PER KALENDARIN (vetem per vete grid-in, pjesa tjeter e faqes e pa-prekur)
// ============================================
$date_index = [];
foreach($dates as $i => $d) { $date_index[$d['date']] = $i; }

$car_row_index = [];
foreach($cars as $i => $c) { $car_row_index[$c['id']] = $i; }

$pills = [];
$occupied = []; // [car_id][date] = true -> kjo dite eshte e zene nga nje rezervim, mos lejo klikim "krijo rezervim"
$return_time_map = []; // [car_id][date] = ora e return-it (dropoff_time) - per +2 ore ne rezervimin e ri
foreach($reservations as $r) {
    if(!isset($car_row_index[$r['car_id']])) continue;

    // shenjo te zena vetem ditet nga pickup deri NJE DITE PARA dropoff
    // (dita e dropoff-it makina kthehet dhe mund te rezervohet perseri ate dite)
    $last_occ_day = ($r['pickup_date'] == $r['dropoff_date'])
        ? $r['dropoff_date']
        : date('Y-m-d', strtotime($r['dropoff_date'] . ' -1 day'));

    $d_cursor = max($r['pickup_date'], $start_date);
    $d_limit = min($last_occ_day, $end_date);
    while($d_cursor <= $d_limit) {
        $occupied[$r['car_id']][$d_cursor] = true;
        $d_cursor = date('Y-m-d', strtotime($d_cursor . ' +1 day'));
    }

    // Shenjo oren e return-it per diten e dropoff-it (qe te mund te bejme +2 ore kur klikohet '+' aty)
    if($r['dropoff_date'] >= $start_date && $r['dropoff_date'] <= $end_date) {
        $return_time_map[$r['car_id']][$r['dropoff_date']] = substr($r['dropoff_time'], 0, 5);
    }

    $res_start = max($r['pickup_date'], $start_date);
    $res_end = min($r['dropoff_date'], $end_date);
    if(!isset($date_index[$res_start]) || !isset($date_index[$res_end])) continue;

    $col_start = $date_index[$res_start];
    $col_end = $date_index[$res_end];
    $span = max(1, $col_end - $col_start + 1);

    $pills[] = [
        'row' => $car_row_index[$r['car_id']],
        'col_start' => $col_start,
        'span' => $span,
        'class' => 'pill-' . ($r['status'] ?: 'pending'),
        'clip_start' => ($r['pickup_date'] < $start_date),
        'clip_end' => ($r['dropoff_date'] > $end_date),
        'half_start' => ($r['pickup_date'] >= $start_date && $span > 1),
        'half_end' => ($r['dropoff_date'] <= $end_date && $span > 1),
        'data' => [
            'code' => $r['reservation_code'],
            'name' => $r['customer_name'],
            'phone' => $r['customer_phone'] ?? '',
            'status' => $r['status'],
            'pickup_date' => $r['pickup_date'],
            'pickup_time' => substr($r['pickup_time'], 0, 5),
            'dropoff_date' => $r['dropoff_date'],
            'dropoff_time' => substr($r['dropoff_time'], 0, 5),
            'total_price' => $r['total_price'] ?? null
        ]
    ];
}

// ============================================
// FUNKSIONET PËR URL-TE E NAVIGIMIT
// ============================================

function getPrevUrl($calendar_mode, $month_offset) {
    if($calendar_mode == 'today') {
        // Nga Today View, Prev shkon te muaji aktual (Qershor)
        return '?mode=month_start&month_offset=0';
    } else {
        // Në month_start mode, zvogëlo offset-in për të shkuar muajin e kaluar
        $new_offset = $month_offset - 1;
        return '?mode=month_start&month_offset=' . $new_offset;
    }
}

function getNextUrl($calendar_mode, $month_offset) {
    if($calendar_mode == 'today') {
        // Nga Today View, Next shkon te muaji tjetër (Korrik)
        return '?mode=month_start&month_offset=1';
    } else {
        // Në month_start mode, rrit offset-in për të shkuar muajin tjetër
        $new_offset = $month_offset + 1;
        return '?mode=month_start&month_offset=' . $new_offset;
    }
}

function getTodayUrl() {
    return 'calendar.php';
}

// Shto parametrat shtesë në URL
function addQueryParams($url) {
    $params = [];
    if(isset($_GET['cars_per_page'])) $params[] = 'cars_per_page=' . (int)$_GET['cars_per_page'];
    if(isset($_GET['sort_by'])) $params[] = 'sort_by=' . urlencode($_GET['sort_by']);
    if(isset($_GET['cars_page'])) $params[] = 'cars_page=' . (int)$_GET['cars_page'];
    
    if(!empty($params)) {
        $url .= (strpos($url, '?') === false ? '?' : '&') . implode('&', $params);
    }
    return $url;
}

// Për të marrë emrin e muajit për display
function getDisplayMonth($start_date, $calendar_mode, $month_offset) {
    if($calendar_mode == 'today') {
        return 'Today View (Yesterday → Today → Next 31 Days)';
    } else {
        $target_date = new DateTime();
        $target_date->modify('first day of this month');
        if($month_offset != 0) {
            $target_date->modify($month_offset . ' months');
        }
        return $target_date->format('F Y');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Availability Calendar - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            z-index: 100;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; min-height: 100vh; display: flex; flex-direction: column; box-sizing: border-box; }
        .page-header { margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        .page-header h1 i { color: #0066cc; margin-right: 10px; }
        
        .month-display {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            padding: 12px 24px;
            margin-bottom: 20px;
            text-align: center;
        }
        .month-display h2 {
            font-size: 20px;
            font-weight: 600;
            color: #1e293b;
        }
        .month-display p {
            font-size: 12px;
            color: #6b7280;
            margin-top: 4px;
        }
        
        .top-controls {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            padding: 12px 20px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }
        .nav-buttons {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }
        .nav-current-label {
            margin-left: 8px;
            font-size: 12.5px;
            font-weight: 700;
            color: #1e293b;
            padding: 8px 12px;
            background: #eef2f7;
            border-radius: 8px;
            white-space: nowrap;
        }
        .nav-btn {
            background: #f3f4f6;
            border: 1px solid #e5e7eb;
            padding: 8px 14px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s;
            text-decoration: none;
            color: #374151;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        .nav-btn:hover { background: #e5e7eb; }
        .today-btn { background: #0066cc; color: white; border-color: #0066cc; }
        .today-btn:hover { background: #0052a3; }
        
        .filter-group {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #f8fafc;
            padding: 4px 12px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        .filter-group label {
            font-size: 12px;
            font-weight: 500;
            color: #374151;
        }
        .filter-group select {
            padding: 6px 10px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 13px;
            background: white;
            cursor: pointer;
        }
        .filter-group .cars-info {
            font-size: 12px;
            color: #6b7280;
            margin-left: 8px;
            padding-left: 8px;
            border-left: 1px solid #e5e7eb;
        }
        
        .cars-pagination {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .cars-pagination a, .cars-pagination span {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 32px;
            padding: 4px 10px;
            background: #f3f4f6;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            text-decoration: none;
            color: #374151;
            font-size: 12px;
            transition: all 0.2s;
        }
        .cars-pagination a:hover {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .cars-pagination .active {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .cars-pagination .disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .search-box {
            display: flex;
            gap: 6px;
            align-items: center;
        }
        .search-box input { 
            padding: 6px 12px; 
            border: 1px solid #d1d5db; 
            border-radius: 6px; 
            width: 180px;
            font-size: 13px;
        }
        .search-box button { 
            padding: 6px 12px; 
            background: #0066cc; 
            color: white; 
            border: none; 
            border-radius: 6px; 
            cursor: pointer;
            font-size: 12px;
        }
        
        .calendar-container {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow-x: auto;
            overflow-y: auto;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            flex: 1 1 auto;
            min-height: calc(100vh - 320px);
            display: flex;
            flex-direction: column;
        }
        .calendar-container > div { width: 100%; }
        
        .cal-grid {
            display: grid;
            grid-template-rows: 44px;
            grid-auto-rows: 36px;
            min-width: max-content;
            position: relative;
            /* korniza e jashtme e dukshme rreth gjithe rrjetit */
            border-top: 1px solid #cbd5e1;
            border-left: 1px solid #cbd5e1;
        }
        
        .cal-head-label, .cal-head-date {
            background: #eef2f7;
            border-bottom: 2px solid #94a3b8;
            border-right: 1px solid #cbd5e1;
            padding: 4px 2px;
            text-align: center;
            font-weight: 700;
            font-size: 10px;
            color: #1e293b;
            position: sticky;
            top: 0;
            z-index: 20;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            line-height: 1.15;
        }
        .cal-head-label { left: 0; z-index: 25; align-items: center; justify-content: center; text-align: center; font-size: 12px; flex-direction: row; }
        .cal-head-date.is-weekend { background: #e2e8f0; }
        .cal-head-date.is-today { background: #0066cc; border-bottom-color: #0066cc; }
        .cal-head-date.is-today .d-num, .cal-head-date.is-today .d-name { color: #fff; }
        .cal-head-date .d-num { font-weight: 700; font-size: 12px; }
        .cal-head-date .d-name { font-size: 8px; color: #64748b; margin-top: 1px; }
        
        .cal-row-label {
            background: #f8fafc;
            border-bottom: 1px solid #cbd5e1;
            border-right: 2px solid #94a3b8;
            position: sticky;
            left: 0;
            z-index: 23;
            display: flex;
            align-items: center;
            padding: 0 12px;
            font-size: 12px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .cal-row-label.alt { background: #eef2f7; }
        .cal-row-label:hover { background: #dbeafe; }
        .cal-row-label .plate-tag { margin-left: 6px; font-size: 9px; font-weight: 700; color: #64748b; background: #e2e8f0; padding: 1px 5px; border-radius: 4px; }
        
        /* QELIZAT - korniza GJITHMONE te dukshme, asnjehere "bosh" */
        .cal-day {
            border-bottom: 1px solid #cbd5e1;
            border-right: 1px solid #cbd5e1;
            background: #ffffff;
            cursor: pointer;
            transition: background 0.12s;
            position: relative;
        }
        .cal-day.alt { background: #f8fafc; }
        .cal-day.is-weekend { background: #f1f5f9; }
        .cal-day.alt.is-weekend { background: #eaeff5; }
        .cal-day:hover { background: #dbeafe; }
        
        .cal-day.is-occupied { cursor: default; }
        .cal-day.is-occupied:hover { background: inherit; }
        
        /* DITET E KALUARA - te dukshme qarte me vija diagonale, JO bosh */
        .cal-day.is-past {
            background-color: #e2e8f0;
            background-image: repeating-linear-gradient(135deg, #cbd5e1 0, #cbd5e1 1px, transparent 1px, transparent 7px);
            cursor: default;
        }
        .cal-day.is-past:hover { background-color: #e2e8f0; }
        
        .cal-day.is-today-col { box-shadow: inset 2px 0 0 #0066cc, inset -2px 0 0 #0066cc; }
        
        .cal-plus {
            position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
            color: #0066cc; font-size: 11px; opacity: 0; transition: opacity 0.12s;
        }
        .cal-day:hover .cal-plus { opacity: 1; }
        

        /* PILLS - rezervimet qe shtrihen permbi qelizat */
        .cal-pill {
            position: relative;
            margin: 4px 3px;
            height: 28px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 0 9px;
            font-size: 10.5px;
            font-weight: 700;
            color: #fff;
            cursor: pointer;
            overflow: hidden;
            white-space: nowrap;
            z-index: 18;
            box-shadow: 0 1px 2px rgba(0,0,0,0.2);
            border: 1px solid rgba(0,0,0,0.08);
            transition: transform 0.12s, box-shadow 0.12s;
        }
        .cal-pill:hover { transform: translateY(-1px); box-shadow: 0 4px 10px rgba(0,0,0,0.25); z-index: 22; }
        .cal-pill .p-tag { font-size: 8px; font-weight: 800; background: rgba(255,255,255,0.3); padding: 1px 4px; border-radius: 4px; flex-shrink: 0; }
        .cal-pill .p-txt { overflow: hidden; text-overflow: ellipsis; }
        
        .cal-pill.half-start { 
            margin-left: 19px; 
            clip-path: polygon(9px 0, 100% 0, 100% 100%, 0 100%);
        }
        .cal-pill.half-end { 
            margin-right: 19px; 
            clip-path: polygon(0 0, 100% 0, calc(100% - 9px) 100%, 0 100%);
        }
        .cal-pill.half-start.half-end {
            clip-path: polygon(9px 0, 100% 0, calc(100% - 9px) 100%, 0 100%);
        }
        .cal-pill.clip-start { border-radius: 0 8px 8px 0; margin-left: 0; clip-path: none; }
        .cal-pill.clip-end { border-radius: 8px 0 0 8px; margin-right: 0; clip-path: none; }
        .cal-pill.clip-start.clip-end { border-radius: 0; clip-path: none; }
        
        .pill-pending { background: #f59e0b; }
        .pill-confirmed { background: #10b981; }
        .pill-running { background: #0066cc; }
        .pill-completed { background: #7c3aed; }
        
        .cal-empty {
            padding: 60px 20px; text-align: center; color: #64748b;
        }
        .cal-empty i { font-size: 44px; color: #cbd5e1; display: block; margin-bottom: 14px; }
        
        .legend {
            display: flex;
            gap: 20px;
            margin-top: 20px;
            padding: 10px 16px;
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            flex-wrap: wrap;
        }
        .legend-item { display: flex; align-items: center; gap: 6px; font-size: 10px; }
        .legend-color { width: 16px; height: 16px; border-radius: 4px; }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(4px);
        }
        .modal-content {
            background: white;
            border-radius: 20px;
            width: 550px;
            max-width: 90%;
            max-height: 85vh;
            overflow: hidden;
            animation: modalSlideIn 0.3s ease;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }
        @keyframes modalSlideIn {
            from { opacity: 0; transform: translateY(-30px) scale(0.95); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .modal-header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: white;
            padding: 20px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .modal-header h3 { font-size: 18px; font-weight: 600; margin: 0; }
        .modal-header h3 i { margin-right: 10px; }
        .modal-header .close-modal { font-size: 28px; cursor: pointer; color: rgba(255,255,255,0.7); transition: color 0.2s; }
        .modal-header .close-modal:hover { color: white; }
        .modal-body { padding: 24px; max-height: 60vh; overflow-y: auto; }
        .modal-footer { padding: 16px 24px; border-top: 1px solid #e2e8f0; background: #f8fafc; display: flex; justify-content: flex-end; gap: 12px; }
        
        .reservation-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
            border-left: 4px solid #0066cc;
            transition: all 0.2s;
        }
        .reservation-card:hover { background: #f1f5f9; }
        .reservation-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; flex-wrap: wrap; gap: 8px; }
        .reservation-code { font-family: monospace; font-weight: bold; background: #e2e8f0; padding: 4px 10px; border-radius: 20px; font-size: 12px; color: #1e293b; }
        .reservation-status { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .status-pending-badge { background: #fef3c7; color: #92400e; }
        .status-confirmed-badge { background: #dcfce7; color: #166534; }
        .status-cancelled-badge { background: #fee2e2; color: #991b1b; }
        .status-completed-badge { background: #e0e7ff; color: #3730a3; }
        
        .reservation-detail-row {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 8px 0;
            font-size: 13px;
            border-bottom: 1px solid #e2e8f0;
        }
        .reservation-detail-row:last-child { border-bottom: none; }
        .reservation-detail-row i { width: 20px; color: #0066cc; }
        
        .empty-state { text-align: center; padding: 40px; color: #64748b; }
        .empty-state i { font-size: 48px; margin-bottom: 16px; color: #cbd5e1; }
        
        .free-slot-info {
            background: #dcfce7;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
        }
        .free-slot-info i { font-size: 48px; color: #10b981; margin-bottom: 12px; }
        .free-slot-info h4 { font-size: 18px; color: #166534; margin-bottom: 8px; }
        
        .btn-primary {
            background: #0066cc;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background 0.2s;
        }
        .btn-primary:hover { background: #0052a3; }
        .btn-secondary {
            background: #e2e8f0;
            color: #1e293b;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s;
        }
        .btn-secondary:hover { background: #cbd5e1; }
        
        .car-toast {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: #1f2937;
            color: white;
            padding: 12px 24px;
            border-radius: 50px;
            font-size: 14px;
            z-index: 1000;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            animation: toastFadeInOut 2.5s ease forwards;
            white-space: nowrap;
        }
        
        @keyframes toastFadeInOut {
            0% { opacity: 0; transform: translateX(-50%) translateY(20px); }
            15% { opacity: 1; transform: translateX(-50%) translateY(0); }
            85% { opacity: 1; transform: translateX(-50%) translateY(0); }
            100% { opacity: 0; transform: translateX(-50%) translateY(-20px); }
        }
        
        .performance-note {
            font-size: 11px;
            color: #6b7280;
            text-align: center;
            margin-top: 12px;
        }
        
        @media (max-width: 900px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .top-controls { flex-direction: column; align-items: stretch; }
            .nav-buttons { justify-content: center; }
            .filter-group { justify-content: space-between; }
            .cars-pagination { justify-content: center; }
            .search-box { justify-content: center; }
            .car-toast { white-space: normal; text-align: center; max-width: 90%; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php" class="active"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-calendar-alt"></i> Availability Calendar</h1>
            <button class="btn-secondary" onclick="window.location.reload()"><i class="fas fa-sync-alt"></i> Refresh</button>
        </div>
        
        <!-- ALL CONTROLS IN ONE LINE -->
        <div class="top-controls">
            <!-- Month Navigation -->
            <div class="nav-buttons">
                <a href="<?php echo addQueryParams(getPrevUrl($calendar_mode, $month_offset)); ?>" class="nav-btn">
                    <i class="fas fa-chevron-left"></i> Prev
                </a>
                <a href="<?php echo addQueryParams(getTodayUrl()); ?>" class="nav-btn today-btn">
                    <i class="fas fa-calendar-day"></i> Today View
                </a>
                <a href="<?php echo addQueryParams(getNextUrl($calendar_mode, $month_offset)); ?>" class="nav-btn">
                    Next <i class="fas fa-chevron-right"></i>
                </a>
                <span class="nav-current-label">
                    <?php echo $calendar_mode == 'today' 
                        ? date('d M', strtotime($start_date)) . ' – ' . date('d M Y', strtotime($end_date)) 
                        : getDisplayMonth($start_date, $calendar_mode, $month_offset); ?>
                </span>
            </div>
            
            <!-- Sort & Per Page -->
            <div class="filter-group">
                <label><i class="fas fa-sort"></i> Sort:</label>
                <select id="sortBySelect" onchange="applyFilters()">
                    <option value="brand" <?php echo $sort_by == 'brand' ? 'selected' : ''; ?>>Brand (A-Z)</option>
                    <option value="brand_desc" <?php echo $sort_by == 'brand_desc' ? 'selected' : ''; ?>>Brand (Z-A)</option>
                    <option value="available_today" <?php echo $sort_by == 'available_today' ? 'selected' : ''; ?>>Available Today First</option>
                </select>
                
                <label style="margin-left: 12px;"><i class="fas fa-eye"></i> Show:</label>
                <select id="carsPerPageSelect" onchange="applyFilters()">
                    <option value="15" <?php echo $cars_per_page == 15 ? 'selected' : ''; ?>>15</option>
                    <option value="25" <?php echo $cars_per_page == 25 ? 'selected' : ''; ?>>25</option>
                    <option value="50" <?php echo $cars_per_page == 50 ? 'selected' : ''; ?>>50</option>
                    <option value="100" <?php echo $cars_per_page == 100 ? 'selected' : ''; ?>>100</option>
                    <option value="999999" <?php echo $cars_per_page == 999999 ? 'selected' : ''; ?>>All</option>
                </select>
                
                <span class="cars-info"><i class="fas fa-car"></i> <?php echo count($cars); ?>/<?php echo $total_cars; ?></span>
            </div>
            
            <!-- Car Pagination -->
            <?php if($total_cars_pages > 1 && $cars_per_page != 999999): ?>
            <div class="cars-pagination">
                <?php if($cars_page > 1): ?>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['cars_page' => 1, 'cars_per_page' => $cars_per_page, 'sort_by' => $sort_by])); ?>">
                        <i class="fas fa-angle-double-left"></i>
                    </a>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['cars_page' => $cars_page - 1, 'cars_per_page' => $cars_per_page, 'sort_by' => $sort_by])); ?>">
                        <i class="fas fa-angle-left"></i>
                    </a>
                <?php else: ?>
                    <span class="disabled"><i class="fas fa-angle-double-left"></i></span>
                    <span class="disabled"><i class="fas fa-angle-left"></i></span>
                <?php endif; ?>
                
                <span class="active"><?php echo $cars_page; ?></span>
                
                <?php if($cars_page < $total_cars_pages): ?>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['cars_page' => $cars_page + 1, 'cars_per_page' => $cars_per_page, 'sort_by' => $sort_by])); ?>">
                        <i class="fas fa-angle-right"></i>
                    </a>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['cars_page' => $total_cars_pages, 'cars_per_page' => $cars_per_page, 'sort_by' => $sort_by])); ?>">
                        <i class="fas fa-angle-double-right"></i>
                    </a>
                <?php else: ?>
                    <span class="disabled"><i class="fas fa-angle-right"></i></span>
                    <span class="disabled"><i class="fas fa-angle-double-right"></i></span>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <!-- Search -->
            <div class="search-box">
                <input type="text" id="carSearch" placeholder="Search car..." onkeyup="filterCars()">
                <button onclick="filterCars()"><i class="fas fa-search"></i></button>
            </div>
        </div>
        
        <!-- Calendar Container -->
        <div class="calendar-container">
            <div style="position: relative;">
                <div class="cal-grid" id="calendarGrid" style="grid-template-columns: 170px repeat(<?php echo count($dates); ?>, 38px);">

                    <div class="cal-head-label" style="grid-row: 1; grid-column: 1;">Car / Date</div>
                    <?php foreach($dates as $i => $d): 
                        $is_weekend = in_array(date('N', strtotime($d['date'])), [6,7]);
                    ?>
                        <div class="cal-head-date <?php echo $d['is_today'] ? 'is-today' : ''; ?> <?php echo $is_weekend ? 'is-weekend' : ''; ?>" style="grid-row: 1; grid-column: <?php echo $i + 2; ?>;">
                            <div class="d-num"><?php echo $d['day']; ?></div>
                            <div class="d-name"><?php echo $d['month'] . ' ' . $d['day_name']; ?></div>
                        </div>
                    <?php endforeach; ?>

                    <?php foreach($cars as $r_idx => $car): 
                        $grid_row = $r_idx + 2;
                        $alt = ($r_idx % 2 == 1) ? 'alt' : '';
                    ?>
                        <div class="cal-row-label car-row <?php echo $alt; ?>"
                             data-car-name="<?php echo strtolower($car['brand'] . ' ' . $car['model'] . ' ' . $car['license_plate']); ?>"
                             data-row="<?php echo $grid_row; ?>"
                             style="grid-row: <?php echo $grid_row; ?>; grid-column: 1;"
                             onclick="showCarPlate('<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($car['license_plate'], ENT_QUOTES); ?>')">
                            <?php echo htmlspecialchars($car['brand'] . ' ' . $car['model']); ?>
                            <span class="plate-tag"><?php echo htmlspecialchars($car['license_plate']); ?></span>
                        </div>
                        <?php foreach($dates as $i => $d): 
                            $is_past = $d['is_past'];
                            $is_weekend = in_array(date('N', strtotime($d['date'])), [6,7]);
                            $is_occupied = isset($occupied[$car['id']][$d['date']]);
                            $is_clickable = !$is_past && !$is_occupied;
                            $return_time = $return_time_map[$car['id']][$d['date']] ?? '';
                        ?>
                        <div class="cal-day <?php echo $alt; ?> <?php echo $is_weekend ? 'is-weekend' : ''; ?> <?php echo $is_past ? 'is-past' : ''; ?> <?php echo $is_occupied ? 'is-occupied' : ''; ?> <?php echo $d['is_today'] ? 'is-today-col' : ''; ?>"
                             data-row="<?php echo $grid_row; ?>"
                             style="grid-row: <?php echo $grid_row; ?>; grid-column: <?php echo $i + 2; ?>;"
                             <?php if($is_clickable): ?>onclick="createReservationOnDate(<?php echo $car['id']; ?>, '<?php echo $d['date']; ?>', '<?php echo htmlspecialchars($return_time, ENT_QUOTES); ?>')"<?php endif; ?>
                             title="<?php echo $is_past ? 'Past date' : ($is_occupied ? 'Reserved' : ($return_time ? 'Free from ' . $return_time . ' (+2h) - click to create a reservation' : 'Free - click to create a reservation')); ?>">
                            <?php if($is_clickable): ?><div class="cal-plus"><i class="fas fa-plus"></i></div><?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php endforeach; ?>

                    <?php foreach($pills as $p): 
                        $cls = $p['class'];
                        $cls .= $p['clip_start'] ? ' clip-start' : '';
                        $cls .= $p['clip_end'] ? ' clip-end' : '';
                        $cls .= $p['half_start'] ? ' half-start' : '';
                        $cls .= $p['half_end'] ? ' half-end' : '';
                    ?>
                        <div class="cal-pill <?php echo $cls; ?>"
                             data-row="<?php echo $p['row'] + 2; ?>"
                             style="grid-row: <?php echo $p['row'] + 2; ?>; grid-column: <?php echo $p['col_start'] + 2; ?> / span <?php echo $p['span']; ?>;"
                             onclick='showReservationDetails(<?php echo htmlspecialchars(json_encode($p['data']), ENT_QUOTES); ?>)'
                             title="<?php echo htmlspecialchars($p['data']['code'] . ' - ' . $p['data']['name'] . ' | Pickup ' . $p['data']['pickup_time'] . ' -> Return ' . $p['data']['dropoff_time']); ?>">
                            <?php if($p['half_start']): ?><span class="p-tag"><?php echo htmlspecialchars($p['data']['pickup_time']); ?></span><?php endif; ?>
                            <span class="p-txt"><?php echo htmlspecialchars($p['data']['name']); ?> · <?php echo htmlspecialchars($p['data']['code']); ?></span>
                            <?php if($p['half_end']): ?><span class="p-tag"><?php echo htmlspecialchars($p['data']['dropoff_time']); ?></span><?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                    <?php if(count($cars) == 0): ?>
                        <div class="cal-empty" style="grid-row: 2; grid-column: 1 / -1;">
                            <i class="fas fa-car-side"></i>
                            No cars registered. <a href="cars.php" style="color: #0066cc;">Add your first car</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Legend -->
        <div class="legend">
            <div class="legend-item"><div class="legend-color" style="background: #f59e0b;"></div> Pending</div>
            <div class="legend-item"><div class="legend-color" style="background: #10b981;"></div> Confirmed</div>
            <div class="legend-item"><div class="legend-color" style="background: #0066cc;"></div> Running</div>
            <div class="legend-item"><div class="legend-color" style="background: #7c3aed;"></div> Completed</div>
            <div class="legend-item"><div class="legend-color" style="background: #fff; border: 1px solid #cbd5e1;"></div> Free</div>
            <div class="legend-item"><div class="legend-color" style="background: #e2e8f0; background-image: repeating-linear-gradient(135deg, #cbd5e1 0, #cbd5e1 1px, transparent 1px, transparent 5px);"></div> Past</div>
        </div>
    </div>
    
    <!-- Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-info-circle"></i> Date Details</h3>
                <span class="close-modal" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body" id="modalContent">
                <div style="text-align: center; padding: 20px;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 32px; color: #0066cc;"></i>
                    <p style="margin-top: 12px;">Loading reservation details...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeModal()">Close</button>
                <button class="btn-primary" id="createReservationBtn" style="display: none;" onclick="goToCreateReservation()">
                    <i class="fas fa-plus"></i> Create Reservation
                </button>
            </div>
        </div>
    </div>
    
    <script>
        function applyFilters() {
            const sortBy = document.getElementById('sortBySelect').value;
            const carsPerPage = document.getElementById('carsPerPageSelect').value;
            const url = new URL(window.location.href);
            url.searchParams.set('sort_by', sortBy);
            url.searchParams.set('cars_per_page', carsPerPage);
            url.searchParams.set('cars_page', 1);
            window.location.href = url.toString();
        }
        
        function showCarPlate(carName, carPlate) {
            const toast = document.createElement('div');
            toast.className = 'car-toast';
            toast.innerHTML = '<i class="fas fa-car"></i> ' + carName + ' - <strong>' + carPlate + '</strong>';
            document.body.appendChild(toast);
            setTimeout(() => { toast.remove(); }, 2500);
        }
        
        function escapeHtml(text) {
            if(!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function statusBadgeClass(status) {
            switch(status) {
                case 'pending': return 'status-pending-badge';
                case 'confirmed': return 'status-confirmed-badge';
                case 'cancelled': return 'status-cancelled-badge';
                case 'completed': return 'status-completed-badge';
                default: return 'status-pending-badge';
            }
        }
        
        function showReservationDetails(res) {
            const modalContent = document.getElementById('modalContent');
            document.getElementById('createReservationBtn').style.display = 'none';
            
            modalContent.innerHTML = `
                <div class="reservation-card" style="margin-bottom: 0;">
                    <div class="reservation-header">
                        <span class="reservation-code">${escapeHtml(res.code)}</span>
                        <span class="reservation-status ${statusBadgeClass(res.status)}">${escapeHtml(res.status)}</span>
                    </div>
                    <div class="reservation-detail-row"><i class="fas fa-user"></i><span>${escapeHtml(res.name)}</span></div>
                    <div class="reservation-detail-row"><i class="fas fa-phone"></i><span>${escapeHtml(res.phone)}</span></div>
                    <div class="reservation-detail-row"><i class="fas fa-calendar-plus"></i><span>Pickup: ${res.pickup_date} at ${res.pickup_time}</span></div>
                    <div class="reservation-detail-row"><i class="fas fa-calendar-minus"></i><span>Return: ${res.dropoff_date} at ${res.dropoff_time}</span></div>
                    ${res.total_price ? `<div class="reservation-detail-row"><i class="fas fa-money-bill-wave"></i><span>Total: €${parseFloat(res.total_price).toFixed(2)}</span></div>` : ''}
                    <div style="margin-top: 12px;">
                        <a href="reservations.php?search=${encodeURIComponent(res.code)}" class="btn-secondary" style="display: inline-block; padding: 6px 12px; font-size: 12px; text-decoration: none;">
                            <i class="fas fa-eye"></i> View Full Details
                        </a>
                    </div>
                </div>
            `;
            document.getElementById('detailsModal').style.display = 'flex';
        }
        
        let pendingCarId = null;
        let pendingDate = null;
        let pendingReturnTime = null;
        
        function createReservationOnDate(carId, date, returnTime) {
            pendingCarId = carId;
            pendingDate = date;
            pendingReturnTime = returnTime || null;
            
            let infoText = `This car is free on <strong>${date}</strong>. You can create a new reservation.`;
            if(pendingReturnTime) {
                const plus2 = addHoursToDateTime(date, pendingReturnTime, 2);
                infoText = `The previous rental returns at <strong>${pendingReturnTime}</strong>. To allow cleaning/prep time, the new pickup will start at <strong>${plus2.time}</strong>${plus2.date !== date ? ' on ' + plus2.date : ''} (return time + 2h).`;
            }
            
            document.getElementById('modalContent').innerHTML = `
                <div class="free-slot-info">
                    <i class="fas fa-check-circle"></i>
                    <h4>Available!</h4>
                    <p>${infoText}</p>
                </div>
            `;
            const btn = document.getElementById('createReservationBtn');
            btn.style.display = 'inline-block';
            btn.innerHTML = '<i class="fas fa-plus"></i> Create Reservation';
            document.getElementById('detailsModal').style.display = 'flex';
        }
        
        // Shton N ore mbi nje date+ore te dhena, dhe rrotullon daten nese kalon mesnaten
        function addHoursToDateTime(dateStr, timeStr, hoursToAdd) {
            const dt = new Date(dateStr + 'T' + timeStr + ':00');
            dt.setHours(dt.getHours() + hoursToAdd);
            const newDate = dt.toISOString().split('T')[0];
            const newTime = dt.toTimeString().substring(0, 5);
            return { date: newDate, time: newTime };
        }
        
        function goToCreateReservation() {
            if(pendingCarId && pendingDate) {
                let pickupDate = pendingDate;
                let pickupTime = '10:00';
                
                if(pendingReturnTime) {
                    const plus2 = addHoursToDateTime(pendingDate, pendingReturnTime, 2);
                    pickupDate = plus2.date;
                    pickupTime = plus2.time;
                }
                
                let dropoffDate = new Date(pickupDate);
                dropoffDate.setDate(dropoffDate.getDate() + 3);
                window.location.href = `create-reservation.php?car_id=${pendingCarId}&pickup_date=${pickupDate}&dropoff_date=${dropoffDate.toISOString().split('T')[0]}&pickup_time=${pickupTime}&dropoff_time=10:00`;
            } else {
                window.location.href = 'create-reservation.php';
            }
        }
        
        function closeModal() {
            document.getElementById('detailsModal').style.display = 'none';
        }
        
        function filterCars() {
            const searchTerm = document.getElementById('carSearch').value.toLowerCase();
            document.querySelectorAll('.cal-row-label').forEach(label => {
                const carName = label.getAttribute('data-car-name');
                const row = label.getAttribute('data-row');
                const match = !carName || carName.includes(searchTerm);
                label.style.display = match ? '' : 'none';
                document.querySelectorAll('.cal-day[data-row="' + row + '"]').forEach(c => c.style.display = match ? '' : 'none');
                document.querySelectorAll('.cal-pill[data-row="' + row + '"]').forEach(p => p.style.display = match ? '' : 'none');
            });
        }
        
        window.onclick = function(event) {
            if(event.target == document.getElementById('detailsModal')) {
                closeModal();
            }
        }
    </script>
</body>
</html>