<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mobile'])) {
    $mobile = trim($_POST['mobile']);

    // মোবাইল নাম্বার যাচাই
    if (!preg_match('/^01[3-9][0-9]{8}$/', $mobile)) {
        echo "INVALID_MOBILE";
        exit;
    }

    // OTP তৈরি ও session-এ সংরক্ষণ
    $otp = rand(100000, 999999);
    // $_SESSION['otp'] = $otp;
    // $_SESSION['mobile'] = $mobile;

    // SMS API সেটআপ

    // $token = "42c70c4272d8b4cb30e0379a8545e089";

    $token = "";
    $message = rawurlencode("আপনার পাসওয়ার্ড:$otp (ভবিষ্যতের জন্য সংরক্ষণ করুন।) ");

    $url = "http://api.greenweb.com.bd/api.php?json";
    $data = array(
        'to' => $mobile,
        'message' => $message,
        'token' => $token
    );

    // CURL দিয়ে পাঠানো
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $smsresult = curl_exec($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    // ফলাফল যাচাই ও রেসপন্স
    if ($smsresult && !$curl_error) {
        echo json_encode([ // Send JSON response for POST as well
            "status" => "OTP_SENT",
            "mobile" => $mobile,
            "otp" => $otp
        ]);
    } else {
        echo json_encode([
            'status' => 'FAILED',
            'error' => $curl_error // Provide error details for debugging
        ]);
    }
    exit; // Exit after processing POST request

} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // For GET requests, send session data if available
    echo json_encode([
        "mobile" => "$mobile" ? "$mobile" : "",
        "otp" => "$otp" ? "$otp" : ""
    ]);
    exit; // Exit after processing GET request
} else {
    echo "INVALID_REQUEST"; // Fallback for other request methods
}
?>