<?php
// admin/cars.php - Versioni i plotë me grupe dhe kontroll rezervimesh
require_once '../includes/config.php';

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

// ============================================
// KONTROLLO ROLE - WORKER VETËM SHIKON
// ============================================
$user_role = $_SESSION['admin_role'] ?? 'admin';
$is_worker = ($user_role == 'worker');

$message = '';
$error = '';

// ============================================
// FUNKSIONI: Llogarit sa makina ka në një grup
// ============================================
function countCarsInGroup($group_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM cars WHERE group_id = ? OR (id = ? AND group_id IS NULL)");
        $stmt->execute([$group_id, $group_id]);
        return (int)$stmt->fetchColumn();
    } catch (PDOException $e) {
        return 0;
    }
}

// ============================================
// FUNKSIONI: KONTROLLO NËSE MAKINA PRIMARE KA KLONE
// ============================================
function hasClones($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM cars WHERE group_id = ?");
        $stmt->execute([$car_id]);
        return (int)$stmt->fetchColumn() > 0;
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// FUNKSIONI: KONTROLLO NËSE MAKINA ËSHTË E KLONUAR (BINJAKE)
// ============================================
function isClone($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT group_id FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $car = $stmt->fetch(PDO::FETCH_ASSOC);
        return ($car && $car['group_id'] !== null);
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// FUNKSIONI: KONTROLLO NËSE FIGURA PËRDORET NGA MAKINA TË TJERA
// ============================================
function isImageUsedByOtherCars($car_id, $image_url, $pdo) {
    if (empty($image_url)) {
        return false;
    }
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM cars WHERE image_url = ? AND id != ?");
        $stmt->execute([$image_url, $car_id]);
        return (int)$stmt->fetchColumn() > 0;
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// FUNKSIONI: Kontrollo nëse makina ka rezervime aktive ose të ardhshme
// ============================================
function hasActiveOrFutureReservations($car_id, $pdo) {
    try {
        $today = date('Y-m-d');
        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM reservations 
            WHERE car_id = ? 
            AND status NOT IN ('cancelled', 'completed')
            AND pickup_date >= ?
        ");
        $stmt->execute([$car_id, $today]);
        $count = (int)$stmt->fetchColumn();
        return $count > 0;
    } catch (PDOException $e) {
        return true;
    }
}

// ============================================
// FUNKSIONI: Bëj një makinë primare të grupit
// ============================================
function makeCarPrimary($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT id, group_id FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $car = $stmt->fetch();
        if (!$car) {
            return false;
        }
        
        if ($car['group_id'] === null) {
            return true;
        }
        
        $old_group_id = $car['group_id'];
        
        $stmt = $pdo->prepare("UPDATE cars SET group_id = NULL, is_primary = 1 WHERE id = ?");
        $stmt->execute([$car_id]);
        
        $stmt = $pdo->prepare("UPDATE cars SET group_id = ? WHERE group_id = ? AND id != ?");
        $stmt->execute([$car_id, $old_group_id, $car_id]);
        
        $stmt = $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE group_id = ? OR (id = ? AND group_id IS NULL)");
        $stmt->execute([$car_id, $car_id]);
        
        $stmt = $pdo->prepare("UPDATE cars SET is_primary = 1 WHERE id = ?");
        $stmt->execute([$car_id]);
        
        return true;
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// FUNKSIONI: Fshi një makinë - ME HEQJE TË REFERENCAVE NË CAR_CHANGE_HISTORY
// ============================================
function deleteCarAndFixGroup($car_id, $pdo) {
    try {
        // Merr detajet e makinës
        $stmt = $pdo->prepare("SELECT id, group_id, is_primary, image_url FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $car = $stmt->fetch();
        
        if (!$car) {
            return ['success' => false, 'message' => 'Car not found'];
        }
        
        // ============================================================
        // KONTROLLO: NËSE MAKINA ËSHTË PRIMARE DHE KA KLONE, MOS E FSHIJ
        // ============================================================
        if ($car['group_id'] === null && $car['is_primary'] == 1) {
            if (hasClones($car_id, $pdo)) {
                return [
                    'success' => false, 
                    'message' => 'Kjo makinë është primare dhe ka makina të klonuara që varen nga ajo. ' .
                                 'Nuk mund të fshihet sepse klonet marrin foton nga kjo makinë. ' .
                                 'Së pari fshini makinat e klonuara (binjaket), pastaj këtë makinë.'
                ];
            }
        }
        
        // ============================================================
        // KONTROLLO NËSE KA REZERVIME AKTIVE
        // ============================================================
        if (hasActiveOrFutureReservations($car_id, $pdo)) {
            $reservations = getActiveOrFutureReservations($car_id, $pdo);
            $error_msg = "Kjo makinë ka rezervime aktive ose të ardhshme dhe nuk mund të fshihet!<br>";
            $error_msg .= "<strong>Rezervimet:</strong><br>";
            foreach($reservations as $r) {
                $error_msg .= "• <strong>{$r['reservation_code']}</strong> - {$r['customer_name']} (Pickup: {$r['pickup_date']}, Status: {$r['status']})<br>";
            }
            $error_msg .= "<br>Ju lutemi fshini ose anuloni këto rezervime përpara se të fshini makinën.";
            return ['success' => false, 'message' => $error_msg];
        }
        
        // ============================================================
        // HEQ REFERENCAT NGA CAR_CHANGE_HISTORY (por i mban log-jet)
        // ============================================================
        $pdo->prepare("UPDATE car_change_history SET old_car_id = NULL WHERE old_car_id = ?")->execute([$car_id]);
        $pdo->prepare("UPDATE car_change_history SET new_car_id = NULL WHERE new_car_id = ?")->execute([$car_id]);
        
        // ============================================================
        // FSHI TË DHËNAT E TJERA TË LIDHURA
        // ============================================================
        $pdo->prepare("DELETE FROM car_maintenance WHERE car_id = ?")->execute([$car_id]);
        $pdo->prepare("DELETE FROM price_rules WHERE car_id = ?")->execute([$car_id]);
        
        // Fshi rezervimet e anuluara ose të përfunduara (nëse ka)
        $pdo->prepare("DELETE FROM reservations WHERE car_id = ? AND status IN ('cancelled', 'completed')")->execute([$car_id]);
        
        // ============================================================
        // FSHI FIGURËN VETËM NËSE NUK PËRDORET NGA MAKINA TË TJERA
        // ============================================================
        if (!empty($car['image_url'])) {
            $image_used_by_others = isImageUsedByOtherCars($car_id, $car['image_url'], $pdo);
            
            $should_delete_image = false;
            
            if ($car['group_id'] === null && $car['is_primary'] == 1) {
                if (!hasClones($car_id, $pdo)) {
                    $should_delete_image = true;
                }
            } else {
                if (!$image_used_by_others) {
                    $should_delete_image = true;
                }
            }
            
            if ($should_delete_image) {
                deleteCarImages($car['image_url']);
            }
        }
        
        // Fshi makinën
        $stmt = $pdo->prepare("DELETE FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        
        return ['success' => true, 'message' => 'Car deleted successfully!'];
        
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
    }
}

// ============================================
// FUNKSIONI: Merr listën e rezervimeve aktive ose të ardhshme
// ============================================
function getActiveOrFutureReservations($car_id, $pdo) {
    try {
        $today = date('Y-m-d');
        $stmt = $pdo->prepare("
            SELECT id, reservation_code, customer_name, pickup_date, dropoff_date, status
            FROM reservations 
            WHERE car_id = ? 
            AND status NOT IN ('cancelled', 'completed')
            AND pickup_date >= ?
            ORDER BY pickup_date ASC
        ");
        $stmt->execute([$car_id, $today]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return [];
    }
}

// ============================================
// HANDLE MAINTENANCE ACTIONS - VETËM ADMIN/SUPER_ADMIN
// ============================================
if(isset($_POST['add_maintenance']) && !$is_worker) {
    $car_id = (int)$_POST['car_id'];
    $service_type = trim($_POST['service_type']);
    $description = trim($_POST['description']);
    $service_date = $_POST['service_date'];
    $cost = !empty($_POST['cost']) ? (float)$_POST['cost'] : 0;
    $notes = trim($_POST['notes'] ?? '');
    $performed_by = trim($_POST['performed_by'] ?? $_SESSION['admin_username']);
    
    if($car_id && $service_type && $description && $service_date) {
        $stmt = $pdo->prepare("INSERT INTO car_maintenance (car_id, service_type, description, service_date, cost, notes, performed_by) 
                                VALUES (?, ?, ?, ?, ?, ?, ?)");
        if($stmt->execute([$car_id, $service_type, $description, $service_date, $cost, $notes, $performed_by])) {
            $message = "Maintenance record added successfully!";
            $major_services = ['Major Service', 'Engine Repair', 'Transmission Repair', 'Body Repair'];
            if(in_array($service_type, $major_services)) {
                $pdo->prepare("UPDATE cars SET status = 'maintenance' WHERE id = ?")->execute([$car_id]);
            }
        } else {
            $error = "Failed to add maintenance record.";
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}

// ============================================
// HANDLE CLONE CAR - VETËM ADMIN/SUPER_ADMIN
// ============================================
if(isset($_POST['clone_car']) && !$is_worker) {
    $source_id = (int)$_POST['source_car_id'];
    $new_plate = trim($_POST['new_license_plate'] ?? '');

    if(!$source_id || !$new_plate) {
        $error = "Plotëso targën e re për makinën identike.";
    } else {
        $stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
        $stmt->execute([$source_id]);
        $source_car = $stmt->fetch(PDO::FETCH_ASSOC);

        if(!$source_car) {
            $error = "Makina burim nuk u gjet.";
        } else {
            // Kontrollo që targa e re nuk ekziston
            $check = $pdo->prepare("SELECT id FROM cars WHERE license_plate = ?");
            $check->execute([$new_plate]);
            if($check->fetch()) {
                $error = "Kjo targë ekziston tashmë te një makinë tjetër.";
            } else {
                // ============================================================
                // PËRCAKTO GROUP_ID NË BAZË TË MAKINËS BURIM
                // ============================================================
                
                // Nëse makina burim është primare (group_id IS NULL dhe is_primary = 1)
                if ($source_car['group_id'] === null && $source_car['is_primary'] == 1) {
                    // Makina burim është primare - group_id do të jetë id e saj
                    $group_id = $source_car['id'];
                    
                    // Sigurohu që makina burim është shenjuar si primare
                    $pdo->prepare("UPDATE cars SET is_primary = 1, group_id = NULL WHERE id = ?")->execute([$source_car['id']]);
                    
                    // Sigurohu që asnjë makinë tjetër në grup të mos jetë primare
                    $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE group_id = ? AND id != ?")->execute([$group_id, $source_car['id']]);
                    
                } else {
                    // Makina burim është e klonuar (ka group_id)
                    $group_id = (int)$source_car['group_id'];
                    
                    // Verifiko që makina primare ekziston ende
                    $check_primary = $pdo->prepare("SELECT id, is_primary FROM cars WHERE id = ? AND is_primary = 1");
                    $check_primary->execute([$group_id]);
                    $primary_exists = $check_primary->fetch();
                    
                    if (!$primary_exists) {
                        // Makina primare nuk ekziston më ose nuk është primare
                        // Bëj makinën burim primare
                        $pdo->prepare("UPDATE cars SET is_primary = 1, group_id = NULL WHERE id = ?")->execute([$source_car['id']]);
                        
                        // Përditëso të gjitha makinat e tjera në grup që të kenë group_id = source_car['id']
                        $pdo->prepare("UPDATE cars SET group_id = ? WHERE group_id = ? AND id != ?")->execute([$source_car['id'], $group_id, $source_car['id']]);
                        
                        // Sigurohu që asnjë makinë tjetër në grup të mos jetë primare
                        $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE group_id = ? OR id = ?")->execute([$source_car['id'], $source_car['id']]);
                        
                        // Përditëso group_id për të gjithë
                        $group_id = $source_car['id'];
                        
                        // Shenjo makinën burim si primare
                        $pdo->prepare("UPDATE cars SET is_primary = 1 WHERE id = ?")->execute([$source_car['id']]);
                    } else {
                        // Primarja ekziston, sigurohu që ajo është e saktë
                        $pdo->prepare("UPDATE cars SET group_id = NULL, is_primary = 1 WHERE id = ?")->execute([$primary_exists['id']]);
                        
                        // Sigurohu që asnjë makinë tjetër në grup të mos jetë primare
                        $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE group_id = ? AND id != ?")->execute([$group_id, $primary_exists['id']]);
                    }
                }
                
                // ============================================================
                // KRIJO MAKINËN E RE (BINJAKE)
                // ============================================================
                $insert = $pdo->prepare("
                    INSERT INTO cars (brand, model, license_plate, car_type, year, fuel_type, transmission, seats, luggage, description, key_features, image_url, status, group_id, is_primary)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'available', ?, 0)
                ");
                $insert->execute([
                    $source_car['brand'],
                    $source_car['model'],
                    $new_plate,
                    $source_car['car_type'],
                    $source_car['year'],
                    $source_car['fuel_type'],
                    $source_car['transmission'],
                    $source_car['seats'],
                    $source_car['luggage'],
                    $source_car['description'],
                    $source_car['key_features'],
                    $source_car['image_url'],
                    $group_id
                ]);
                
                $new_car_id = $pdo->lastInsertId();
                
                // ============================================================
                // KOPJO PRICE_RULES
                // ============================================================
                $stmt_rules = $pdo->prepare("SELECT * FROM price_rules WHERE car_id = ?");
                $stmt_rules->execute([$source_car['id']]);
                $rules = $stmt_rules->fetchAll(PDO::FETCH_ASSOC);
                
                $insert_rule = $pdo->prepare("
                    INSERT INTO price_rules (car_id, rule_type, start_date, end_date, fixed_price, discount_percent, min_days, priority, is_active)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                foreach($rules as $r) {
                    $insert_rule->execute([
                        $new_car_id,
                        $r['rule_type'],
                        $r['start_date'],
                        $r['end_date'],
                        $r['fixed_price'],
                        $r['discount_percent'],
                        $r['min_days'],
                        $r['priority'],
                        $r['is_active']
                    ]);
                }
                
                // ============================================================
                // SIGUROHU QË MAKINA PRIMARE ËSHTË E SAKTA
                // ============================================================
                // Gjej primaren aktuale të grupit dhe sigurohu që është e saktë
                $stmt_primary = $pdo->prepare("
                    SELECT id FROM cars 
                    WHERE (id = ? OR group_id = ?) AND is_primary = 1
                    LIMIT 1
                ");
                $stmt_primary->execute([$group_id, $group_id]);
                $current_primary = $stmt_primary->fetch();
                
                if (!$current_primary) {
                    // Nëse nuk ka primare, bëj makinën e parë në grup primare
                    $stmt_first = $pdo->prepare("
                        SELECT id FROM cars 
                        WHERE id = ? OR group_id = ?
                        ORDER BY id ASC
                        LIMIT 1
                    ");
                    $stmt_first->execute([$group_id, $group_id]);
                    $first_car = $stmt_first->fetch();
                    
                    if ($first_car) {
                        // Bëj këtë makinë primare
                        $pdo->prepare("UPDATE cars SET is_primary = 1, group_id = NULL WHERE id = ?")->execute([$first_car['id']]);
                        
                        // Përditëso të gjitha makinat e tjera në grup
                        $pdo->prepare("UPDATE cars SET group_id = ? WHERE id != ? AND (id = ? OR group_id = ?)")->execute([$first_car['id'], $first_car['id'], $group_id, $group_id]);
                        
                        // Sigurohu që asnjë makinë tjetër të mos jetë primare
                        $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE id != ? AND (id = ? OR group_id = ?)")->execute([$first_car['id'], $group_id, $group_id]);
                    }
                } else {
                    // Primarja ekziston, sigurohu që ajo është e saktë (group_id NULL dhe is_primary = 1)
                    $pdo->prepare("UPDATE cars SET group_id = NULL, is_primary = 1 WHERE id = ?")->execute([$current_primary['id']]);
                    
                    // Sigurohu që asnjë makinë tjetër në grup të mos jetë primare
                    $pdo->prepare("UPDATE cars SET is_primary = 0 WHERE id != ? AND (id = ? OR group_id = ?)")->execute([$current_primary['id'], $group_id, $group_id]);
                }
                
                $message = "Makina identike u shtua me sukses me targën {$new_plate}!";
            }
        }
    }
}

// ============================================
// HANDLE DELETE - VETËM ADMIN/SUPER_ADMIN
// ============================================
if(isset($_GET['delete_id']) && !$is_worker) {
    $id = (int)$_GET['delete_id'];
    
    $result = deleteCarAndFixGroup($id, $pdo);
    if ($result['success']) {
        $message = $result['message'];
    } else {
        $error = $result['message'];
    }
    
    // Redirect duke ruajtur filtrat
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $car_type = isset($_GET['car_type']) ? $_GET['car_type'] : '';
    $status = isset($_GET['status']) ? $_GET['status'] : '';
    $transmission = isset($_GET['transmission']) ? $_GET['transmission'] : '';
    $sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
    $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    
    $redirect_url = 'cars.php';
    $params = [];
    if($search) $params[] = 'search=' . urlencode($search);
    if($car_type) $params[] = 'car_type=' . urlencode($car_type);
    if($status) $params[] = 'status=' . urlencode($status);
    if($transmission) $params[] = 'transmission=' . urlencode($transmission);
    if($sort) $params[] = 'sort=' . urlencode($sort);
    if($order) $params[] = 'order=' . urlencode($order);
    if($page > 1) $params[] = 'page=' . $page;
    
    if(!empty($params)) {
        $redirect_url .= '?' . implode('&', $params);
    }
    
    if(!$result['success']) {
        $_SESSION['delete_error'] = $error;
    }
    
    header('Location: ' . $redirect_url);
    exit();
}

// ============================================
// SHFAQ ERRORIN NGA SESSIONI
// ============================================
if(isset($_SESSION['delete_error'])) {
    $error = $_SESSION['delete_error'];
    unset($_SESSION['delete_error']);
}

// ============================================
// AJAX HANDLERS
// ============================================

// Get maintenance history for a car (AJAX)
if(isset($_GET['ajax']) && isset($_GET['get_maintenance'])) {
    header('Content-Type: application/json');
    $car_id = (int)$_GET['get_maintenance'];
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $per_page = 10;
    $offset = ($page - 1) * $per_page;
    
    $stmt = $pdo->prepare("SELECT brand, model, license_plate FROM cars WHERE id = ?");
    $stmt->execute([$car_id]);
    $car = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$car) {
        echo json_encode(['success' => false, 'message' => 'Car not found']);
        exit;
    }
    
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM car_maintenance WHERE car_id = ?");
    $count_stmt->execute([$car_id]);
    $total = $count_stmt->fetchColumn();
    $total_pages = ceil($total / $per_page);
    
    $stmt = $pdo->prepare("
        SELECT * FROM car_maintenance 
        WHERE car_id = ? 
        ORDER BY service_date DESC, created_at DESC
        LIMIT $offset, $per_page
    ");
    $stmt->execute([$car_id]);
    $maintenance = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'car' => $car,
        'maintenance' => $maintenance,
        'total' => $total,
        'current_page' => $page,
        'total_pages' => $total_pages,
        'per_page' => $per_page
    ]);
    exit;
}

// Get car history (reservations) - AJAX
if(isset($_GET['ajax']) && isset($_GET['car_history'])) {
    header('Content-Type: application/json');
    $car_id = (int)$_GET['car_history'];
    $page = isset($_GET['history_page']) ? (int)$_GET['history_page'] : 1;
    $per_page = 10;
    $offset = ($page - 1) * $per_page;
    
    $stmt = $pdo->prepare("SELECT brand, model, license_plate FROM cars WHERE id = ?");
    $stmt->execute([$car_id]);
    $car = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$car) {
        echo json_encode(['success' => false, 'message' => 'Car not found']);
        exit;
    }
    
    $count_stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM reservations r 
        WHERE r.car_id = ?
    ");
    $count_stmt->execute([$car_id]);
    $total_reservations = $count_stmt->fetchColumn();
    $total_pages = ceil($total_reservations / $per_page);
    
    $stmt = $pdo->prepare("
        SELECT 
            r.*,
            c.brand, 
            c.model, 
            c.license_plate,
            i.name as insurance_name
        FROM reservations r 
        LEFT JOIN cars c ON r.car_id = c.id
        LEFT JOIN insurance_types i ON r.selected_insurance_id = i.id
        WHERE r.car_id = ? 
        ORDER BY r.pickup_date DESC, r.created_at DESC
        LIMIT $offset, $per_page
    ");
    $stmt->execute([$car_id]);
    $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($reservations as &$res) {
        if(!empty($res['selected_options'])) {
            $options_data = json_decode($res['selected_options'], true);
            if(is_array($options_data) && count($options_data) > 0) {
                $option_names = [];
                foreach($options_data as $opt) {
                    if(isset($opt['name'])) {
                        $option_names[] = $opt['name'] . (isset($opt['quantity']) && $opt['quantity'] > 1 ? ' x' . $opt['quantity'] : '');
                    }
                }
                $res['options_names'] = implode(', ', $option_names);
            } else {
                $res['options_names'] = '';
            }
        } else {
            $res['options_names'] = '';
        }
    }
    
    echo json_encode([
        'success' => true,
        'car' => $car,
        'reservations' => $reservations,
        'total_count' => $total_reservations,
        'current_page' => $page,
        'total_pages' => $total_pages,
        'per_page' => $per_page
    ]);
    exit;
}

// ============================================
// SORTING & FILTERS
// ============================================
$sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$sort_order = isset($_GET['order']) && strtoupper($_GET['order']) == 'ASC' ? 'ASC' : 'DESC';

$allowed_sort_columns = [
    'id', 'brand', 'model', 'license_plate', 'car_type', 'year', 
    'transmission', 'seats', 'status'
];
if(!in_array($sort_column, $allowed_sort_columns)) {
    $sort_column = 'id';
    $sort_order = 'DESC';
}

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$car_type = isset($_GET['car_type']) ? $_GET['car_type'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$transmission = isset($_GET['transmission']) ? $_GET['transmission'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$sql = "SELECT * FROM cars WHERE 1=1";
$count_sql = "SELECT COUNT(*) FROM cars WHERE 1=1";
$params = [];

if($search) {
    $sql .= " AND (brand LIKE ? OR model LIKE ? OR license_plate LIKE ?)";
    $count_sql .= " AND (brand LIKE ? OR model LIKE ? OR license_plate LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
}

if($car_type) {
    $sql .= " AND car_type = ?";
    $count_sql .= " AND car_type = ?";
    $params[] = $car_type;
}

if($status) {
    $sql .= " AND status = ?";
    $count_sql .= " AND status = ?";
    $params[] = $status;
}

if($transmission) {
    $sql .= " AND transmission = ?";
    $count_sql .= " AND transmission = ?";
    $params[] = $transmission;
}

$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_cars = $count_stmt->fetchColumn();
$total_pages = ceil($total_cars / $per_page);

$sql .= " ORDER BY " . $sort_column . " " . $sort_order . " LIMIT $offset, $per_page";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$cars = $stmt->fetchAll(PDO::FETCH_ASSOC);

$car_types = $pdo->query("SELECT DISTINCT car_type FROM cars ORDER BY car_type")->fetchAll(PDO::FETCH_COLUMN);

$type_labels = [
    'economy' => 'Economy',
    'sedan' => 'Sedan',
    'suv' => 'SUV',
    '7-seats' => '7+ Seats',
    'cabrio' => 'Cabrio',
    'luxury' => 'Luxury'
];

$page_title = 'Manage Cars';

function sort_url($column) {
    global $sort_column, $sort_order, $search, $car_type, $status, $transmission, $per_page;
    $new_order = ($sort_column == $column && $sort_order == 'ASC') ? 'DESC' : 'ASC';
    $url = "?sort=" . $column . "&order=" . $new_order . "&per_page=" . $per_page;
    if($search) $url .= "&search=" . urlencode($search);
    if($car_type) $url .= "&car_type=" . urlencode($car_type);
    if($status) $url .= "&status=" . urlencode($status);
    if($transmission) $url .= "&transmission=" . urlencode($transmission);
    return $url;
}

function sort_icon($column) {
    global $sort_column, $sort_order;
    if($sort_column == $column) {
        return $sort_order == 'ASC' ? '↑' : '↓';
    }
    return '↕';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - 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;
        }
        .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; }
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        .page-header h1 i { color: #0066cc; margin-right: 10px; }
        
        .btn-add {
            background: #0066cc;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }
        .btn-add:hover {
            background: #0052a3;
            transform: translateY(-1px);
        }
        .btn-add.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 3px solid #10b981;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 3px solid #dc2626;
        }
        
        .filters-bar {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            padding: 16px 20px;
            margin-bottom: 24px;
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            align-items: flex-end;
        }
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #374151;
            text-transform: uppercase;
        }
        .filter-group input, .filter-group select {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
            min-width: 160px;
        }
        .filter-group button {
            background: #0066cc;
            color: white;
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
        }
        .filter-group button.reset {
            background: #6b7280;
        }
        
        .cars-table {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        th {
            background: #f9fafb;
            font-weight: 600;
            color: #374151;
        }
        th a {
            color: #374151;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        th a:hover {
            color: #0066cc;
        }
        .sort-icon {
            font-size: 12px;
            color: #9ca3af;
        }
        .car-image {
            width: 50px;
            height: 50px;
            object-fit: contain;
            border-radius: 8px;
            background: #f3f4f6;
            padding: 2px;
        }
        .license-plate-badge {
            background: #f3f4f6;
            padding: 4px 8px;
            border-radius: 6px;
            font-family: monospace;
            font-size: 12px;
            font-weight: 600;
            color: #1f2937;
            display: inline-block;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .status-available { background: #d1fae5; color: #059669; }
        .status-maintenance { background: #fef3c7; color: #92400e; }
        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .btn-edit, .btn-price, .btn-history, .btn-delete, .btn-clone {
            padding: 6px 12px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.2s;
            cursor: pointer;
            border: none;
        }
        .btn-edit { background: #0066cc; color: white; }
        .btn-edit:hover { background: #0052a3; }
        .btn-edit.disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
        .btn-price { background: #10b981; color: white; }
        .btn-price:hover { background: #059669; }
        .btn-price.disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
        .btn-history { background: #8b5cf6; color: white; }
        .btn-history:hover { background: #7c3aed; }
        .btn-delete { background: #dc2626; color: white; }
        .btn-delete:hover { background: #b91c1c; }
        .btn-delete.disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
        .btn-clone { background: #f59e0b; color: white; }
        .btn-clone:hover { background: #d97706; }
        .btn-clone.disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
        .group-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            background: #fef3c7;
            color: #92400e;
            font-size: 11px;
            font-weight: 600;
            padding: 2px 8px;
            border-radius: 999px;
            margin-top: 4px;
        }
        .group-badge.primary {
            background: #dbeafe;
            color: #1e40af;
        }
        .group-badge.primary i {
            color: #3b82f6;
        }
        
        .has-clones-badge {
            display: inline-block;
            background: #fef3c7;
            color: #92400e;
            font-size: 10px;
            padding: 2px 8px;
            border-radius: 12px;
            margin-top: 4px;
            border: 1px solid #fcd34d;
        }
        .has-clones-badge i {
            color: #f59e0b;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 24px;
            flex-wrap: wrap;
        }
        .pagination a, .pagination span {
            padding: 8px 14px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            text-decoration: none;
            color: #374151;
            background: white;
            font-size: 13px;
            transition: all 0.2s;
        }
        .pagination a:hover {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .pagination .active {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .pagination .disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px;
            color: #6b7280;
        }
        .empty-state i {
            font-size: 48px;
            color: #d1d5db;
            margin-bottom: 16px;
            display: block;
        }
        
        .info-text {
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            margin-top: 16px;
        }
        
        .worker-badge {
            display: inline-block;
            background: #fef3c7;
            color: #92400e;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            margin-left: 12px;
        }
        
        /* Modal Styles */
        .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: 1300px;
            max-width: 95%;
            max-height: 90vh;
            overflow: hidden;
            animation: modalSlideIn 0.3s ease;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
            display: flex;
            flex-direction: column;
        }
        @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;
            flex-shrink: 0;
        }
        .modal-header h3 { font-size: 20px; font-weight: 600; margin: 0; }
        .modal-header h3 i { margin-right: 12px; }
        .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; 
            flex: 1;
            overflow-y: auto; 
            min-height: 300px;
        }
        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            border-radius: 0 0 20px 20px;
            flex-shrink: 0;
        }
        
        /* Two Column Layout for History Modal */
        .history-two-columns {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }
        .history-column {
            background: #f8fafc;
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid #e2e8f0;
        }
        .history-column-header {
            background: #f1f5f9;
            padding: 12px 16px;
            font-weight: 600;
            font-size: 14px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .history-column-header i {
            color: #0066cc;
        }
        .history-column-header .badge-count {
            background: #0066cc;
            color: white;
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 11px;
        }
        .history-column-body {
            padding: 12px;
            max-height: 500px;
            overflow-y: auto;
        }
        
        .car-info-card {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }
        .car-info-card .car-icon { font-size: 48px; color: #0066cc; }
        .car-info-card .car-details h4 {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 6px;
        }
        .car-info-card .car-details p { color: #475569; font-size: 14px; }
        .car-info-card .car-stats {
            margin-left: auto;
            background: white;
            padding: 8px 16px;
            border-radius: 40px;
            font-size: 14px;
            font-weight: 600;
            color: #0066cc;
        }
        
        .history-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
        }
        .history-table th {
            background: #f1f5f9;
            padding: 8px 8px;
            text-align: left;
            font-weight: 600;
            color: #1e293b;
            border-bottom: 1px solid #e2e8f0;
            position: sticky;
            top: 0;
            font-size: 10px;
        }
        .history-table td {
            padding: 8px 8px;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
            font-size: 11px;
        }
        .history-table tr:hover {
            background: #f8fafc;
        }
        .history-badge {
            font-family: monospace;
            font-weight: bold;
            color: #0066cc;
        }
        
        .res-status-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 600;
        }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-confirmed { background: #dbeafe; color: #1e40af; }
        .status-running { background: #d1fae5; color: #065f46; }
        .status-completed { background: #e0e7ff; color: #3730a3; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        .payment-paid { background: #d1fae5; color: #065f46; }
        .payment-unpaid { background: #fee2e2; color: #991b1b; }
        .payment-partial { background: #fef3c7; color: #92400e; }
        
        .btn-sm {
            background: #0066cc;
            color: white;
            padding: 3px 8px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 10px;
            font-weight: 500;
            display: inline-block;
            border: none;
            cursor: pointer;
        }
        .btn-sm:hover { background: #0052a3; }
        
        .empty-history {
            text-align: center;
            padding: 30px;
            color: #6b7280;
        }
        .empty-history i {
            font-size: 32px;
            color: #cbd5e1;
            margin-bottom: 12px;
            display: block;
        }
        
        .extras-text {
            font-size: 10px;
            color: #64748b;
            max-width: 150px;
            white-space: normal;
            word-break: break-word;
        }
        
        .history-pagination {
            display: flex;
            justify-content: center;
            gap: 6px;
            margin-top: 12px;
            padding: 8px;
            background: #f8fafc;
            border-radius: 8px;
            flex-wrap: wrap;
        }
        .history-pagination a, .history-pagination span {
            padding: 4px 10px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            text-decoration: none;
            color: #475569;
            background: white;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .history-pagination a:hover {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .history-pagination .active {
            background: #0066cc;
            color: white;
            border-color: #0066cc;
        }
        .history-pagination .disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background: #f1f5f9;
        }
        
        .history-loading {
            text-align: center;
            padding: 20px;
        }
        
        /* Add Maintenance Form */
        .maintenance-add-section {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
            border: 1px solid #e2e8f0;
        }
        .maintenance-add-section h4 {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 12px;
            color: #1e293b;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            user-select: none;
        }
        .maintenance-add-section h4 i {
            color: #10b981;
            transition: transform 0.3s ease;
        }
        .maintenance-add-section h4 .toggle-icon {
            transition: transform 0.3s ease;
            display: inline-block;
        }
        .maintenance-add-section h4 .toggle-icon.rotated {
            transform: rotate(45deg);
        }
        .maintenance-add-section .maint-form-wrapper {
            display: none;
            padding-top: 12px;
            border-top: 1px solid #e5e7eb;
        }
        .maintenance-add-section .maint-form-wrapper.open {
            display: block;
        }
        .maintenance-add-section.disabled {
            opacity: 0.6;
            pointer-events: none;
        }
        
        .maint-form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }
        .maint-form-group {
            margin-bottom: 12px;
        }
        .maint-form-group label {
            display: block;
            font-size: 11px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 4px;
        }
        .maint-form-group input, .maint-form-group select, .maint-form-group textarea {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 13px;
        }
        .btn-add-maint {
            background: #10b981;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            width: 100%;
            margin-top: 8px;
        }
        .btn-add-maint:hover { background: #059669; }
        .btn-add-maint.disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
        
        /* Blocked Modal - Popup */
        .blocked-modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: 2000;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(4px);
        }
        .blocked-modal-overlay.show {
            display: flex;
        }
        .blocked-modal {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 95%;
            padding: 32px 28px;
            text-align: center;
            animation: modalSlideIn 0.3s ease;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.3);
        }
        .blocked-modal .modal-icon {
            font-size: 56px;
            margin-bottom: 16px;
        }
        .blocked-modal h3 {
            font-size: 22px;
            font-weight: 700;
            color: #1a1a2e;
            margin-bottom: 8px;
        }
        .blocked-modal .car-name {
            font-size: 16px;
            font-weight: 600;
            color: #0066cc;
            margin-bottom: 12px;
        }
        .blocked-modal p {
            color: #6b7280;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 20px;
        }
        .blocked-modal .btn-view-reservations {
            display: inline-block;
            background: #0066cc;
            color: white;
            padding: 12px 28px;
            border: none;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.2s;
        }
        .blocked-modal .btn-view-reservations:hover {
            background: #0052a3;
        }
        .blocked-modal .btn-close-blocked {
            display: inline-block;
            background: #e5e7eb;
            color: #374151;
            padding: 10px 24px;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s;
        }
        .blocked-modal .btn-close-blocked:hover {
            background: #d1d5db;
        }
        .blocked-modal .modal-actions {
            display: flex;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 8px;
        }
        
        @media (max-width: 1000px) {
            .history-two-columns {
                grid-template-columns: 1fr;
            }
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .filters-bar { flex-direction: column; align-items: stretch; }
            .filter-group input, .filter-group select { width: 100%; }
            .action-buttons { flex-direction: column; }
            .btn-edit, .btn-price, .btn-history, .btn-delete { justify-content: center; }
            .modal-content { width: 98%; }
            .history-table { display: block; overflow-x: auto; }
            .car-info-card { flex-direction: column; text-align: center; }
            .car-info-card .car-stats { margin-left: 0; }
            .maint-form-row { grid-template-columns: 1fr; }
            .blocked-modal { padding: 24px 20px; }
        }
    </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" class="active"><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"><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-car"></i> Manage Cars
                <?php if($is_worker): ?>
                    <span class="worker-badge"><i class="fas fa-eye"></i> View Only</span>
                <?php endif; ?>
            </h1>
            <?php if($is_worker): ?>
                <span style="font-size: 13px; color: #6b7280;">
                    <i class="fas fa-lock"></i> Worker mode: You can view cars and history, but cannot edit or delete.
                </span>
            <?php else: ?>
                <a href="add-car.php" class="btn-add"><i class="fas fa-plus"></i> Add New Car</a>
            <?php endif; ?>
        </div>
        
        <?php if($message): ?>
            <div class="alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        <?php if($error): ?>
            <div class="alert-error">
                <i class="fas fa-exclamation-circle"></i> 
                <?php echo $error; ?>
                <?php if(strpos($error, 'rezervime') !== false): ?>
                    <br><br>
                    <a href="reservations.php" 
                       style="display:inline-block; margin-top:8px; background:#0066cc; color:white; padding:8px 16px; border-radius:6px; text-decoration:none;">
                        <i class="fas fa-calendar-check"></i> Shiko të gjitha Rezervimet
                    </a>
                <?php endif; ?>
                <?php if(strpos($error, 'klonuara') !== false): ?>
                    <br><br>
                    <span style="display:inline-block; margin-top:8px; background:#fef3c7; color:#92400e; padding:8px 16px; border-radius:6px;">
                        <i class="fas fa-info-circle"></i> Së pari fshini makinat e klonuara që varen nga kjo.
                    </span>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <div class="filters-bar">
            <form method="GET" id="filterForm" style="display: contents;">
                <input type="hidden" name="sort" value="<?php echo htmlspecialchars($sort_column); ?>">
                <input type="hidden" name="order" value="<?php echo htmlspecialchars($sort_order); ?>">
                <div class="filter-group">
                    <label><i class="fas fa-search"></i> Search</label>
                    <input type="text" name="search" placeholder="Brand, model or plate..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-car"></i> Car Type</label>
                    <select name="car_type">
                        <option value="">All Types</option>
                        <?php foreach($car_types as $type): ?>
                            <option value="<?php echo $type; ?>" <?php echo $car_type == $type ? 'selected' : ''; ?>>
                                <?php echo $type_labels[$type] ?? ucfirst($type); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-cog"></i> Transmission</label>
                    <select name="transmission">
                        <option value="">All</option>
                        <option value="Manual" <?php echo $transmission == 'Manual' ? 'selected' : ''; ?>>Manual</option>
                        <option value="Automatic" <?php echo $transmission == 'Automatic' ? 'selected' : ''; ?>>Automatic</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-circle"></i> Status</label>
                    <select name="status">
                        <option value="">All</option>
                        <option value="available" <?php echo $status == 'available' ? 'selected' : ''; ?>>Available</option>
                        <option value="maintenance" <?php echo $status == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                    </select>
                </div>
                <div class="filter-group">
                    <button type="submit"><i class="fas fa-filter"></i> Apply</button>
                </div>
                <div class="filter-group">
                    <button type="button" class="reset" onclick="resetFilters()"><i class="fas fa-undo"></i> Reset</button>
                </div>
            </form>
        </div>
        
        <div class="cars-table">
            <?php if(count($cars) > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th><a href="<?php echo sort_url('id'); ?>">ID <span class="sort-icon"><?php echo sort_icon('id'); ?></span></a></th>
                            <th>Image</th>
                            <th><a href="<?php echo sort_url('brand'); ?>">Car <span class="sort-icon"><?php echo sort_icon('brand'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('license_plate'); ?>">License Plate <span class="sort-icon"><?php echo sort_icon('license_plate'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('car_type'); ?>">Type <span class="sort-icon"><?php echo sort_icon('car_type'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('year'); ?>">Year <span class="sort-icon"><?php echo sort_icon('year'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('transmission'); ?>">Transmission <span class="sort-icon"><?php echo sort_icon('transmission'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('seats'); ?>">Seats <span class="sort-icon"><?php echo sort_icon('seats'); ?></span></a></th>
                            <th><a href="<?php echo sort_url('status'); ?>">Status <span class="sort-icon"><?php echo sort_icon('status'); ?></span></a></th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($cars as $car): 
                            $thumb_url = '';
                            if(!empty($car['image_url'])) {
                                $thumb_path = str_replace('uploads/', 'uploads/thumbnails/', $car['image_url']);
                                if(file_exists('../' . $thumb_path)) {
                                    $thumb_url = $thumb_path;
                                } else {
                                    $thumb_url = $car['image_url'];
                                }
                            }
                            
                            $group_count = 0;
                            $is_primary = false;
                            $show_group_badge = false;
                            $group_display_id = null;
                            $has_clones = false;
                            $is_primary_with_clones = false;
                            
                            if ($car['group_id'] !== null) {
                                $group_display_id = $car['group_id'];
                                $group_count = countCarsInGroup($car['group_id'], $pdo);
                                $show_group_badge = ($group_count > 1);
                            } else if ($car['is_primary'] == 1) {
                                $is_primary = true;
                                $group_display_id = $car['id'];
                                $group_count = countCarsInGroup($car['id'], $pdo);
                                $show_group_badge = ($group_count > 1);
                                $has_clones = hasClones($car['id'], $pdo);
                                $is_primary_with_clones = ($has_clones && $group_count > 1);
                            }
                            
                            $has_reservations = hasActiveOrFutureReservations($car['id'], $pdo);
                        ?>
                        <tr>
                            <td>#<?php echo $car['id']; ?></td>
                            <td>
                                <img src="../<?php echo $thumb_url ?: ($car['image_url'] ?: 'https://placehold.co/50x50?text=Car'); ?>" 
                                     class="car-image" 
                                     loading="lazy"
                                     width="50"
                                     height="50"
                                     alt="<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES, 'UTF-8'); ?>"
                                     onerror="this.src='https://placehold.co/50x50?text=Car'">
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES, 'UTF-8'); ?></strong>
                                
                                <?php if($show_group_badge || $is_primary_with_clones): ?>
                                    <?php if($is_primary): ?>
                                        <br><span class="group-badge primary" title="Makina kryesore e grupit (ID: <?php echo $group_display_id; ?>)">
                                            <i class="fas fa-crown"></i> Grupi #<?php echo $group_display_id; ?> (<?php echo $group_count; ?> makina)
                                        </span>
                                        <?php if($is_primary_with_clones): ?>
                                            <br><span class="has-clones-badge">
                                                <i class="fas fa-copy"></i> Ka <?php echo $group_count - 1; ?> makina të klonuara
                                            </span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <br><span class="group-badge" title="Pjesë e grupit të makinave identike (ID: <?php echo $group_display_id; ?>)">
                                            <i class="fas fa-layer-group"></i> Grupi #<?php echo $group_display_id; ?> (<?php echo $group_count; ?> makina)
                                        </span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                            <td><span class="license-plate-badge"><?php echo htmlspecialchars($car['license_plate'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                            <td><?php echo $type_labels[$car['car_type']] ?? ucfirst($car['car_type']); ?></td>
                            <td><?php echo $car['year']; ?></td>
                            <td><?php echo $car['transmission']; ?></td>
                            <td><?php echo $car['seats']; ?> seats</td>
                            <td>
                                <span class="status-badge status-<?php echo $car['status']; ?>">
                                    <?php echo $car['status'] == 'available' ? 'Available' : 'Maintenance'; ?>
                                </span>
                            </td>
                            <td class="action-buttons">
                                <?php if(!$is_worker): ?>
                                    <a href="edit-car.php?id=<?php echo $car['id']; ?>" class="btn-edit">
                                        <i class="fas fa-edit"></i> Edit
                                    </a>
                                <?php else: ?>
                                    <span class="btn-edit disabled"><i class="fas fa-edit"></i> Edit</span>
                                <?php endif; ?>
                                
                                <?php if(!$is_worker): ?>
                                    <a href="price-list.php?car_id=<?php echo $car['id']; ?>" class="btn-price">
                                        <i class="fas fa-tags"></i> Price
                                    </a>
                                <?php else: ?>
                                    <span class="btn-price disabled"><i class="fas fa-tags"></i> Price</span>
                                <?php endif; ?>
                                
                                <?php if(!$is_worker): ?>
                                    <button class="btn-clone" onclick="openCloneModal(<?php echo $car['id']; ?>, '<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>')">
                                        <i class="fas fa-copy"></i> Klono
                                    </button>
                                <?php else: ?>
                                    <span class="btn-clone disabled"><i class="fas fa-copy"></i> Klono</span>
                                <?php endif; ?>
                                
                                <button class="btn-history" onclick="showCarMaintenance(<?php echo $car['id']; ?>, '<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($car['license_plate'], ENT_QUOTES); ?>')">
                                    <i class="fas fa-history"></i> History
                                </button>
                                
                                <?php if(!$is_worker): ?>
                                    <?php if($is_primary_with_clones): ?>
                                        <button class="btn-delete" style="background:#6b7280; cursor:not-allowed;" 
                                                onclick="showPrimaryWithClonesBlocked('<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>', <?php echo $group_count - 1; ?>)">
                                            <i class="fas fa-lock"></i> Bllokuar
                                        </button>
                                    <?php elseif($has_reservations): ?>
                                        <button class="btn-delete" onclick="showReservationBlockedModal('<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>')">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    <?php else: ?>
                                        <button class="btn-delete" onclick="confirmDelete(<?php echo $car['id']; ?>, '<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES); ?>', <?php echo $show_group_badge ? 'true' : 'false'; ?>, <?php echo $group_count; ?>, <?php echo $is_primary ? 'true' : 'false'; ?>)">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="btn-delete disabled"><i class="fas fa-trash"></i> Delete</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-car-side"></i>
                    <p>No cars found</p>
                    <?php if($search || $car_type || $status || $transmission): ?>
                        <p style="margin-top: 8px;">Try changing your filters</p>
                        <button onclick="resetFilters()" class="btn-add" style="margin-top: 16px; background: #6b7280;">Clear Filters</button>
                    <?php else: ?>
                        <?php if(!$is_worker): ?>
                            <a href="add-car.php" class="btn-add" style="margin-top: 16px;">Add Your First Car</a>
                        <?php else: ?>
                            <p style="margin-top: 16px; color: #9ca3af;">No cars available</p>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <?php if($total_pages > 1): ?>
        <div class="pagination">
            <?php if($page > 1): ?>
                <a href="?page=<?php echo $page-1; ?>&sort=<?php echo urlencode($sort_column); ?>&order=<?php echo urlencode($sort_order); ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $car_type ? '&car_type=' . urlencode($car_type) : ''; ?><?php echo $status ? '&status=' . urlencode($status) : ''; ?><?php echo $transmission ? '&transmission=' . urlencode($transmission) : ''; ?>">
                    <i class="fas fa-chevron-left"></i> Previous
                </a>
            <?php else: ?>
                <span class="disabled"><i class="fas fa-chevron-left"></i> Previous</span>
            <?php endif; ?>
            
            <?php 
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if($start_page > 1): ?>
                <a href="?page=1&sort=<?php echo urlencode($sort_column); ?>&order=<?php echo urlencode($sort_order); ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $car_type ? '&car_type=' . urlencode($car_type) : ''; ?><?php echo $status ? '&status=' . urlencode($status) : ''; ?><?php echo $transmission ? '&transmission=' . urlencode($transmission) : ''; ?>">1</a>
                <?php if($start_page > 2): ?>
                    <span>...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for($i = $start_page; $i <= $end_page; $i++): ?>
                <?php if($i == $page): ?>
                    <span class="active"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&sort=<?php echo urlencode($sort_column); ?>&order=<?php echo urlencode($sort_order); ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $car_type ? '&car_type=' . urlencode($car_type) : ''; ?><?php echo $status ? '&status=' . urlencode($status) : ''; ?><?php echo $transmission ? '&transmission=' . urlencode($transmission) : ''; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if($end_page < $total_pages): ?>
                <?php if($end_page < $total_pages - 1): ?>
                    <span>...</span>
                <?php endif; ?>
                <a href="?page=<?php echo $total_pages; ?>&sort=<?php echo urlencode($sort_column); ?>&order=<?php echo urlencode($sort_order); ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $car_type ? '&car_type=' . urlencode($car_type) : ''; ?><?php echo $status ? '&status=' . urlencode($status) : ''; ?><?php echo $transmission ? '&transmission=' . urlencode($transmission) : ''; ?>">
                    <?php echo $total_pages; ?>
                </a>
            <?php endif; ?>
            
            <?php if($page < $total_pages): ?>
                <a href="?page=<?php echo $page+1; ?>&sort=<?php echo urlencode($sort_column); ?>&order=<?php echo urlencode($sort_order); ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $car_type ? '&car_type=' . urlencode($car_type) : ''; ?><?php echo $status ? '&status=' . urlencode($status) : ''; ?><?php echo $transmission ? '&transmission=' . urlencode($transmission) : ''; ?>">
                    Next <i class="fas fa-chevron-right"></i>
                </a>
            <?php else: ?>
                <span class="disabled">Next <i class="fas fa-chevron-right"></i></span>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <div class="info-text">
            Showing <?php echo count($cars); ?> of <?php echo $total_cars; ?> cars
        </div>
    </div>
    
    <!-- Car History Modal (2 Columns: Reservations + Maintenance) -->
    <div id="historyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-history"></i> Car History</h3>
                <span class="close-modal" onclick="closeHistoryModal()">&times;</span>
            </div>
            <div class="modal-body" id="historyContent">
                <div class="history-loading">
                    <i class="fas fa-spinner fa-spin" style="font-size: 32px; color: #0066cc;"></i>
                    <p style="margin-top: 12px;">Loading history...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeHistoryModal()" style="background: #6b7280; color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer;">Close</button>
            </div>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content" style="max-width: 450px;">
            <div class="modal-header" style="background: #dc2626;">
                <h3 style="color:white;"><i class="fas fa-exclamation-triangle"></i> Delete Car?</h3>
                <span class="close-modal" onclick="closeDeleteModal()" style="color:rgba(255,255,255,0.7);">&times;</span>
            </div>
            <div class="modal-body" style="text-align:center;">
                <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626; margin-bottom: 16px;"></i>
                <p id="deleteCarName" style="color: #6b7280; font-size: 16px; margin-bottom: 12px;"></p>
                <div id="deleteGroupWarning" style="display: none; background: #fef3c7; padding: 12px; border-radius: 8px; margin-bottom: 16px; font-size: 13px; color: #92400e;">
                    <i class="fas fa-info-circle"></i> <span id="deleteGroupWarningText"></span>
                </div>
                <p style="font-size: 13px; color: #dc2626; margin-bottom: 20px;">This will also delete all price rules, images, and maintenance records for this car. This action cannot be undone!</p>
                <div style="display: flex; gap: 12px; justify-content: center;">
                    <button onclick="closeDeleteModal()" class="btn-secondary" style="background: #6b7280; color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer;">Cancel</button>
                    <a id="deleteConfirmLink" href="#" class="btn-delete" style="background: #dc2626; color: white; padding: 10px 20px; border-radius: 8px; text-decoration: none;">Delete Car</a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Blocked: Primary with Clones Modal -->
    <div id="primaryWithClonesModal" class="blocked-modal-overlay">
        <div class="blocked-modal">
            <div class="modal-icon" style="color:#f59e0b;">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <h3 style="color:#92400e;">Nuk mund të fshihet!</h3>
            <div class="car-name" id="primaryWithClonesCarName">-</div>
            <p>
                <strong>Kjo makinë është primare dhe ka <span id="cloneCountDisplay">0</span> makina të klonuara që varen nga ajo.</strong><br><br>
                Makinat e klonuara marrin foton dhe të dhënat nga kjo makinë primare.<br><br>
                <strong>Ju lutemi së pari fshini makinat e klonuara, pastaj këtë makinë.</strong>
            </p>
            <div class="modal-actions">
                <button class="btn-close-blocked" onclick="closePrimaryWithClonesModal()" style="background:#f59e0b; color:white;">
                    <i class="fas fa-times"></i> Kuptova
                </button>
            </div>
        </div>
    </div>
    
    <!-- Blocked: Reservation Modal -->
    <div id="reservationBlockedModal" class="blocked-modal-overlay">
        <div class="blocked-modal">
            <div class="modal-icon">
                <i class="fas fa-lock"></i>
            </div>
            <h3>Nuk mund të fshihet!</h3>
            <div class="car-name" id="reservationBlockedCarName">-</div>
            <p>
                Kjo makinë ka rezervime aktive ose të ardhshme dhe nuk mund të fshihet.<br><br>
                <strong>Ju lutemi fshini ose anuloni rezervimet përpara se të fshini makinën.</strong>
            </p>
            <div class="modal-actions">
                <a href="reservations.php" target="_blank" class="btn-view-reservations">
                    <i class="fas fa-calendar-check"></i> Shiko Rezervimet
                </a>
                <button class="btn-close-blocked" onclick="closeReservationBlockedModal()">
                    <i class="fas fa-times"></i> Mbyll
                </button>
            </div>
        </div>
    </div>
    
    <!-- Clone Car Modal -->
    <div id="cloneModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center;">
        <div style="background: white; border-radius: 16px; max-width: 420px; width: 90%; padding: 24px;">
            <i class="fas fa-copy" style="font-size: 40px; color: #f59e0b; margin-bottom: 12px; display:block; text-align:center;"></i>
            <h3 style="margin-bottom: 6px; text-align:center;">Shto makinë identike</h3>
            <p id="cloneCarName" style="color: #6b7280; margin-bottom: 18px; text-align:center;"></p>
            <form method="POST" id="cloneForm">
                <input type="hidden" name="clone_car" value="1">
                <input type="hidden" name="source_car_id" id="cloneSourceId" value="">
                <label style="display:block; font-size:13px; font-weight:600; margin-bottom:6px;">Targa e makinës së re</label>
                <input type="text" name="new_license_plate" id="cloneNewPlate" required placeholder="p.sh. AA 123 BC" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; margin-bottom:18px; font-size:14px;">
                <p style="font-size:12px; color:#6b7280; margin-bottom:18px;">Çdo gjë tjetër (brand, model, foto, specifikat, çmimi) kopjohet automatikisht nga makina origjinale. Vetëm targa do të jetë e ndryshme.</p>
                <div style="display: flex; gap: 12px; justify-content: center;">
                    <button type="button" onclick="closeCloneModal()" class="btn-secondary" style="background: #6b7280; color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer;">Anulo</button>
                    <button type="submit" class="btn-clone" style="padding: 10px 20px; border-radius: 8px; font-size:14px;">Shto Makinën</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        let currentCarId = null;
        let currentReservationPage = 1;
        let totalReservationPages = 1;
        let currentMaintenancePage = 1;
        let totalMaintenancePages = 1;
        let currentCarName = '';
        let currentCarPlate = '';
        
        // ============================================
        // MODALET E BLLOKIMIT
        // ============================================
        
        function showPrimaryWithClonesBlocked(carName, cloneCount) {
            document.getElementById('primaryWithClonesCarName').innerText = carName;
            document.getElementById('cloneCountDisplay').innerText = cloneCount;
            document.getElementById('primaryWithClonesModal').classList.add('show');
        }
        
        function closePrimaryWithClonesModal() {
            document.getElementById('primaryWithClonesModal').classList.remove('show');
        }
        
        function showReservationBlockedModal(carName) {
            document.getElementById('reservationBlockedCarName').innerText = carName;
            document.getElementById('reservationBlockedModal').classList.add('show');
        }
        
        function closeReservationBlockedModal() {
            document.getElementById('reservationBlockedModal').classList.remove('show');
        }
        
        function resetFilters() {
            window.location.href = 'cars.php';
        }
        
        function showCarMaintenance(carId, carName, carPlate) {
            currentCarId = carId;
            currentCarName = carName;
            currentCarPlate = carPlate;
            currentReservationPage = 1;
            currentMaintenancePage = 1;
            
            const modalContent = document.getElementById('historyContent');
            modalContent.innerHTML = '<div class="history-loading"><i class="fas fa-spinner fa-spin" style="font-size: 32px; color: #0066cc;"></i><p style="margin-top: 12px;">Loading history...</p></div>';
            document.getElementById('historyModal').style.display = 'flex';
            
            setTimeout(loadFullHistoryContent, 300);
        }
        
        function loadFullHistoryContent() {
            let html = `
                <div class="car-info-card">
                    <div class="car-icon"><i class="fas fa-car"></i></div>
                    <div class="car-details">
                        <h4>${escapeHtml(currentCarName)}</h4>
                        <p><i class="fas fa-tag"></i> License Plate: <strong>${escapeHtml(currentCarPlate)}</strong></p>
                    </div>
                    <div class="car-stats">
                        <i class="fas fa-calendar-alt"></i> Reservations & Maintenance
                    </div>
                </div>
                
                <div class="history-two-columns">
                    <div class="history-column">
                        <div class="history-column-header">
                            <span><i class="fas fa-calendar-check"></i> Reservations</span>
                            <span class="badge-count" id="reservationCount">Loading...</span>
                        </div>
                        <div class="history-column-body" id="reservationHistoryContainer">
                            <div class="history-loading"><i class="fas fa-spinner fa-spin"></i> Loading...</div>
                        </div>
                    </div>
                    <div class="history-column">
                        <div class="history-column-header">
                            <span><i class="fas fa-tools"></i> Maintenance</span>
                            <span class="badge-count" id="maintenanceCount">Loading...</span>
                        </div>
                        <div class="history-column-body" id="maintenanceHistoryContainer">
                            <div class="history-loading"><i class="fas fa-spinner fa-spin"></i> Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('historyContent').innerHTML = html;
            
            loadReservationHistory(1);
            loadMaintenanceHistory(1);
        }
        
        function loadReservationHistory(page) {
            fetch(`?ajax=1&car_history=${currentCarId}&history_page=${page}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success) {
                        currentReservationPage = data.current_page;
                        totalReservationPages = data.total_pages;
                        renderReservationHistory(data);
                    }
                })
                .catch(err => console.error('Reservation history error:', err));
        }
        
        function loadMaintenanceHistory(page) {
            fetch(`?ajax=1&get_maintenance=${currentCarId}&page=${page}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success) {
                        currentMaintenancePage = data.current_page;
                        totalMaintenancePages = data.total_pages;
                        renderMaintenanceHistory(data);
                    }
                })
                .catch(err => console.error('Maintenance history error:', err));
        }
        
        function renderReservationHistory(data) {
            let container = document.getElementById('reservationHistoryContainer');
            if(!container) return;
            
            let badge = document.getElementById('reservationCount');
            if(badge) badge.innerText = data.total_count;
            
            let html = '';
            
            if(data.reservations && data.reservations.length > 0) {
                html += `
                    <div style="overflow-x: auto;">
                        <table class="history-table">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Customer</th>
                                    <th>Phone</th>
                                    <th>Pickup</th>
                                    <th>Return</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                data.reservations.forEach(r => {
                    let totalDisplay = r.grand_total ? parseFloat(r.grand_total).toFixed(2) : (r.total_price ? parseFloat(r.total_price).toFixed(2) : '0');
                    let statusClass = getStatusClass(r.status);
                    let paymentClass = getPaymentClass(r.payment_status);
                    
                    let tabParam = '';
                    if (r.status === 'completed' && r.payment_status === 'paid') {
                        tabParam = '&tab=completed';
                    } else {
                        tabParam = '&tab=active';
                    }
                    
                    html += `
                        <tr>
                            <td class="history-badge">${escapeHtml(r.reservation_code)}</td>
                            <td><strong>${escapeHtml(r.customer_name)}</strong></td>
                            <td>${escapeHtml(r.customer_phone)}</td>
                            <td>${r.pickup_date}<br><small>${r.pickup_time ? r.pickup_time.substring(0,5) : '-'}</small></td>
                            <td>${r.dropoff_date}<br><small>${r.dropoff_time ? r.dropoff_time.substring(0,5) : '-'}</small></td>
                            <td>€${totalDisplay}</td>
                            <td>
                                <span class="res-status-badge ${statusClass}">${r.status}</span>
                                <br>
                                <span class="res-status-badge ${paymentClass}">${r.payment_status == 'partial' ? 'Partial' : (r.payment_status == 'paid' ? 'Paid' : 'Unpaid')}</span>
                            </td>
                            <td>
                                <a href="reservations.php?search=${encodeURIComponent(r.reservation_code)}${tabParam}" class="btn-sm" target="_blank">
                                    <i class="fas fa-eye"></i> View
                                </a>
                            </td>
                        </tr>
                    `;
                });
                
                html += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                html += `
                    <div class="empty-history">
                        <i class="fas fa-calendar-times"></i>
                        <p>No reservations found for this car</p>
                    </div>
                `;
            }
            
            if(totalReservationPages > 1) {
                html += '<div class="history-pagination">';
                if(currentReservationPage > 1) {
                    html += `<a onclick="loadReservationHistory(${currentReservationPage - 1})"><i class="fas fa-chevron-left"></i></a>`;
                } else {
                    html += `<span class="disabled"><i class="fas fa-chevron-left"></i></span>`;
                }
                
                let startPage = Math.max(1, currentReservationPage - 2);
                let endPage = Math.min(totalReservationPages, currentReservationPage + 2);
                for(let i = startPage; i <= endPage; i++) {
                    if(i === currentReservationPage) {
                        html += `<span class="active">${i}</span>`;
                    } else {
                        html += `<a onclick="loadReservationHistory(${i})">${i}</a>`;
                    }
                }
                
                if(currentReservationPage < totalReservationPages) {
                    html += `<a onclick="loadReservationHistory(${currentReservationPage + 1})"><i class="fas fa-chevron-right"></i></a>`;
                } else {
                    html += `<span class="disabled"><i class="fas fa-chevron-right"></i></span>`;
                }
                html += '</div>';
            }
            
            container.innerHTML = html;
        }
        
        function renderMaintenanceHistory(data) {
            let container = document.getElementById('maintenanceHistoryContainer');
            if(!container) return;
            
            let badge = document.getElementById('maintenanceCount');
            if(badge) badge.innerText = data.total;
            
            let html = '';
            
            <?php if(!$is_worker): ?>
            html += `
                <div class="maintenance-add-section">
                    <h4 onclick="toggleMaintForm()">
                        <i class="fas fa-plus-circle toggle-icon" id="maintToggleIcon"></i> 
                        Add Maintenance Record
                    </h4>
                    <div class="maint-form-wrapper" id="maintFormWrapper">
                        <form method="POST">
                            <input type="hidden" name="car_id" value="${currentCarId}">
                            <div class="maint-form-row">
                                <div class="maint-form-group">
                                    <label>Service Type *</label>
                                    <input type="text" name="service_type" placeholder="e.g., Oil Change, Brake Pads, Tire Change..." required>
                                </div>
                                <div class="maint-form-group">
                                    <label>Service Date *</label>
                                    <input type="date" name="service_date" value="${new Date().toISOString().split('T')[0]}" required>
                                </div>
                            </div>
                            <div class="maint-form-group">
                                <label>Description *</label>
                                <input type="text" name="description" placeholder="Brief description of work done" required>
                            </div>
                            <div class="maint-form-row">
                                <div class="maint-form-group">
                                    <label>Cost (€)</label>
                                    <input type="number" step="0.01" name="cost" placeholder="0.00">
                                </div>
                                <div class="maint-form-group">
                                    <label>Performed By</label>
                                    <input type="text" name="performed_by" placeholder="Mechanic name">
                                </div>
                            </div>
                            <div class="maint-form-group">
                                <label>Notes</label>
                                <textarea name="notes" rows="2" placeholder="Additional notes..."></textarea>
                            </div>
                            <button type="submit" name="add_maintenance" class="btn-add-maint">
                                <i class="fas fa-save"></i> Add Maintenance Record
                            </button>
                        </form>
                    </div>
                </div>
            `;
            <?php else: ?>
            html += `
                <div class="maintenance-add-section disabled" style="opacity:0.6; pointer-events:none;">
                    <h4>
                        <i class="fas fa-lock"></i> 
                        Add Maintenance Record (Worker - View Only)
                    </h4>
                    <div style="padding:10px; background:#fef3c7; border-radius:8px; font-size:12px; color:#92400e;">
                        <i class="fas fa-info-circle"></i> Only admins can add maintenance records.
                    </div>
                </div>
            `;
            <?php endif; ?>
            
            if(data.maintenance && data.maintenance.length > 0) {
                html += `
                    <div style="overflow-x: auto;">
                        <table class="history-table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Service Type</th>
                                    <th>Description</th>
                                    <th>Cost</th>
                                    <th>Performed By</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                data.maintenance.forEach(m => {
                    html += `
                        <tr>
                            <td>${m.service_date}</td>
                            <td><strong>${escapeHtml(m.service_type)}</strong></td>
                            <td>${escapeHtml(m.description)}</td>
                            <td>${m.cost > 0 ? '€' + parseFloat(m.cost).toFixed(2) : '-'}</td>
                            <td>${escapeHtml(m.performed_by ? m.performed_by : '-')}</td>
                        </tr>
                    `;
                });
                
                html += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                html += `
                    <div class="empty-history">
                        <i class="fas fa-tools"></i>
                        <p>No maintenance records found for this car</p>
                    </div>
                `;
            }
            
            if(totalMaintenancePages > 1) {
                html += '<div class="history-pagination">';
                if(currentMaintenancePage > 1) {
                    html += `<a onclick="loadMaintenanceHistory(${currentMaintenancePage - 1})"><i class="fas fa-chevron-left"></i></a>`;
                } else {
                    html += `<span class="disabled"><i class="fas fa-chevron-left"></i></span>`;
                }
                
                let startPage = Math.max(1, currentMaintenancePage - 2);
                let endPage = Math.min(totalMaintenancePages, currentMaintenancePage + 2);
                for(let i = startPage; i <= endPage; i++) {
                    if(i === currentMaintenancePage) {
                        html += `<span class="active">${i}</span>`;
                    } else {
                        html += `<a onclick="loadMaintenanceHistory(${i})">${i}</a>`;
                    }
                }
                
                if(currentMaintenancePage < totalMaintenancePages) {
                    html += `<a onclick="loadMaintenanceHistory(${currentMaintenancePage + 1})"><i class="fas fa-chevron-right"></i></a>`;
                } else {
                    html += `<span class="disabled"><i class="fas fa-chevron-right"></i></span>`;
                }
                html += '</div>';
            }
            
            container.innerHTML = html;
        }
        
        function toggleMaintForm() {
            const wrapper = document.getElementById('maintFormWrapper');
            const icon = document.getElementById('maintToggleIcon');
            if(wrapper) {
                wrapper.classList.toggle('open');
            }
            if(icon) {
                icon.classList.toggle('rotated');
            }
        }
        
        function getStatusClass(status) {
            switch(status) {
                case 'pending': return 'status-pending';
                case 'confirmed': return 'status-confirmed';
                case 'running': return 'status-running';
                case 'completed': return 'status-completed';
                case 'cancelled': return 'status-cancelled';
                default: return 'status-pending';
            }
        }
        
        function getPaymentClass(payment_status) {
            switch(payment_status) {
                case 'paid': return 'payment-paid';
                case 'partial': return 'payment-partial';
                default: return 'payment-unpaid';
            }
        }
        
        function closeHistoryModal() {
            document.getElementById('historyModal').style.display = 'none';
            currentCarId = null;
        }
        
        let deleteId = null;
        let deleteName = '';
        let deleteIsGroup = false;
        let deleteGroupCount = 0;
        let deleteIsPrimary = false;
        
        function confirmDelete(id, name, isGroup, groupCount, isPrimary) {
            deleteId = id;
            deleteName = name;
            deleteIsGroup = isGroup || false;
            deleteGroupCount = groupCount || 0;
            deleteIsPrimary = isPrimary || false;
            
            let url = '?delete_id=' + id;
            <?php if($search): ?>
            url += '&search=' + encodeURIComponent('<?php echo addslashes($search); ?>');
            <?php endif; ?>
            <?php if($car_type): ?>
            url += '&car_type=' + encodeURIComponent('<?php echo addslashes($car_type); ?>');
            <?php endif; ?>
            <?php if($status): ?>
            url += '&status=' + encodeURIComponent('<?php echo addslashes($status); ?>');
            <?php endif; ?>
            <?php if($transmission): ?>
            url += '&transmission=' + encodeURIComponent('<?php echo addslashes($transmission); ?>');
            <?php endif; ?>
            <?php if($sort_column != 'id' || $sort_order != 'DESC'): ?>
            url += '&sort=' + encodeURIComponent('<?php echo addslashes($sort_column); ?>');
            url += '&order=' + encodeURIComponent('<?php echo addslashes($sort_order); ?>');
            <?php endif; ?>
            <?php if($page > 1): ?>
            url += '&page=' + <?php echo $page; ?>;
            <?php endif; ?>
            
            document.getElementById('deleteConfirmLink').href = url;
            document.getElementById('deleteCarName').innerHTML = '<strong>' + name + '</strong>';
            
            const warningDiv = document.getElementById('deleteGroupWarning');
            const warningText = document.getElementById('deleteGroupWarningText');
            
            if (deleteIsGroup && deleteGroupCount > 1) {
                if (deleteIsPrimary) {
                    warningText.innerHTML = '⚠️ <strong>Kjo është makina kryesore (primare) e grupit me ' + deleteGroupCount + ' makina identike.</strong> Nëse e fshini, një makinë tjetër nga grupi do të bëhet automatikisht primare.';
                } else {
                    warningText.innerHTML = '⚠️ Kjo makinë është pjesë e një grupi me ' + deleteGroupCount + ' makina identike. Fshirja e saj nuk ndikon tek makinat e tjera të grupit.';
                }
                warningDiv.style.display = 'block';
            } else {
                warningDiv.style.display = 'none';
            }
            
            document.getElementById('deleteModal').style.display = 'flex';
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
        }
        
        function openCloneModal(carId, carName) {
            <?php if($is_worker): ?>
            alert('Workers cannot clone cars.');
            return;
            <?php endif; ?>
            
            document.getElementById('cloneSourceId').value = carId;
            document.getElementById('cloneNewPlate').value = '';
            document.getElementById('cloneCarName').innerHTML = 'Krijo një kopje identike të <strong>' + carName + '</strong>';
            document.getElementById('cloneModal').style.display = 'flex';
        }
        
        function closeCloneModal() {
            document.getElementById('cloneModal').style.display = 'none';
        }
        
        function escapeHtml(text) {
            if(!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        window.onclick = function(event) {
            const historyModal = document.getElementById('historyModal');
            const deleteModal = document.getElementById('deleteModal');
            const primaryModal = document.getElementById('primaryWithClonesModal');
            const reservationModal = document.getElementById('reservationBlockedModal');
            
            if(event.target == historyModal) {
                closeHistoryModal();
            }
            if(event.target == deleteModal) {
                closeDeleteModal();
            }
            if(event.target == primaryModal) {
                closePrimaryWithClonesModal();
            }
            if(event.target == reservationModal) {
                closeReservationBlockedModal();
            }
        }
        
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closePrimaryWithClonesModal();
                closeReservationBlockedModal();
                closeDeleteModal();
                closeHistoryModal();
            }
        });
    </script>
</body>
</html>