<?php
// FINAL CORRECTED SCRIPT: get_order_history.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. Validate Connection
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

// 2. Validate that a user_id was provided
if (!isset($_GET['user_id']) || empty($_GET['user_id'])) {
    http_response_code(400); // Bad Request
    $response['status'] = 'error';
    $response['message'] = 'User ID is required to fetch order history.';
    echo json_encode($response);
    exit;
}

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

try {
    // 3. THE FIX: This query now joins with the 'users' table
    $sql = "SELECT 
                o.id,
                o.user_id,
                o.total_price,
                o.status,
                o.created_at AS order_date,
                u.name AS user_name,
                u.mobile AS user_mobile
            FROM orders o
            LEFT JOIN users u ON o.user_id = u.id
            WHERE o.user_id = ? 
            ORDER BY o.id DESC"; 

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orders = [];
    while($row = $result->fetch_assoc()) {
        $orders[] = $row;
    }

    // 4. Success: Send the JSON response
    echo json_encode($orders);

} catch (Exception $e) {
    // 5. Failure
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'An error occurred while fetching your orders: ' . $e->getMessage();
    echo json_encode($response);
}

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