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

// تسجيل بداية الطلب
error_log("[Auth_Debug] Start processing phone verification request.");

$phoneNumber = filterRequest("phone_number");
$otp         = filterRequest("otp");

if (!$phoneNumber) {
    error_log("[Auth_Error] Phone number is missing in the request.");
    jsonError("Phone number is required");
    exit();
}

if (!$otp) {
    error_log("[Auth_Error] OTP is missing in the request.");
    jsonError("OTP is required");
    exit();
}

// تسجيل الرقم
error_log("[Auth_Debug] Received phone number (Masked): " . substr($phoneNumber, 0, 7) . "***** | OTP: " . $otp);

// تشفير رقم الهاتف
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
error_log("[Auth_Debug] Phone number encrypted successfully.");

try {
    // ✅ 1. التحقق من السجل المخزن في قاعدة البيانات
    $stmtSelect = $con->prepare("SELECT * FROM phone_verification_passenger WHERE phone_number = ? ORDER BY created_at DESC LIMIT 1");
    $stmtSelect->execute([$phoneNumber_encrypted]);
    $record = $stmtSelect->fetch(PDO::FETCH_ASSOC);

    if (!$record) {
        error_log("[Auth_Error] No verification record found for this number.");
        jsonError("Verification session not found. Please request a new code.");
        exit();
    }

    // ✅ 2. فك تشفير ومقارنة الرمز
    $decryptedOtp = $encryptionHelper->decryptData($record['token']);
    if ($decryptedOtp !== $otp) {
        error_log("[Auth_Error] OTP mismatch. Expected: $decryptedOtp, Got: $otp");
        jsonError("Invalid verification code.");
        exit();
    }

    // ✅ 3. التحقق من الصلاحية (خلال 5 دقائق)
    $now = date('Y-m-d H:i:s');
    if ($record['expiration_time'] && $record['expiration_time'] < $now) {
        error_log("[Auth_Error] OTP expired.");
        jsonError("Verification code has expired. Please request a new one.");
        exit();
    }

    // ✅ 4. حذف السجلات القديمة وإدخال سجل مؤكد (verified = 1)
    error_log("[Auth_Step_1] Deleting old verification records for this phone...");
    $stmtDelete = $con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?");
    $stmtDelete->execute([$phoneNumber_encrypted]);

    $stmtInsert = $con->prepare("
        INSERT INTO phone_verification_passenger (phone_number, token, expiration_time, verified, created_at)
        VALUES (?, NULL, NULL, 1, ?)
    ");
    $stmtInsert->execute([$phoneNumber_encrypted, $now]);
    error_log("[Auth_Step_1] Inserted verified record.");

    // ✅ 5. فحص هل الراكب موجود مسبقاً
    error_log("[Auth_Step_3] Checking if passenger exists in passengers table...");

    $checkPassengerStmt = $con->prepare("
        SELECT * FROM passengers WHERE phone = ?
    ");
    $checkPassengerStmt->execute([$phoneNumber_encrypted]);
    $passenger = $checkPassengerStmt->fetch(PDO::FETCH_ASSOC);

    if ($passenger) {
        // ✅ الراكب موجود
        error_log("[Auth_Result] Passenger Found. ID: " . $passenger['id']);

        printSuccess([
            "message" => "Passenger already registered.",
            "isRegistered" => true,
            "passenger" => [
                "id" => $passenger['id'],
                "first_name" => $encryptionHelper->decryptData($passenger['first_name']),
                "last_name" => $encryptionHelper->decryptData($passenger['last_name']),
                "email" => $encryptionHelper->decryptData($passenger['email']),
                "phone" => $phoneNumber
            ]
        ]);
    } else {
        // ✅ الراكب جديد
        error_log("[Auth_Result] Passenger Not Found. Treating as new user.");

        printSuccess([
            "message" => "Phone number verified successfully.",
            "isRegistered" => false
        ]);
    }

} catch (PDOException $e) {
    error_log("[Auth_DB_Exception] Error: " . $e->getMessage() . " | File: " . $e->getFile() . " | Line: " . $e->getLine());
    jsonError("Database error occurred. Please contact support.");
} catch (Exception $e) {
    error_log("[Auth_General_Exception] Error: " . $e->getMessage());
    jsonError("An unexpected error occurred.");
}

// تسجيل نهاية الطلب
error_log("[Auth_Debug] Request processing finished.");
?>