<?php
// FINAL CORRECTED SCRIPT: get_all_orders.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 = [];

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;
}

try {
    // This query safely joins with the 'users' table.
    // It provides default values if a user is not found, preventing errors.
    $sql = "SELECT 
                o.id,
                o.user_id,
                IFNULL(u.name, 'Unknown User') AS user_name, 
                IFNULL(u.mobile, 'N/A') AS user_mobile,
                o.total_price,
                o.status,
                o.created_at AS order_date
            FROM orders o
            LEFT JOIN users u ON o.user_id = u.id
            ORDER BY o.id DESC"; 

    $result = $conn->query($sql);
    
    $orders = [];
    while($row = $result->fetch_assoc()) {
        $orders[] = $row;
    }

    echo json_encode($orders);

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

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