<?php
session_start();
header('Content-Type: application/json');
include('includes/dbconnection.php');

if(isset($_POST['mobilenumber'])) {
    $mobilenumber = $_POST['mobilenumber'];
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    
    // Validate mobile number (10 digits)
    if(!preg_match('/^[0-9]{10}$/', $mobilenumber)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid mobile number']);
        exit;
    }
    
    // Check if mobile number or email already exists
    $ret = mysqli_query($con, "SELECT Email FROM tbluser WHERE Email='$email' OR MobileNumber='$mobilenumber'");
    $result = mysqli_fetch_array($ret);
    if($result) {
        echo json_encode(['status' => 'error', 'message' => 'This email or mobile number is already registered']);
        exit;
    }
    
    // Generate 6-digit OTP
    $OTP = rand(100000, 999999);
    
    // Store OTP in session with timestamp
    $_SESSION['registration_otp'] = $OTP;
    $_SESSION['registration_mobile'] = $mobilenumber;
    $_SESSION['otp_timestamp'] = time();
    
    // Send OTP via SMS API
    $API = "a35fe7f7fe8217b4369a0af4244d1fca";
    $PHONE = $mobilenumber;
    $URL = "https://sms.renflair.in/V1.php?API=$API&PHONE=$PHONE&OTP=$OTP";
    
    $curl = curl_init($URL);
    curl_setopt($curl, CURLOPT_URL, $URL);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($curl);
    $curl_error = curl_error($curl);
    curl_close($curl);
    
    if($curl_error) {
        echo json_encode(['status' => 'error', 'message' => 'Failed to send OTP. Please try again.']);
        exit;
    }
    
    $data = json_decode($resp, true);
    
    // Check API response (adjust based on actual API response format)
    echo json_encode(['status' => 'success', 'message' => 'OTP sent successfully to your mobile number']);
    
} else {
    echo json_encode(['status' => 'error', 'message' => 'Mobile number is required']);
}
?>
