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

$phoneNumber = filterRequest("phone_number");
$otp = filterRequest("otp");
$email = $phoneNumber . '@intaleqapp.com';

error_log("📥 [verifyOtp.php] Received phone number: $phoneNumber | OTP: $otp");

if (empty($phoneNumber) || empty($otp)) {
    jsonError("Phone number and OTP are required.");
    exit();
}

// 🔐 تشفير البيانات
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$email_encrypted       = $encryptionHelper->encryptData($email);

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

    if (!$record) {
        jsonError("Verification session not found. Please request a new code.");
        exit();
    }

    // 🔍 2. فك تشفير ومقارنة الرمز
    $decryptedOtp = $encryptionHelper->decryptData($record['token_code']);
    if ($decryptedOtp !== $otp) {
        jsonError("Invalid verification code.");
        exit();
    }

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

    // 🧹 حذف أي رموز قديمة لنفس الرقم
    $con->prepare("DELETE FROM phone_verification WHERE phone_number = ?")
        ->execute([$phoneNumber_encrypted]);

    // 🧾 توليد driverID فريد
    $raw = $phoneNumber;
    $driverID = substr(md5($raw), 2, 20);

    // 🔐 توليد رمز تجريبي (بدون OTP حقيقي لتجنب Null)
    $dummyToken = $encryptionHelper->encryptData('AUTO');

    // ✅ إدخال سجل تحقق مباشر
    $stmt = $con->prepare("
        INSERT INTO phone_verification 
            (phone_number, token_code, email, driverId, expiration_time, is_verified, created_at)
        VALUES (?, ?, ?, ?, NULL, 1, ?)
    ");
    $stmt->execute([$phoneNumber_encrypted, $dummyToken, $email_encrypted, $driverID, $now]);

    error_log("✅ [verifyOtp.php] Verification record inserted successfully for $phoneNumber");

    // 🔍 التحقق إذا السائق موجود مسبقاً
    $checkDriverStmt = $con->prepare("SELECT * FROM driver WHERE phone = ?");
    $checkDriverStmt->execute([$phoneNumber_encrypted]);
    $driver = $checkDriverStmt->fetch(PDO::FETCH_ASSOC);

    if ($driver) {
        error_log("👤 [verifyOtp.php] Driver already registered. Returning driver info.");
        printSuccess([
            "message" => "Driver already registered.",
            "isRegistered" => true,
            "driver" => [
                "id"         => $driver['id'],
                "first_name" => $encryptionHelper->decryptData($driver['first_name']),
                "last_name"  => $encryptionHelper->decryptData($driver['last_name']),
                "email"      => $encryptionHelper->decryptData($driver['email']),
                "phone"      => $phoneNumber
            ]
        ]);
    } else {
        error_log("🆕 [verifyOtp.php] Phone verified. Driver not found.");
        printSuccess([
            "message" => "Phone number verified successfully.",
            "isRegistered" => false,
            "driverID" => $driverID
        ]);
    }

} catch (PDOException $e) {
    error_log("💥 [verifyOtp.php] PDO ERROR: " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
}
?>
