<?php
require_once 'includes/config.php';

header('Content-Type: application/json');

$car_id = isset($_GET['car_id']) ? (int)$_GET['car_id'] : 0;
$pickup_date = isset($_GET['pickup_date']) ? $_GET['pickup_date'] : '';
$pickup_time = isset($_GET['pickup_time']) ? $_GET['pickup_time'] : '10:00';
$dropoff_date = isset($_GET['dropoff_date']) ? $_GET['dropoff_date'] : '';
$dropoff_time = isset($_GET['dropoff_time']) ? $_GET['dropoff_time'] : '10:00';
$preparation_hours = isset($_GET['prep_hours']) ? (int)$_GET['prep_hours'] : PREPARATION_HOURS;
$exclude_id = isset($_GET['exclude_id']) ? (int)$_GET['exclude_id'] : 0;

if(!$car_id || !$pickup_date || !$dropoff_date) {
    echo json_encode(['available' => true, 'reason' => '']);
    exit;
}

// Validimi i datave
if($pickup_date > $dropoff_date) {
    echo json_encode(['available' => false, 'reason' => 'Return date must be after pickup date']);
    exit;
}

if($pickup_date == $dropoff_date && $pickup_time >= $dropoff_time) {
    echo json_encode(['available' => false, 'reason' => 'For the same day, return time must be after pickup time']);
    exit;
}

$exclude = $exclude_id ?: null;
$result = isGroupAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, $exclude, $preparation_hours);

// Nese nuk eshte i disponueshem dhe eshte nje konflikt i tipit "pickup pas dropoff", 
// sigurohemi qe mesazhi eshte i qarte
if(!$result['available'] && empty($result['reason'])) {
    $result['reason'] = 'Car is not available for the selected dates and times.';
}

echo json_encode($result);
?>