<?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 (3 خانات) */
$otp = (string)rand(100, 999);

/* 2) إرسال الرمز عبر بوابة الفلاش كول / واتساب */
$nabehUrl = 'https://otp.intaleqapp.com/api/request-otp.php';
$appKey = getenv('NABEH_OTP_APP_KEY');

$payload = [
    'phone' => $receiver,
    'device_type' => 'android',
    'method' => 'whatsapp',
    'code' => $otp
];

$ch = curl_init($nabehUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        "X-App-Key: $appKey"
    ],
    CURLOPT_TIMEOUT => 15,
    CURLOPT_CONNECTTIMEOUT => 5
]);

$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    error_log("⚠️ [Flash Call OTP Driver] Curl Error: $error");
    jsonError('Failed to connect to OTP service');
    exit;
}

$decoded = json_decode((string)$res, true);
if ($httpCode !== 200 || !($decoded['success'] ?? false)) {
    error_log("❌ [Flash Call OTP Driver] Failed response: Code $httpCode | Body: " . (string)$res);
    jsonError($decoded['message'] ?? 'Failed to request verification code');
    exit;
}

/* 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 sent and saved successfully');
    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');
}
?>
