<?php
session_start();

// Vendos zonën kohore të Shqipërisë
date_default_timezone_set('Europe/Tirane');

$host = 'localhost';
$dbname = 'escal_2b';
$username = 'escal_2b';
$password = 'Bkasxh12.';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    $pdo->exec("SET NAMES utf8mb4");
    $pdo->exec("SET CHARACTER SET utf8mb4");
    $pdo->exec("SET character_set_connection=utf8mb4");
    $pdo->exec("SET character_set_client=utf8mb4");
    $pdo->exec("SET character_set_results=utf8mb4");
    
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

define('SITE_URL', 'http://rent.esc.al/');
define('PREPARATION_HOURS', 2);

// ============================================
// MULTI-LANGUAGE SUPPORT
// ============================================

// Detect and set language
function detectLanguage() {
    // Check URL parameter first
    if(isset($_GET['lang'])) {
        $lang = $_GET['lang'];
        $allowed = ['en', 'de', 'pl', 'cs', 'no'];
        if(in_array($lang, $allowed)) {
            $_SESSION['lang'] = $lang;
            return $lang;
        }
    }
    
    // Check session
    if(isset($_SESSION['lang'])) {
        return $_SESSION['lang'];
    }
    
    // Check browser language (simplified)
    if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $browser_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
        $allowed = ['en', 'de', 'pl', 'cs', 'no'];
        if(in_array($browser_lang, $allowed)) {
            $_SESSION['lang'] = $browser_lang;
            return $browser_lang;
        }
    }
    
    // Default: English
    $_SESSION['lang'] = 'en';
    return 'en';
}

// Load language file
function loadLanguage($lang) {
    $lang_file = __DIR__ . '/../lang/' . $lang . '.php';
    if(file_exists($lang_file)) {
        return include $lang_file;
    }
    // Fallback to English
    $fallback_file = __DIR__ . '/../lang/en.php';
    if(file_exists($fallback_file)) {
        return include $fallback_file;
    }
    return [];
}

// Global translation function
function t($key, $default = '') {
    global $lang_data;
    if(!isset($lang_data) || !is_array($lang_data)) {
        $lang_data = [];
    }
    return isset($lang_data[$key]) ? $lang_data[$key] : ($default ?: $key);
}

// Get available languages
function getAvailableLanguages() {
    return [
        'en' => ['name' => 'English', 'flag' => '🇬🇧', 'code' => 'en'],
        'de' => ['name' => 'Deutsch', 'flag' => '🇩🇪', 'code' => 'de'],
        'pl' => ['name' => 'Polski', 'flag' => '🇵🇱', 'code' => 'pl'],
        'cs' => ['name' => 'Čeština', 'flag' => '🇨🇿', 'code' => 'cs'],
        'no' => ['name' => 'Norsk', 'flag' => '🇳🇴', 'code' => 'no'],
    ];
}

// Get current language
function getCurrentLanguage() {
    return isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en';
}

// Initialize language
$current_lang = detectLanguage();
$_SESSION['lang'] = $current_lang;
$lang_data = loadLanguage($current_lang);
$available_languages = getAvailableLanguages();

