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

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

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

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

try {
    // 🧹 حذف أي رموز قديمة لنفس الرقم
    $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');

    // 🕒 الوقت الحالي
    $now = date('Y-m-d H:i:s');

    // ✅ إدخال سجل تحقق مباشر
    $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] Auto 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 automatically. Driver not found.");
        printSuccess([
            "message" => "Phone number verified automatically (no OTP required).",
            "isRegistered" => false,
            "driverID" => $driverID
        ]);
    }

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