<?php
/** Dashboard stats — returns role-aware KPI cards + chart series for a date range. */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not signed in.']);
    exit;
}
require_once __DIR__ . '/../includes/dashboard_lib.php';

$conn  = getDBConnection();
$role  = $_SESSION['role'] ?? 'admin';
$rk    = $_POST['range'] ?? $_GET['range'] ?? 'this_month';
$from  = $_POST['from'] ?? $_GET['from'] ?? null;
$to    = $_POST['to'] ?? $_GET['to'] ?? null;

$range     = dashboard_date_range($conn, (string) $rk, $from, $to);
$kpis      = dashboard_compute_kpis($conn, $range, $role);
$chart     = dashboard_series($conn, $range);
$secondary = dashboard_secondary_chart($conn, $range, $role);
$lists     = dashboard_lists($conn, $range, $role);

echo json_encode([
    'success'   => true,
    'range'     => ['key' => $range['key'], 'label' => $range['label'], 'from' => $range['from'], 'to' => $range['to']],
    'kpis'      => $kpis,
    'chart'     => $chart,
    'secondary' => $secondary,
    'lists'     => $lists,
    'role'      => $role,
]);