// ============================================
// CREATE THUMBNAIL FUNCTION
// ============================================
function createThumbnail($source_path, $target_path, $width = 150) {
    if(!extension_loaded('gd')) {
        return false;
    }
    
    $image_info = @getimagesize($source_path);
    if(!$image_info) return false;
    
    $mime_type = $image_info['mime'];
    $source_width = $image_info[0];
    $source_height = $image_info[1];
    
    switch($mime_type) {
        case 'image/jpeg':
        case 'image/jpg':
            $source = @imagecreatefromjpeg($source_path);
            break;
        case 'image/png':
            $source = @imagecreatefrompng($source_path);
            break;
        case 'image/gif':
            $source = @imagecreatefromgif($source_path);
            break;
        case 'image/webp':
            if(function_exists('imagecreatefromwebp')) {
                $source = @imagecreatefromwebp($source_path);
            } else {
                return false;
            }
            break;
        default:
            return false;
    }
    
    if(!$source) return false;
    
    $ratio = $width / $source_width;
    $new_width = $width;
    $new_height = round($source_height * $ratio);
    
    $thumbnail = imagecreatetruecolor($new_width, $new_height);
    
    if($mime_type == 'image/png' || $mime_type == 'image/gif') {
        imagealphablending($thumbnail, false);
        imagesavealpha($thumbnail, true);
        $transparent = imagecolorallocatealpha($thumbnail, 0, 0, 0, 127);
        imagefilledrectangle($thumbnail, 0, 0, $new_width, $new_height, $transparent);
    } else {
        $white = imagecolorallocate($thumbnail, 255, 255, 255);
        imagefilledrectangle($thumbnail, 0, 0, $new_width, $new_height, $white);
    }
    
    imagecopyresampled($thumbnail, $source, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
    
    $target_dir = dirname($target_path);
    if(!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    switch($mime_type) {
        case 'image/jpeg':
        case 'image/jpg':
            $result = imagejpeg($thumbnail, $target_path, 75);
            break;
        case 'image/png':
            $result = imagepng($thumbnail, $target_path, 6);
            break;
        case 'image/gif':
            $result = imagegif($thumbnail, $target_path);
            break;
        case 'image/webp':
            if(function_exists('imagewebp')) {
                $result = imagewebp($thumbnail, $target_path, 75);
            } else {
                $result = false;
            }
            break;
        default:
            $result = false;
    }
    
    imagedestroy($source);
    imagedestroy($thumbnail);
    return $result;
}

// ============================================
// DELETE CAR IMAGES
// ============================================
function deleteCarImages($image_url) {
    if(empty($image_url)) return true;
    
    $base_path = '../' . $image_url;
    $thumb_path = str_replace('uploads/', 'uploads/thumbnails/', $base_path);
    
    $deleted = true;
    
    if(file_exists($base_path)) {
        if(!unlink($base_path)) {
            $deleted = false;
        }
    }
    
    if(file_exists($thumb_path)) {
        if(!unlink($thumb_path)) {
            $deleted = false;
        }
    }
    
    return $deleted;
}

// ============================================
// SETTINGS FUNCTIONS
// ============================================
function getSetting($key, $pdo, $default = '') {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ? AND is_active = 1");
        $stmt->execute([$key]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['setting_value'] : $default;
    } catch (PDOException $e) {
        return $default;
    }
}

// ============================================
// INSURANCE & EXTRAS FUNCTIONS
// ============================================
function getInsuranceTypes($pdo, $activeOnly = true) {
    $sql = "SELECT * FROM insurance_types";
    if($activeOnly) $sql .= " WHERE is_active = 1";
    $sql .= " ORDER BY sort_order, id";
    return $pdo->query($sql)->fetchAll();
}

function getAdditionalOptions($pdo, $activeOnly = true) {
    $sql = "SELECT * FROM additional_options";
    if($activeOnly) $sql .= " WHERE is_active = 1";
    $sql .= " ORDER BY sort_order, id";
    return $pdo->query($sql)->fetchAll();
}

function calculateExtrasTotal($insurance_id, $selected_options, $days, $pdo) {
    $total = 0;
    $selected_insurance_price = 0;
    
    if($insurance_id) {
        $stmt = $pdo->prepare("SELECT price_per_day, price_one_time, is_daily FROM insurance_types WHERE id = ?");
        $stmt->execute([$insurance_id]);
        $insurance = $stmt->fetch();
        if($insurance) {
            if($insurance['is_daily']) {
                $selected_insurance_price = ($insurance['price_per_day'] ?: 0) * $days;
            } else {
                $selected_insurance_price = $insurance['price_one_time'] ?: 0;
            }
            $total += $selected_insurance_price;
        }
    }
    
    $options_data = [];
    if(!empty($selected_options)) {
        $options_array = is_string($selected_options) ? json_decode($selected_options, true) : $selected_options;
        if(is_array($options_array)) {
            foreach($options_array as $opt) {
                $stmt = $pdo->prepare("SELECT price_per_day, price_one_time, is_daily, name FROM additional_options WHERE id = ?");
                $stmt->execute([$opt['id']]);
                $option = $stmt->fetch();
                if($option) {
                    $qty = $opt['quantity'] ?? 1;
                    if($option['is_daily']) {
                        $cost = ($option['price_per_day'] ?: 0) * $days * $qty;
                    } else {
                        $cost = ($option['price_one_time'] ?: 0) * $qty;
                    }
                    $total += $cost;
                    $options_data[] = [
                        'id' => $opt['id'],
                        'name' => $option['name'],
                        'quantity' => $qty,
                        'price' => $cost,
                        'is_daily' => $option['is_daily'],
                        'price_per_day' => $option['price_per_day'],
                        'price_one_time' => $option['price_one_time']
                    ];
                }
            }
        }
    }
    
    return [
        'extras_total' => round($total, 2),
        'selected_insurance_price' => round($selected_insurance_price, 2),
        'options_data' => $options_data
    ];
}

// ============================================
// RESERVATION FUNCTIONS
// ============================================
function generateReservationCode($pdo) {
    $year = date('Y');
    $prefix = "RENT-{$year}-";
    
    try {
        $stmt = $pdo->prepare("
            SELECT MAX(CAST(SUBSTRING(reservation_code, -4) AS UNSIGNED)) as max_num 
            FROM reservations 
            WHERE reservation_code LIKE ?
        ");
        $stmt->execute([$prefix . '%']);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $max_num = $result['max_num'] ?? 0;
        $new_num = $max_num + 1;
        
        if($new_num > 9999) {
            $new_num = 1;
        }
        
        $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE reservation_code = ?");
        $new_code = $prefix . str_pad($new_num, 4, '0', STR_PAD_LEFT);
        $check_stmt->execute([$new_code]);
        $exists = $check_stmt->fetchColumn();
        
        while($exists > 0 && $new_num < 9999) {
            $new_num++;
            $new_code = $prefix . str_pad($new_num, 4, '0', STR_PAD_LEFT);
            $check_stmt->execute([$new_code]);
            $exists = $check_stmt->fetchColumn();
        }
        
        return $new_code;
        
    } catch (PDOException $e) {
        return $prefix . date('YmdHis') . rand(100, 999);
    }
}

// ============================================
// CALCULATE DAYS BASED ON 24-HOUR PERIODS
// ============================================
function getDaysBetween($start_date, $start_time, $end_date, $end_time) {
    try {
        $start = new DateTime($start_date . ' ' . $start_time);
        $end = new DateTime($end_date . ' ' . $end_time);
        
        // Nese koha e kthimit eshte para ose e barabarte me kohen e marrjes
        if ($end <= $start) {
            return 0;
        }
        
        // Llogarit diferencen ne sekonda
        $diff_seconds = $end->getTimestamp() - $start->getTimestamp();
        
        // Llogarit sa ore kane kaluar
        $hours = $diff_seconds / 3600;
        
        // Rrumbullakos lart (ceil) - nese ka kaluar 24 ore e 1 minut, behen 2 dite
        $days = ceil($hours / 24);
        
        return max(1, $days); // Sigurohemi qe te kthehet te pakten 1 dite
        
    } catch (Exception $e) {
        return 1;
    }
}

// ============================================
// CAR & PRICE FUNCTIONS
// ============================================
function getCarBasePrice($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT fixed_price FROM price_rules 
                               WHERE car_id = ? AND rule_type = 'base_price' AND is_active = 1
                               LIMIT 1");
        $stmt->execute([$car_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? (float)$result['fixed_price'] : 50;
    } catch (PDOException $e) {
        return 50;
    }
}

function calculateDynamicPrice($car_id, $start_date, $start_time, $end_date, $end_time, $pdo) {
    $days = getDaysBetween($start_date, $start_time, $end_date, $end_time);
    
    try {
        $stmt = $pdo->prepare("
            SELECT * FROM price_rules 
            WHERE car_id = ? AND is_active = 1 
            ORDER BY priority DESC, id DESC
        ");
        $stmt->execute([$car_id]);
        $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $rules = [];
    }
    
    $base_price = 50;
    foreach($rules as $rule) {
        if($rule['rule_type'] == 'base_price') {
            $base_price = (float)$rule['fixed_price'];
            break;
        }
    }
    
    // Llogarit totalin bazuar ne ditet e llogaritura me 24-ore
    $total = $base_price * $days;
    
    // Apliko zbritjet (weekly, monthly) nese ka
    $discount_percent = 0;
    foreach($rules as $rule) {
        if($rule['rule_type'] == 'weekly_discount' && $days >= (int)$rule['min_days']) {
            $discount_percent = max($discount_percent, (float)$rule['discount_percent']);
        }
        if($rule['rule_type'] == 'monthly_discount' && $days >= (int)$rule['min_days']) {
            $discount_percent = max($discount_percent, (float)$rule['discount_percent']);
        }
        if($rule['rule_type'] == 'custom_period_discount' && $days >= (int)$rule['min_days']) {
            if($start_date <= $rule['end_date'] && $end_date >= $rule['start_date']) {
                $discount_percent = max($discount_percent, (float)$rule['discount_percent']);
            }
        }
    }
    
    $discount_amount = $total * ($discount_percent / 100);
    $total_price = $total - $discount_amount;
    
    return [
        'base_price' => round($base_price, 2),
        'days' => $days,
        'subtotal' => round($total, 2),
        'discount_percent' => $discount_percent,
        'discount_amount' => round($discount_amount, 2),
        'total_price' => round($total_price, 2)
    ];
}

// ============================================
// AVAILABILITY FUNCTION
// ============================================
function isCarAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, $exclude_id = null, $preparation_hours = PREPARATION_HOURS) {
    if(empty($pickup_date) || empty($dropoff_date)) {
        return ['available' => true, 'reason' => ''];
    }
    
    try {
        $pickup_datetime = new DateTime($pickup_date . ' ' . $pickup_time);
        $dropoff_datetime = new DateTime($dropoff_date . ' ' . $dropoff_time);
    } catch (Exception $e) {
        return ['available' => false, 'reason' => 'Invalid date format'];
    }
    
    if($pickup_datetime >= $dropoff_datetime) {
        return ['available' => false, 'reason' => 'Return date/time must be after pickup date/time'];
    }
    
    try {
        $sql = "SELECT id, pickup_date, pickup_time, dropoff_date, dropoff_time, status 
                FROM reservations 
                WHERE car_id = ? 
                AND status NOT IN ('cancelled')";
        
        if($exclude_id) {
            $sql .= " AND id != ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$car_id, $exclude_id]);
        } else {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$car_id]);
        }
        
        $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $reservations = [];
    }
    
    if(count($reservations) == 0) {
        return ['available' => true, 'reason' => ''];
    }
    
    foreach($reservations as $res) {
        try {
            $res_pickup = new DateTime($res['pickup_date'] . ' ' . $res['pickup_time']);
            $res_dropoff = new DateTime($res['dropoff_date'] . ' ' . $res['dropoff_time']);
        } catch (Exception $e) {
            continue;
        }
        
        $overlaps = ($pickup_datetime < $res_dropoff && $dropoff_datetime > $res_pickup);
        
        if($overlaps) {
            return [
                'available' => false, 
                'reason' => "This car is already booked for these dates."
            ];
        }
        
        if($pickup_date == $res['dropoff_date']) {
            $res_dropoff_datetime = new DateTime($res['dropoff_date'] . ' ' . $res['dropoff_time']);
            $available_from = clone $res_dropoff_datetime;
            $available_from->modify("+{$preparation_hours} hours");
            $available_from_str = $available_from->format('H:i');
            
            if($pickup_datetime < $available_from) {
                return [
                    'available' => false, 
                    'reason' => "Available for pickup after {$available_from_str} on {$pickup_date}"
                ];
            }
        }
        
        if($dropoff_date == $res['pickup_date']) {
            $res_pickup_datetime = new DateTime($res['pickup_date'] . ' ' . $res['pickup_time']);
            $must_return_by = clone $res_pickup_datetime;
            $must_return_by->modify("-{$preparation_hours} hours");
            $must_return_by_str = $must_return_by->format('H:i');
            
            if($dropoff_datetime > $must_return_by) {
                return [
                    'available' => false,
                    'reason' => "Car must be returned by {$must_return_by_str} or earlier on {$dropoff_date}"
                ];
            }
        }
    }
    
    return ['available' => true, 'reason' => ''];
}

// ============================================
// CAR GROUP FUNCTIONS (makina identike / të njejtit model)
// ============================================

// Kthen ID-n e "grupit" për një makinë (group_id nëse e ka, përndryshe id-ja e saj vetë)
function getCarGroupId($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT group_id FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($row && !empty($row['group_id'])) {
            return (int)$row['group_id'];
        }
        return (int)$car_id;
    } catch (PDOException $e) {
        return (int)$car_id;
    }
}

// Kthen të gjitha car_id e një grupi (përfshirë makinën primare), vetëm ato me status 'available'
function getCarsInGroup($group_id, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT id FROM cars 
            WHERE (id = ? OR group_id = ?) AND status = 'available'
            ORDER BY id ASC
        ");
        $stmt->execute([$group_id, $group_id]);
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (PDOException $e) {
        return [$group_id];
    }
}

// Si isCarAvailable(), por kontrollon TË GJITHA makinat identike të grupit.
// Nëse të paktën 1 është e lirë, kthen 'available' => true dhe 'assigned_car_id' => id-ja konkrete e lirë.
function isGroupAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, $exclude_id = null, $preparation_hours = PREPARATION_HOURS) {
    $group_id = getCarGroupId($car_id, $pdo);
    $car_ids = getCarsInGroup($group_id, $pdo);

    if(empty($car_ids)) {
        $car_ids = [$car_id];
    }

    $last_reason = 'Car is not available for the selected dates and times.';

    foreach($car_ids as $cid) {
        $result = isCarAvailable($cid, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, $exclude_id, $preparation_hours);
        if($result['available']) {
            return [
                'available' => true,
                'reason' => '',
                'assigned_car_id' => (int)$cid
            ];
        } else {
            $last_reason = $result['reason'];
        }
    }

    return [
        'available' => false,
        'reason' => $last_reason,
        'assigned_car_id' => null
    ];
}

