<?php
// FINAL SCRIPT: get_order_details.php

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

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

$response = [];

// 1. Validation
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database connection failed.';
    echo json_encode($response);
    exit;
}

if (!isset($_GET['order_id']) || empty($_GET['order_id'])) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Order ID is required.';
    echo json_encode($response);
    exit;
}

$order_id = intval($_GET['order_id']);

try {
    // 2. THE FIX: Fetch main order details and alias created_at to order_date
    $sql_order = "SELECT 
                    o.*, 
                    o.created_at AS order_date, -- <<< THE FIX IS HERE
                    u.name AS user_name, 
                    u.address AS user_address, 
                    u.mobile AS user_mobile 
                FROM orders o
                LEFT JOIN users u ON o.user_id = u.id
                WHERE o.id = ?";
    
    $stmt_order = $conn->prepare($sql_order);
    $stmt_order->bind_param("i", $order_id);
    $stmt_order->execute();
    $order_result = $stmt_order->get_result();
    $order = $order_result->fetch_assoc();

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

    // 3. Fetch order items
    $sql_items = "SELECT * FROM order_items WHERE order_id = ?";
    $stmt_items = $conn->prepare($sql_items);
    $stmt_items->bind_param("i", $order_id);
    $stmt_items->execute();
    $items_result = $stmt_items->get_result();
    $items = [];
    while ($row = $items_result->fetch_assoc()) {
        $items[] = $row;
    }

    // 4. Combine into a single JSON response
    $response = $order; 
    $response['items'] = $items;

    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(500);
    $response = ['status' => 'error', 'message' => 'Server Error: ' . $e->getMessage()];
    echo json_encode($response);
}

$conn->close();
exit;
?>