<?php

require_once __DIR__ . '/../connect.php'; // Contains DB connection, filterRequest, printSuccess/Failure, encryptionHelper

$receiver = filterRequest("phone_number"); // رقم الهاتف

if (empty($receiver)) {
    jsonError("Receiver phone number is required.");
    exit;
}

$username = getenv('SMS_USERNAME');
$password = getenv('SMS_PASSWORD_EGYPT'); // Make sure this is the correct variable name for Egypt
$sender   = getenv('SMS_SENDER');


if (!$username || !$password || !$sender) {
   
    exit;
}

$otp = rand(10000, 99999);
$message = "Tripz app code is " . $otp;

$apiUrl = 'https://sms.kazumi.me/api/sms/send-sms';
$payload = [
    'username' => $username,
    'password' => $password,
    'language' => 'e' , // Assuming 'e' is for English as per original
    'sender'   => $sender,
    'receiver' => $receiver,
    'message'  => $message
];
$jsonPayload = json_encode($payload);
$response = callAPI("POST", $apiUrl, $jsonPayload); 

if ($response && isset($response->message) && $response->message == 'Success') {
    // 3. تخزين في Redis بدلاً من MySQL (أسرع وأكثر أماناً مع TTL تلقائي)
    if ($redis) {
        try {
            $redis->setex("otp:passenger:$receiver", 300, $otp); // صلاحية 5 دقائق
            jsonSuccess(null, "OTP sent and saved to Redis successfully");
        } catch (Exception $e) {
            error_log("Redis Error (OTP): " . $e->getMessage());
            jsonError("OTP sent but failed to save in Redis");
        }
    } else {
        jsonError("Redis service unavailable");
    }
} else {
    jsonError("OTP not sent (SMS API failed or invalid response)");
}

// دالة الاتصال بالـ API
function callAPI($method, $url, $data) {
  
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "Accept: application/json" // Often good to add
        ],
        CURLOPT_TIMEOUT => 30, // Set a timeout
        CURLOPT_CONNECTTIMEOUT => 10 // Set a connection timeout
    ]);
    $api_raw_response = curl_exec($curl);

    if (curl_errno($curl)) {
        $curl_error_msg = curl_error($curl);
        $curl_error_no = curl_errno($curl);
        error_log("cURL Error (callAPI): [{$curl_error_no}] " . $curl_error_msg);
        curl_close($curl);
        return false; // Indicate cURL failure clearly
    }
    curl_close($curl);

    $decoded_response = json_decode($api_raw_response);
    if (json_last_error() !== JSON_ERROR_NONE) {
         return null; // Indicate JSON decode failure
    }
    error_log("callAPI: Decoded response: " . print_r($decoded_response, true));
    return $decoded_response;
}
?>