<?php
  
    // --- START DEBUGGING CODE ---
    $log_file = 'request_debug_log.txt';
    $current_time = date('Y-m-d H:i:s');
    $request_data = json_encode($_POST);
    $log_message = "[{$current_time}] Received POST data: {$request_data}\n";
    file_put_contents($log_file, $log_message, FILE_APPEND);
    // --- END DEBUGGING CODE ---

  




// FINAL STABLE SCRIPT FOR SPLASHJET BD
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';

if (empty($mobile)) {
    echo json_encode(['status' => 'error', 'message' => 'Mobile number is required']);
    exit;
}

$normalized_mobile = substr($mobile, -10);

try {
    $sql_check = "SELECT id, mobile FROM users WHERE mobile LIKE CONCAT('%', ?)";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("s", $normalized_mobile);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        $user = $result_check->fetch_assoc();
        $reset_code = rand(100000, 999999);
        
        $sql_update = "UPDATE users SET reset_code = ? WHERE id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("si", $reset_code, $user['id']);
        $stmt_update->execute();
        $stmt_update->close();

        // --- SMS API CONFIGURATION ---
        $apiKey = "c8605ed1f98049dc";
        $secretKey = "bd2f98ac"; 
        $senderId = "FLOW TECH"; // Corrected ID with space
        $message = "Your password reset OTP for Splashjet BD is: " . $reset_code;
        
        // Use standard HTTP (Port 80) to avoid firewall timeout issues on 7790
        $url = "https://smpp.ajuratech.com:7790/sendtext?apikey";
         
        $postData = [
            'apikey' => $apiKey,
            'secretkey' => $secretKey,
            'callerID' => $senderId,
            'toUser' => $user['mobile'],
            'messageContent' => $message
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50); // Longer timeout
        
        $sms_output = curl_exec($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        // Even if SMS fails, we tell the app 'success' because the code is in the DB
        // But we can check the output for debugging
        $response['status'] = 'success';
        $response['message'] = 'A reset code has been sent to your mobile number.';
        
        // Uncomment the line below only during testing to see the API response in Logcat
        // $response['api_response'] = $sms_output; 

        echo json_encode($response);

    } else {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'User not found']);
    }
    $stmt_check->close();

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server error occurred']);
}

$conn->close();
exit;