<?php

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


$text='444';

$encryptedText = $encryptionHelper->encryptData($text);

$username = getenv('SMS_USERNAME');
$password = getenv('SMS_PASSWORD_EGYPT');
$sender   = getenv('SMS_SENDER');

$language = filterRequest("language");
$receiver = filterRequest("receiver");

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

$apiUrl = 'https://sms.kazumi.me/api/sms/send-sms';

$payload = [
    'username' => $username,
    'password' => $password,
    'language' => $language,
    'sender'   => $sender,
    'receiver' => $receiver,
    'message'  => $message0
];

error_log("Sending SMS to $receiver with OTP: $otp");

$response = callAPI("POST", $apiUrl, json_encode($payload));

error_log("API Response: " . print_r($response, true));

// التحقق من رسالة الاستجابة
if ($response && isset($response->message) && $response->message == "Success") {
    $expiration_time = date('Y-m-d H:i:s', strtotime('+5 minutes'));
    $created_at = date('Y-m-d H:i:s');

    error_log("Saving to DB: phone=$receiver, token=$otp, expires=$expiration_time");

    try {
        $receiver1=$encryptionHelper->encryptData($receiver);
        $otp1=$encryptionHelper->encryptData($otp);
        
        $stmt = $con->prepare("
            INSERT INTO phone_verification_passenger 
            (phone_number, token, expiration_time, verified, created_at) 
            VALUES (?, ?, ?, 0, ?)
        ");
        $success = $stmt->execute([$receiver1, $otp1, $expiration_time, $created_at]);

        if ($success) {
            error_log("OTP saved successfully to DB.");
            jsonSuccess(null, 'OTP sent and saved successfully');
        } else {
            error_log("SQL execution failed.");
            jsonError('OTP sent but not saved to database');
        }

    } catch (PDOException $e) {
        error_log("Database Error: " . $e->getMessage());
        jsonError('Database error');
    }

} else {
    error_log("OTP not sent. API response did not indicate success. Response: " . print_r($response, true));
    jsonError('OTP not sent');
}

// دالة التعامل مع 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"]
    ]);

    $response = curl_exec($curl);
    
    if (curl_errno($curl)) {
        error_log("cURL Error: " . curl_error($curl));
    }

    curl_close($curl);

    return json_decode($response);
}

?>