<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../includes/db_config.php';
require_once '../includes/User.php';

try {
    if (!User::isLoggedIn()) { throw new Exception('User not logged in'); }
    if (!User::isAdmin())    { throw new Exception('Access denied'); }

    $oid = isset($_GET['id']) ? (int)$_GET['id'] : 0;  
    if (!$oid){ throw new Exception('Order ID is required'); }

    $db = getDBConnection();

    $sql = "
        SELECT o.*,
               COALESCE(o.customer_name, u.name) as customer_name,
               GROUP_CONCAT(s.name SEPARATOR ', ') as service_names,
               GROUP_CONCAT(oi.quantity SEPARATOR ', ') as quantities
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        WHERE o.id = ?
        GROUP BY o.id
    ";

    $st = $db->prepare($sql);
    $st->execute([$oid]);
    $ord = $st->fetch(PDO::FETCH_ASSOC);

    if (!$ord){ throw new Exception('Order not found'); }

    echo json_encode(['success'=>true,'order'=>$ord]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>$e->getMessage()]);
}
?>
