<?php
require_once __DIR__ . '/../../connect.php';

// استقبال البيانات
$driverId = filterRequest("id");
$phone = filterRequest("phone");
$gender = filterRequest("gender");
$name = filterRequest("name");
$name_english = filterRequest("name_english");
$address = filterRequest("address");
$religion = filterRequest("religion");
$age = filterRequest("age");
$startNameAddress = filterRequest("startNameAddress");
$locationCoordinate = filterRequest("locationCoordinate");
$education = filterRequest("education");
$license_type = filterRequest("license_type");
$national_number = filterRequest("national_number");
$car_plate = filterRequest("car_plate");
$make = filterRequest("make");
$model = filterRequest("model");
$year = filterRequest("year");
$color = filterRequest("color");
$color_hex = filterRequest("color_hex");
$token = filterRequest("token");
$rating = filterRequest("rating");
$countRide = filterRequest("countRide");
$passengerId = filterRequest("passengerId");
$timeSelected = filterRequest("timeSelected");
$status = filterRequest("status");

// 🔐 تشفير الحقول الحساسة
$phone = $encryptionHelper->encryptData($phone);
$gender = $encryptionHelper->encryptData($gender);
$name = $encryptionHelper->encryptData($name);
$name_english = $encryptionHelper->encryptData($name_english);
$car_plate = $encryptionHelper->encryptData($car_plate);
$token = $encryptionHelper->encryptData($token);
$education = $encryptionHelper->encryptData($education);
$national_number = $encryptionHelper->encryptData($national_number);
$age = $encryptionHelper->encryptData($age);

// ⏰ تحويل الوقت للفحص
$selectedTime = new DateTime($timeSelected);
$startTime = $selectedTime->format('Y-m-d H:i:s');
$endTime = $selectedTime->add(new DateInterval('PT6H'))->format('Y-m-d H:i:s');

// ✅ فحص هل السائق لديه أكثر من رحلتين خلال 6 ساعات
$sqlCheck = "SELECT COUNT(*) as trip_count 
             FROM `mishwaritrips` 
             WHERE `driverId` = :driverId
             AND `timeSelected` BETWEEN :startTime AND :endTime";
$stmtCheck = $con->prepare($sqlCheck);
$stmtCheck->bindParam(':driverId', $driverId);
$stmtCheck->bindParam(':startTime', $startTime);
$stmtCheck->bindParam(':endTime', $endTime);
$stmtCheck->execute();
$result = $stmtCheck->fetch(PDO::FETCH_ASSOC);

if ($result['trip_count'] >= 2) {
    jsonError("Driver already has 2 trips within the specified period.");
    exit;
}

// ✅ فحص إن الراكب لا يملك رحلة فعالة بنفس اليوم
$sqlCheckPassenger = "
SELECT * 
FROM `mishwaritrips`
WHERE `passengerId` = :passengerId
AND `status` != 'Finished'
AND DATE(`timeSelected`) = CURDATE()
";
$stmtCheckPassenger = $con->prepare($sqlCheckPassenger);
$stmtCheckPassenger->bindParam(':passengerId', $passengerId);
$stmtCheckPassenger->execute();
$existingTrip = $stmtCheckPassenger->fetch(PDO::FETCH_ASSOC);

// إذا كانت موجودة يتم التحديث
if ($existingTrip) {
    $sqlUpdate = "UPDATE `mishwaritrips` SET 
        `driverId` = :driverId,
        `phone` = :phone,
        `gender` = :gender,
        `name` = :name,
        `name_english` = :name_english,
        `address` = :address,
        `religion` = :religion,
        `age` = :age,
        `startNameAddress` = :startNameAddress,
        `locationCoordinate` = :locationCoordinate,
        `education` = :education,
        `license_type` = :license_type,
        `national_number` = :national_number,
        `car_plate` = :car_plate,
        `make` = :make,
        `model` = :model,
        `color` = :color,
        `color_hex` = :color_hex,
        `token` = :token,
        `rating` = :rating,
        `countRide` = :countRide,
        `timeSelected` = :timeSelected,
        `status` = :status 
        WHERE `passengerId` = :passengerId";

    $stmtUpdate = $con->prepare($sqlUpdate);
    $stmtUpdate->execute([
        ':driverId' => $driverId,
        ':phone' => $phone,
        ':gender' => $gender,
        ':name' => $name,
        ':name_english' => $name_english,
        ':address' => $address,
        ':religion' => $religion,
        ':age' => $age,
        ':startNameAddress' => $startNameAddress,
        ':locationCoordinate' => $locationCoordinate,
        ':education' => $education,
        ':license_type' => $license_type,
        ':national_number' => $national_number,
        ':car_plate' => $car_plate,
        ':make' => $make,
        ':model' => $model,
        ':color' => $color,
        ':color_hex' => $color_hex,
        ':token' => $token,
        ':rating' => $rating,
        ':countRide' => $countRide,
        ':timeSelected' => $timeSelected,
        ':status' => $status,
        ':passengerId' => $passengerId
    ]);

    if ($stmtUpdate->rowCount() > 0) {
        jsonSuccess(null, "Trip updated successfully");
    } else {
        jsonError("Failed to update trip data");
    }

} else {
    // إدخال رحلة جديدة
    $sqlInsert = "INSERT INTO `mishwaritrips` (
        `driverId`, `phone`, `gender`, `name`, `name_english`, `address`, `religion`, 
        `age`, `startNameAddress`, `locationCoordinate`, `education`, `license_type`, 
        `national_number`, `car_plate`, `make`, `model`, `color`, `color_hex`, `token`, 
        `rating`, `countRide`, `passengerId`, `timeSelected`, `createdAt`, `status`
    ) VALUES (
        :driverId, :phone, :gender, :name, :name_english, :address, :religion, 
        :age, :startNameAddress, :locationCoordinate, :education, :license_type, 
        :national_number, :car_plate, :make, :model, :color, :color_hex, :token, 
        :rating, :countRide, :passengerId, :timeSelected, NOW(), :status
    )";

    $stmtInsert = $con->prepare($sqlInsert);
    $stmtInsert->execute([
        ':driverId' => $driverId,
        ':phone' => $phone,
        ':gender' => $gender,
        ':name' => $name,
        ':name_english' => $name_english,
        ':address' => $address,
        ':religion' => $religion,
        ':age' => $age,
        ':startNameAddress' => $startNameAddress,
        ':locationCoordinate' => $locationCoordinate,
        ':education' => $education,
        ':license_type' => $license_type,
        ':national_number' => $national_number,
        ':car_plate' => $car_plate,
        ':make' => $make,
        ':model' => $model,
        ':color' => $color,
        ':color_hex' => $color_hex,
        ':token' => $token,
        ':rating' => $rating,
        ':countRide' => $countRide,
        ':passengerId' => $passengerId,
        ':timeSelected' => $timeSelected,
        ':status' => $status
    ]);

    if ($stmtInsert->rowCount() > 0) {
        jsonSuccess(null, "New trip inserted successfully");
    } else {
        jsonError("Failed to insert new trip data");
    }
}
?>