// Gjen dhe kthen ID-n e një makine konkrete (targë reale) brenda grupit që është e lirë
// për datat e dhëna. Përdoret pikërisht para se të krijohet rezervimi.
function assignAvailableCarInGroup($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, $preparation_hours = PREPARATION_HOURS) {
    return isGroupAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, null, $preparation_hours);
}

// Kopjon te gjitha price_rules e makines primare (car_id) tek te gjitha makinat e tjera
// te te njejtit grup (sibling-at), qe te kete te njejtin çmim/rregulla si makina kryesore.
function syncGroupPriceRules($car_id, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT group_id FROM cars WHERE id = ?");
        $stmt->execute([$car_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $group_id = ($row && !empty($row['group_id'])) ? (int)$row['group_id'] : (int)$car_id;

        // gjej te gjithe "vellezerit" (te gjitha makinat e grupit, perveq vete makines primare)
        $sibl_stmt = $pdo->prepare("SELECT id FROM cars WHERE (id = ? OR group_id = ?) AND id != ?");
        $sibl_stmt->execute([$group_id, $group_id, $car_id]);
        $sibling_ids = $sibl_stmt->fetchAll(PDO::FETCH_COLUMN);

        if(empty($sibling_ids)) {
            return;
        }

        // merr te gjitha rregullat (aktive dhe joaktive) e makines primare
        $rules_stmt = $pdo->prepare("SELECT * FROM price_rules WHERE car_id = ?");
        $rules_stmt->execute([$car_id]);
        $rules = $rules_stmt->fetchAll(PDO::FETCH_ASSOC);

        $insert_stmt = $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($sibling_ids as $sid) {
            // fshi rregullat aktuale te makines "binjake" dhe rivendosi nga makina primare
            $pdo->prepare("DELETE FROM price_rules WHERE car_id = ?")->execute([$sid]);

            foreach($rules as $r) {
                $insert_stmt->execute([
                    $sid,
                    $r['rule_type'],
                    $r['start_date'],
                    $r['end_date'],
                    $r['fixed_price'],
                    $r['discount_percent'],
                    $r['min_days'],
                    $r['priority'],
                    $r['is_active']
                ]);
            }
        }
    } catch (PDOException $e) {
        // heshtazi anashkalo - sinkronizimi i çmimeve nuk duhet te ndaloje veprimin kryesor
    }
}

// ============================================
// SECURITY FUNCTIONS
// ============================================
function generateCSRFToken() {
    if(empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// ============================================
// CALENDAR FUNCTIONS
// ============================================
function getReservationsForCalendar($start_date, $end_date, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT car_id, pickup_date, dropoff_date, pickup_time, dropoff_time, 
                   status, id, customer_name, customer_phone, reservation_code
            FROM reservations 
            WHERE status != 'cancelled'
            AND pickup_date <= ? AND dropoff_date >= ?
            ORDER BY car_id, pickup_date
        ");
        $stmt->execute([$end_date, $start_date]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return [];
    }
}

function buildCalendarAvailability($cars, $reservations, $start_date, $end_date) {
    $fully_booked = [];
    $pickup_days = [];
    $dropoff_days = [];
    
    $date_range = [];
    $current = new DateTime($start_date);
    $end = new DateTime($end_date);
    while($current <= $end) {
        $date_range[$current->format('Y-m-d')] = true;
        $current->modify('+1 day');
    }
    
    foreach($reservations as $r) {
        $car_id = $r['car_id'];
        $pickup = $r['pickup_date'];
        $dropoff = $r['dropoff_date'];
        
        $current_date = new DateTime($pickup);
        $end_date_obj = new DateTime($dropoff);
        
        while($current_date <= $end_date_obj) {
            $current_date_str = $current_date->format('Y-m-d');
            
            if(!isset($date_range[$current_date_str])) {
                $current_date->modify('+1 day');
                continue;
            }
            
            if($current_date_str == $pickup) {
                $pickup_days[$car_id][$current_date_str] = [
                    'code' => $r['reservation_code'],
                    'time' => substr($r['pickup_time'], 0, 5)
                ];
            } elseif($current_date_str == $dropoff) {
                $dropoff_days[$car_id][$current_date_str] = [
                    'code' => $r['reservation_code'],
                    'time' => substr($r['dropoff_time'], 0, 5)
                ];
            } else {
                $fully_booked[$car_id][$current_date_str] = true;
            }
            
            $current_date->modify('+1 day');
        }
    }
    
    return [$fully_booked, $pickup_days, $dropoff_days];
}

function sendBookingEmail($to, $subject, $message) {
    return true;
}

function getBookingEmailTemplate($booking_data, $car_data) {
    return "";
}
?>