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

/* ───── 1) جلب الحقول من طلب POST ───── */
$driverID        = filterRequest("driverID");
$vin             = filterRequest("vin");
$carPlate        = filterRequest("car_plate");
$make            = filterRequest("make");
$model           = filterRequest("model");
$year            = filterRequest("year");
$expirationDate  = filterRequest("expiration_date");
$color           = filterRequest("color");
$owner           = filterRequest("owner");
$colorHex        = filterRequest("color_hex");
$fuel            = filterRequest("fuel");

/* ───── 2) التحقق من الحقول الأساسية ───── */
$required = [
  'driverID'       => $driverID,
  'vin'            => $vin,
  'car_plate'      => $carPlate,
  'make'           => $make,
  'model'          => $model,
  'year'           => $year,
  'expirationDate' => $expirationDate,
  'color'          => $color,
  'owner'          => $owner,
  'colorHex'       => $colorHex,
  'fuel'           => $fuel,
];

foreach ($required as $field => $val) {
    if ($val === null || $val === '') {
        jsonError("Missing required field: $field");
        exit;
    }
}

/* ───── 3) تشفير الحقول الحساسة ───── */
$vin      = $encryptionHelper->encryptData($vin);
$carPlate = $encryptionHelper->encryptData($carPlate);
$owner    = $encryptionHelper->encryptData($owner);

/* ───── 4) هل لدى السائق مركبة مُسجلة سابقًا؟ ───── */
$hasCar = $con->prepare("SELECT 1 FROM CarRegistration WHERE driverID = :d LIMIT 1");
$hasCar->execute([':d' => $driverID]);
$isDefault = $hasCar->rowCount() === 0 ? 1 : 0;

/* ───── 5) إدراج السجل ───── */
$sql = "
  INSERT INTO CarRegistration (
    driverID, vin, car_plate, make, model, year, expiration_date,
    color, owner, color_hex, fuel, isDefault, created_at, status
  ) VALUES (
    :driverID, :vin, :carPlate, :make, :model, :year, :expirationDate,
    :color, :owner, :colorHex, :fuel, :isDefault, NOW(), 'yet'
  )
";

$ins = $con->prepare($sql);
$ins->execute([
  ':driverID'       => $driverID,
  ':vin'            => $vin,
  ':carPlate'       => $carPlate,
  ':make'           => $make,
  ':model'          => $model,
  ':year'           => $year,
  ':expirationDate' => $expirationDate,
  ':color'          => $color,
  ':owner'          => $owner,
  ':colorHex'       => $colorHex,
  ':fuel'           => $fuel,
  ':isDefault'      => $isDefault,
]);

if ($ins->rowCount() > 0) {
    jsonSuccess(null, "Car registration saved.");
} else {
    jsonError("Failed to save car registration.");
}