<?php
require_once __DIR__ . '/../../../connect.php';
//sendWhatsAppDriver.php
error_log("--- [send_otp_driver.php] Started ---");

/**
 * فحص البلاك ليست (خاصة بالسائقين)
 * - يشفّر الهاتف الخام ويبحث عنه في جدول blacklist_driver
 */
function is_blacklisted_driver(PDO $con, $encryptionHelper, string $phone): bool {
    $raw     = trim($phone);
    $enc_raw = $encryptionHelper->encryptData($raw);

    $sql = "SELECT 1 FROM blacklist_driver WHERE phone = :ph LIMIT 1";
    $q = $con->prepare($sql);
    $q->execute(['ph' => $enc_raw]);

    return (bool)$q->fetchColumn();
}

/* 0) استقبل الرقم وتحقق من البلاك ليست */
$receiver = filterRequest("receiver");

if (!$receiver) {
    jsonError('Phone number is required.');
    error_log("[send_otp_driver.php] Error: phone empty");
    exit();
}

if (is_blacklisted_driver($con, $encryptionHelper, $receiver)) {
    jsonError('This driver is blacklisted and cannot receive OTP.');
    error_log("[send_otp_driver.php] BLOCKED (blacklisted): $receiver");
    exit();
}

/* 1) توليد الـ OTP */
$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;

/* 🟢 2) تخطي الإرسال الفعلي */
error_log("[send_otp_driver.php] Skipping actual WhatsApp send. OTP for $receiver: $otp");

/* 3) حفظ الـ OTP في قاعدة البيانات */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc      = $encryptionHelper->encryptData($otp);

$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');

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

    $stmt = $con->prepare("
        INSERT INTO phone_verification
            (phone_number, token_code, expiration_time, is_verified, created_at)
        VALUES (?, ?, ?, 0, ?)
    ");
    $stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);

    jsonSuccess(null, 'OTP generated and saved successfully (no message sent)');
    error_log("[send_otp_driver.php] OTP saved for driver $receiver");

} catch (PDOException $e) {
    error_log("[send_otp_driver.php] DB error: ".$e->getMessage());
    jsonError('OTP generated but failed to save to database');
}
?>
