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



try {
    /* =========== 1) الحقول الواردة من الـ POST =========== */
    $required = ["phone", "password", "first_name", "last_name"];
    $optional = [
        "id", "email", "gender", "license_type", "national_number",
        "name_arabic", "issue_date", "expiry_date", "license_categories",
        "address", "licenseIssueDate", "status", "birthdate", "site",
        "accountBank", "bankCode", "employmentType",
        "maritalStatus", "fullNameMaritial", "expirationDate"
    ];

    $data = [];

    // التحقق من الحقول المطلوبة
    foreach ($required as $f) {
        $val = filterRequest($f);
        if ($val === null || $val === '') {
            jsonError("Missing required field: $f");
            exit;
        }
        $data[$f] = $val;
    }

    // قراءة الحقول الاختيارية
    foreach ($optional as $f) {
        $v = filterRequest($f);
        $data[$f] = ($v === null || $v === '' || $v === 'Not specified') ? null : $v;
    }

  if ($data['email'] === null) {
    // phone هنا ما زال خامًا (غير مُشفَّر)
    $data['email'] = $data['phone'] . '@intaleqapp.com';
		}
    /* =========== 2) تشفير الحقول الحسّاسة =========== */
    $encryptThese = ["phone", "email", "first_name", "last_name", "name_arabic","gender", "national_number",
                     "address", "site", "fullNameMaritial"];

    foreach ($encryptThese as $f) {
        if ($data[$f] !== null) {
            $data[$f] = $encryptionHelper->encryptData($data[$f]);
        }
    }

    /* =========== 3) توليد driver ID (id) إذا لم يُرسَل =========== */
    

    /* =========== 4) هَش كلمة المرور =========== */
    $data['password_hashed'] = password_hash($data['password'], PASSWORD_DEFAULT);

    /* =========== 5) منع التكرار في الهاتف / الإيميل =========== */
    $dup = $con->prepare(
        "SELECT id FROM driver WHERE phone = :phone OR email = :email"
    );
    $dup->execute([
        ':phone' => $data['phone'],
        ':email' => $data['email']
    ]);
    if ($dup->rowCount() > 0) {
        jsonError("Phone or email already registered.");
        exit;
    }

    /* =========== 6) إدخال السجل الجديد =========== */
    $sql = "
      INSERT INTO driver (
        id, phone, email, password, gender, license_type, national_number,
        name_arabic, issue_date, expiry_date, license_categories,
        address, licenseIssueDate, status, birthdate, site,
        first_name, last_name, accountBank, bankCode,
        employmentType, maritalStatus, fullNameMaritial, expirationDate,
        created_at, updated_at
      ) VALUES (
        :id, :phone, :email, :pwd, :gender, :license_type, :national_number,
        :name_arabic, :issue_date, :expiry_date, :license_categories,
        :address, :licenseIssueDate, :status, :birthdate, :site,
        :first_name, :last_name, :accountBank, :bankCode,
        :employmentType, :maritalStatus, :fullNameMaritial, :expirationDate,
        NOW(), NOW()
      )
    ";

    $ins = $con->prepare($sql);

    // خريطة الربط (تطابق تمامًا أسماء الـ placeholders في الـ SQL أعلاه)
    $bind = [
        'id'               => $data['id'],
        'phone'            => $data['phone'],
        'email'            => $data['email'],
        'pwd'              => $data['password_hashed'],
        'gender'           => $data['gender'],
        'license_type'     => $data['license_type'],
        'national_number'  => $data['national_number'],
        'name_arabic'      => $data['name_arabic'],
        'issue_date'       => $data['issue_date'],
        'expiry_date'      => $data['expiry_date'],
        'license_categories'=> $data['license_categories']?? 'B',
        'address'          => $data['address'],
        'licenseIssueDate' => $data['licenseIssueDate'],
        'status'           => $data['status'] ?? 'yet',
        'birthdate'        => $data['birthdate'],
        'site'             => $data['site'],
        'first_name'       => $data['first_name'],
        'last_name'        => $data['last_name'],
        'accountBank'      => 'yet',
        'bankCode'         => 'yet',
        'employmentType'   => $data['employmentType']?? 'yet',
        'maritalStatus'    => $data['maritalStatus']?? 'yet',
        'fullNameMaritial' => $data['fullNameMaritial']?? 'yet',
        'expirationDate'   => $data['expirationDate']?? 'yet',
    ];

    foreach ($bind as $key => $value) {
        $ins->bindValue(":$key", $value);
    }

    if ($ins->execute()) {
        jsonSuccess($data['id']);   // ترجع driver ID
    } else {
        jsonError("Failed to insert driver record.");
    }

} catch (PDOException $e) {
    error_log("DriverInsert PDO: " . $e->getMessage());
    jsonError("Database error.");
}
?>