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

// استقبال رقم الهاتف
$phone = filterRequest('phone');
$language = filterRequest('lang') ?? 'r';

// 1️⃣ جلب بيانات API من البيئة
$username     = "Sefer";
$password     = getenv("SMS_PASSWORD_EGYPT");
$apiEndpoint  = getenv("SMS_API_ENDPOINT");
$sender       = "SEFER";
$appName      = "Tripz";

if (!$password || !$apiEndpoint) {
    jsonError("API configuration is missing");
    exit;
}

// 2️⃣ توليد كود OTP من السيرفر
$otp = rand(100000, 999999);

// 3️⃣ تشفير البيانات قبل تخزينها
$phoneEncrypted = $encryptionHelper->encryptData($phone);
$otpEncrypted   = $encryptionHelper->encryptData($otp);

// 4️⃣ تخزين OTP في قاعدة البيانات
try {
    $insertOtp = "INSERT INTO otp_verification_fingerPrint (phone, otp) VALUES (?, ?)";
    $stmt = $con->prepare($insertOtp);
    $stmt->execute([$phoneEncrypted, $otpEncrypted]);
} catch (PDOException $e) {
    error_log("DB Insert Error: " . $e->getMessage());
    jsonError("Failed to save OTP to the database");
    exit;
}

// 5️⃣ إرسال الرسالة عبر API
$message = "$appName app code is $otp\ncopy it to app";

$payload = json_encode([
    "username" => $username,
    "password" => $password,
    "message"  => $message,
    "language" => $language,
    "sender"   => $sender,
    "receiver" => $phone
]);

$ch = curl_init($apiEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// 6️⃣ التحقق من نجاح الإرسال
if ($httpCode != 200) {
    error_log("SMS API Failed. HTTP Code: $httpCode. Response: " . $response);
    jsonError("Failed to send OTP SMS");
    exit;
}

// 7️⃣ إرجاع النتيجة
jsonSuccess(["message" => "OTP sent successfully"]);
?>