<?php
$allowRegistration = true;
require_once __DIR__ . '/../connect.php';

// جلب البيانات من المستخدم
$phone       = filterRequest("phone");
$email       = filterRequest("email");
$first_name  = filterRequest("first_name");
$last_name   = filterRequest("last_name");
$password    = filterRequest("password");
$gender      = filterRequest("gender");
$birthdate   = filterRequest("birthdate");
$site        = filterRequest("site");
$id          = filterRequest("id");

// تشفير البيانات الحساسة
$phone       = $encryptionHelper->encryptData($phone);
$email       = $encryptionHelper->encryptData($email);
$gender      = $encryptionHelper->encryptData($gender);
$birthdate   = $encryptionHelper->encryptData($birthdate);
$site        = $encryptionHelper->encryptData($site);
$first_name  = $encryptionHelper->encryptData($first_name);
$last_name   = $encryptionHelper->encryptData($last_name);

// تشفير الباسورد
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

try {
    // التحقق من وجود الإيميل أو رقم الهاتف مسبقًا
    $sql = "SELECT * FROM passengers WHERE phone = :phone OR email = :email";
    $stmt = $con->prepare($sql);
    $stmt->bindParam(":phone", $phone);
    $stmt->bindParam(":email", $email);
    $stmt->execute();
    $results = $stmt->fetchAll();

    if (count($results) > 0) {
        jsonError("The email or phone number is already registered.");
        exit;
    }

    // إدخال البيانات الجديدة
    $sql = "INSERT INTO passengers (
        id, phone, email, password, gender, birthdate, site, first_name, last_name
    ) VALUES (
        :id, :phone, :email, :password, :gender, :birthdate, :site, :first_name, :last_name
    )";
    $stmt = $con->prepare($sql);
    $stmt->bindParam(":id", $id);
    $stmt->bindParam(":phone", $phone);
    $stmt->bindParam(":email", $email);
    $stmt->bindParam(":password", $hashedPassword);
    $stmt->bindParam(":gender", $gender);
    $stmt->bindParam(":birthdate", $birthdate);
    $stmt->bindParam(":site", $site);
    $stmt->bindParam(":first_name", $first_name);
    $stmt->bindParam(":last_name", $last_name);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        jsonSuccess(null, "success to save passenger data");
    } else {
        jsonError("Failed to save passenger data");
    }

} catch (PDOException $e) {
    error_log("Database Error: " . $e->getMessage());
    jsonError("An error occurred while saving the data.");
}
?>