<?php
ini_set("max_execution_time", 0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type");

include '../connection.php'; 

// Get user_id from GET parameter
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

error_log("Received request for user_id: $user_id"); // Log the received user_id

if ($user_id <= 0) {
    echo json_encode(["success" => false, "message" => "Missing or invalid user_id"]);
    exit;
}

$sql = "SELECT COUNT(*) AS total_orders FROM tbl_order WHERE user_id = $user_id";
$result = mysqli_query($conn, $sql);

if ($result) {
    $row = mysqli_fetch_assoc($result);
    error_log("Found {$row['total_orders']} orders for user $user_id"); // Log the result
    echo json_encode([
        'success' => true,
        'total_orders' => (int)$row['total_orders'] // Ensure integer type
    ]);
} else {
    error_log("Query failed: " . mysqli_error($conn)); // Log errors
    echo json_encode([
        'success' => false,
        'message' => mysqli_error($conn)
    ]);
}

mysqli_close($conn);
?>
