<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");

require_once "../../dbcon.php";
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS')
    exit(0);

// Validate user_id
$user_id = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
if ($user_id <= 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid or missing user_id'
    ]);
    exit;
}

// --- Stats for the user ---
$stats = [];

// Total Orders
$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM orders WHERE user_id = $user_id");
$stats['total_orders'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

// Cars In Transit (assuming 'in_transit' status)
$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM orders WHERE user_id = $user_id AND status='in_transit'");
$stats['cars_in_transit'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

// Pending Payments
$q = mysqli_query($conn, "SELECT SUM(total_amount) as pending FROM orders WHERE user_id = $user_id AND payment_status='pending'");
$stats['pending_payments'] = (float) (mysqli_fetch_assoc($q)['pending'] ?? 0);

// Invoiced / Completed
$q = mysqli_query($conn, "SELECT SUM(total_amount) as invoiced FROM orders WHERE user_id = $user_id AND status='completed'");
$stats['invoiced'] = (float) (mysqli_fetch_assoc($q)['invoiced'] ?? 0);

// --- Recent Bookings ---
$recentBookings = [];
$q = mysqli_query($conn, "SELECT o.*, c.model as car_name 
    FROM orders o 
    JOIN cars c ON c.id = o.car_id 
    WHERE o.user_id = $user_id
    ORDER BY o.created_at DESC LIMIT 5");
while ($row = mysqli_fetch_assoc($q)) {
    $recentBookings[] = [
        'id' => $row['id'],
        'car_name' => $row['car_name'],
        'date' => $row['created_at'],
        'status' => $row['status'],
        'amount' => $row['total_amount'],
    ];
}


echo json_encode([
    'status' => 'success',
    'data' => [
        'stats' => $stats,
        'recentBookings' => $recentBookings,
        
    ]
]);
exit;
