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

// استرجاع البيانات من الطلب
$phone_number     = filterRequest("phone_number");
$driverId         = filterRequest("driverId");
$email            = filterRequest("email");
$expiration_time  = filterRequest("expiration_time"); // اختياري للمستقبل

// تحقق من وجود رقم الهاتف
if (empty($phone_number)) {
    jsonError("Phone number is required");
    exit;
}

// توليد رمز تحقق مكوّن من 5 أرقام
$token_code = str_pad(random_int(0, 99999), 5, '0', STR_PAD_LEFT);

// تشفير البيانات الحساسة
$encryptedPhone = $encryptionHelper->encryptData($phone_number);
$encryptedToken = $encryptionHelper->encryptData($token_code);
$encryptedEmail = $encryptionHelper->encryptData($email); // اختياري إذا بتحب تشفيره

// التحقق من وجود الرقم مسبقاً في قاعدة البيانات
$sqlCheck = "SELECT * FROM `phone_verification` WHERE `phone_number` = :phone";
$stmtCheck = $con->prepare($sqlCheck);
$stmtCheck->bindParam(":phone", $encryptedPhone);
$stmtCheck->execute();

$success = false;

// إذا كان الرقم موجود → تحديث
if ($stmtCheck->rowCount() > 0) {
    $sqlUpdate = "UPDATE `phone_verification` 
                  SET `token_code` = :token, 
                      `expiration_time` = DATE_ADD(NOW(), INTERVAL 5 MINUTE) 
                  WHERE `phone_number` = :phone";
    $stmt = $con->prepare($sqlUpdate);
    $stmt->bindParam(":token", $encryptedToken);
    $stmt->bindParam(":phone", $encryptedPhone);
    $stmt->execute();
    $success = $stmt->rowCount() > 0;
} else {
    // إذا الرقم غير موجود → إدخال جديد
    $sqlInsert = "INSERT INTO `phone_verification` 
                  (`phone_number`, `driverId`, `email`, `token_code`, `expiration_time`, `is_verified`, `created_at`) 
                  VALUES 
                  (:phone, :driverId, :email, :token, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())";
    $stmt = $con->prepare($sqlInsert);
    $stmt->bindParam(":phone", $encryptedPhone);
    $stmt->bindParam(":driverId", $driverId);
    $stmt->bindParam(":email", $encryptedEmail);
    $stmt->bindParam(":token", $encryptedToken);
    $stmt->execute();
    $success = $stmt->rowCount() > 0;
}

// إذا تم الحفظ بنجاح → أرسل الرمز عبر SMS
if ($success) {
    // تحميل بيانات الاتصال بالـ SMS API من المتغيرات البيئية
    $username = getenv('SMS_USERNAME');
    $password = getenv('SMS_PASSWORD_EGYPT');
    $sender   = getenv('SMS_SENDER');

    if (!$username || !$password || !$sender) {
        jsonError("SMS credentials are missing");
        exit;
    }

    $message  = "Tripz app code is " . $token_code;
    $receiver = $phone_number;

    $apiUrl = 'https://sms.kazumi.me/api/sms/send-sms';
    $payload = [
        'username' => $username,
        'password' => $password,
        'language' => 'e',
        'sender'   => $sender,
        'receiver' => $receiver,
        'message'  => $message
    ];

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

    if ($smsResponse) {
        jsonSuccess(null, "Verification code sent and saved successfully");
    } else {
        jsonError("Code saved, but SMS sending failed");
    }
} else {
    jsonError("Failed to save verification data");
}

// دالة الاتصال بالـ 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"
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10
    ]);

    $api_raw_response = curl_exec($curl);

    if (curl_errno($curl)) {
        error_log("cURL Error [".curl_errno($curl)."]: " . curl_error($curl));
        curl_close($curl);
        return false;
    }

    curl_close($curl);
    $decoded_response = json_decode($api_raw_response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Invalid JSON response from SMS API.");
        return false;
    }

    error_log("SMS API response: " . print_r($decoded_response, true));
    return $decoded_response;
}
?>