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

error_log("--- [send_otp_pass.php] Started ---");

/* Helpers */
function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }

/**
 * Check blacklist by encrypted phone
 */
function is_blacklisted(PDO $con, $encryptionHelper, string $phone): bool {
    $raw   = trim($phone);
    $norm  = normalize_phone($raw);

    $enc_raw  = $encryptionHelper->encryptData($raw);
    $enc_norm = $encryptionHelper->encryptData($norm);

    $sql = "SELECT 1
              FROM passenger_blacklist
             WHERE phone IN (:enc_raw, :enc_norm)
               AND (expires_at IS NULL OR expires_at > NOW())
             LIMIT 1";

    $q = $con->prepare($sql);
    $q->execute([
        'enc_raw'  => $enc_raw,
        'enc_norm' => $enc_norm,
    ]);

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

/* 0) Get phone number */
$receiver = filterRequest("receiver");
if (!$receiver) {
    jsonError('Phone number is required.');
    exit();
}

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

/* 1) Generate OTP */
$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;

/* 🟢 2) Skip sending and log instead */
error_log("[send_otp] Skipping actual send. OTP generated for $receiver: $otp");

/* 3) Save OTP (encrypted) */
$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_passenger WHERE phone_number = ?")
        ->execute([$receiver_enc]);

    $stmt = $con->prepare("
        INSERT INTO phone_verification_passenger
            (phone_number, token, expiration_time, 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] OTP saved successfully for $receiver");

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

/*
require_once __DIR__ . '/../../connect.php';

error_log("--- [send_otp.php] Started ---");


function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }


function is_blacklisted(PDO $con, $encryptionHelper, string $phone): bool {
    $raw   = trim($phone);
    $norm  = normalize_phone($raw);

    // شَفِّر قبل السؤال
    $enc_raw  = $encryptionHelper->encryptData($raw);
    $enc_norm = $encryptionHelper->encryptData($norm);

    $sql = "SELECT 1
              FROM passenger_blacklist
             WHERE phone IN (:enc_raw, :enc_norm)
               AND (expires_at IS NULL OR expires_at > NOW())
             LIMIT 1";

    $q = $con->prepare($sql);
    $q->execute([
        'enc_raw'  => $enc_raw,
        'enc_norm' => $enc_norm,
    ]);

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

$receiver = filterRequest("receiver");
if (!$receiver) { jsonError('Phone number is required.'); exit(); }

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

$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;

function normalize($raw) {
    if (is_string($raw)) return json_decode($raw, true) ?: [];
    if ($raw instanceof stdClass) return (array)$raw;
    return is_array($raw) ? $raw : [];
}

$response = normalize(sendWhatsAppFromServer($receiver, $messageBody));
$sentOK   = $response['success'] ?? false;

if (!$sentOK) {
    error_log("[send_otp] WA-Server failed ⇒ ".(($response['message'] ?? null) ?: json_encode($response)));

    $payload = [
        "number"       => $receiver,
        "type"         => "text",
        "message"      => $messageBody,
        "instance_id"  => getenv("RASEEL_DRIVER_INSTANCE_ID"),
        "access_token" => getenv("RASEEL_DRIVER_ACCESS_TOKEN")
    ];
    $response = callAPI("POST", "https://raseelplus.com/api/send", json_encode($payload));
    $response = normalize($response);

    $sentOK   = ($response['status'] ?? '') === 'success';
    if (!$sentOK) {
        error_log("[send_otp] RaseelPlus failed ⇒ ".json_encode($response));
        jsonError('Failed to send OTP: '.($response['message'] ?? 'Unknown error'));
        exit();
    }
}

$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_passenger WHERE phone_number = ?")
        ->execute([$receiver_enc]);

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

    jsonSuccess(null, 'OTP sent and saved successfully');
    error_log("[send_otp] OTP saved for $receiver");

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

function callAPI($method, $url, $data) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/json",
            "Accept: application/json"
        ],
    ]);
    $body = curl_exec($ch);
    $err  = curl_error($ch);
    curl_close($ch);
    return $err ? [] : json_decode($body, true);
}
*/
