<?php
require_once __DIR__ . '/../../connect.php';
header('Content-Type: application/json; charset=utf-8');

// دوال مساعدة لو لم تكن موجودة


// جلب بيانات السيارة من الطلب
$owner_name         = $encryptionHelper->encryptData(filterRequest("owner_name"));
$phone              = $encryptionHelper->encryptData(filterRequest("phone")); // 🔒
$car_number         = $encryptionHelper->encryptData(filterRequest("car_number"));
$manufacture_year   = filterRequest("manufacture_year");
$car_model          = filterRequest("car_model");
$car_type           = filterRequest("car_type");
$site               = filterRequest("site");
$registration_date  = filterRequest("registration_date");

// تحقق بسيط من القيم المطلوبة
if (empty($owner_name) || empty($phone)) {
    jsonError("Missing required fields", 422);
}

// SQL مع bind parameters
$sql = "INSERT INTO `carsToWork`(
    `owner_name`,
    `phone`,
    `car_number`,
    `manufacture_year`,
    `car_model`,
    `car_type`,
    `site`,
    `registration_date`
) VALUES (
    :owner_name,
    :phone,
    :car_number,
    :manufacture_year,
    :car_model,
    :car_type,
    :site,
    :registration_date
)";

try {
    $stmt = $con->prepare($sql);

    $stmt->bindParam(':owner_name', $owner_name);
    $stmt->bindParam(':phone', $phone);
    $stmt->bindParam(':car_number', $car_number);
    $stmt->bindParam(':manufacture_year', $manufacture_year);
    $stmt->bindParam(':car_model', $car_model);
    $stmt->bindParam(':car_type', $car_type);
    $stmt->bindParam(':site', $site);
    $stmt->bindParam(':registration_date', $registration_date);

    if ($stmt->execute()) {
        printSuccess("Car data saved successfully", ["insert_id" => $con->lastInsertId()]);
    } else {
        $err = $stmt->errorInfo();
        jsonError("Failed to save car data: " . ($err[2] ?? 'unknown error'), 500);
    }
} catch (Exception $e) {
    jsonError("Exception: " . $e->getMessage(), 500);
}
?>