<?php
// fetch_orders.php

header('Content-Type: application/json');
require_once '../connection.php'; // defines $conn (MySQLi connection)

// 1. Get user ID and optional status from query parameters
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

if ($user_id <= 0) {
    echo json_encode(['success' => false, 'msg' => 'Invalid user_id']);
    exit;
}

// 2. Build the SQL query with optional status filtering
$sql = "SELECT * FROM tbl_order WHERE user_id = ?";
$params = [$user_id];
$types = "i";

if (!empty($status)) {
    $sql .= " AND status = ?";
    $params[] = $status;
    $types .= "s";
}

$sql .= " ORDER BY order_date DESC";

// 3. Prepare and execute the order query
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'msg' => 'Order query failed']);
    exit;
}
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$orders = [];

while ($order_row = $result->fetch_assoc()) {
    $order_id = $order_row['id'];

    // 4. Fetch items for each order with product and service names
    $item_sql = "
        SELECT 
            oi.*, 
            pt.name AS product_name,
            st.name AS service_name
        FROM tbl_order_items oi
        LEFT JOIN tbl_product_type pt ON oi.product_id = pt.id
        LEFT JOIN tbl_service_type st ON oi.service_id = st.id
        WHERE oi.order_id = ?
    ";

    $item_stmt = $conn->prepare($item_sql);
    if (!$item_stmt) {
        echo json_encode(['success' => false, 'msg' => 'Item query failed']);
        exit;
    }

    $item_stmt->bind_param("i", $order_id);
    $item_stmt->execute();
    $item_result = $item_stmt->get_result();

    $items = [];
    while ($item_row = $item_result->fetch_assoc()) {
        $items[] = $item_row;
    }

    $orders[] = [
        'order' => $order_row,
        'items' => $items,
    ];

    $item_stmt->close();
}

$stmt->close();

// 5. Return the full order + items with names in JSON format
echo json_encode([
    'success' => true,
    'orders' => $orders
], JSON_UNESCAPED_UNICODE);
?>
