<?php
// FINAL CORRECTED SCRIPT: get_dashboard_data.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) { /* ... connection error ... */ }

try {
    // Get Order Status Counts
    $sql_counts = "SELECT status, COUNT(*) as count FROM orders GROUP BY status";
    $result_counts = $conn->query($sql_counts);
    $status_counts = [
        'Pending' => 0, 'Processing' => 0, 'Shipped' => 0, 
        'Delivered' => 0, 'Cancelled' => 0
    ];
    while($row = $result_counts->fetch_assoc()) {
        if (array_key_exists($row['status'], $status_counts)) {
            $status_counts[$row['status']] = $row['count'];
        }
    }
    $status_counts['Total'] = array_sum($status_counts);

    // THE FIX: Changed 'o.order_date' to 'o.created_at'
    $sql_orders = "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 -- Fetched the correct column
                   FROM orders o
                   LEFT JOIN users u ON o.user_id = u.id
                   ORDER BY o.id DESC 
                   LIMIT 50";

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

    // Combine into a single response
    $response = [
        'status' => 'success',
        'status_counts' => $status_counts,
        'orders' => $orders
    ];

} catch (Exception $e) { /* ... exception handling ... */ }

echo json_encode($response);
$conn->close();
exit;
?>