<?php
session_start();
include("configa.php");

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

    if (!preg_match('/^01[3-9][0-9]{8}$/', $mobile)) {
        echo json_encode([
            "status" => "INVALID_MOBILE"
        ]);
        exit;
    }

    $stmt = $conn->prepare("SELECT password FROM seller WHERE username = ?");
    $stmt->bind_param("s", $mobile);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($otp);
        $stmt->fetch();

        // SMS API সেটআপ
         $token = "42c70c4272d8b4cb30e0379a8545e089";

        // ✅ Web OTP API compatible SMS format
        $domain = "onlineshop.updsbd.com"; // আপনার ডোমেইন
        $message = "আপনার পাসওয়ার্ড (OTP): $otp \n@$domain #$otp";



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



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

        $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([
                "status" => "PASSWORD_SENT",
                "mobile" => $mobile
            ]);
        } else {
            echo json_encode([
                "status" => "FAILED",
                "error" => $curl_error
            ]);
        }

    } else {
        echo json_encode([
            "status" => "NOT_FOUND"
        ]);
    }

    $stmt->close();
    $conn->close();
}
elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode([
        "mobile" => isset($_SESSION['mobile']) ? $_SESSION['mobile'] : "",
        "otp" => isset($_SESSION['otp']) ? $_SESSION['otp'] : ""
    ]);
    exit;
}
else {
    echo json_encode([
        "status" => "INVALID_REQUEST"
    ]);
}
?>
