<?php
/**
 * ajax/dashboard_charts.php
 * Returns JSON: revenue (30-day), procedures (7-day), conditions (this month)
 * Called asynchronously AFTER the dashboard page has rendered, so it does
 * not block the initial page paint.
 */
ob_start();
session_start();
if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    http_response_code(403);
    exit(json_encode(['error' => 'Unauthorized']));
}

include '../layouts/dbconn.php';
date_default_timezone_set('Africa/Nairobi');

// ── 30-second chart cache in session ──────────────────────────────────────
$CACHE_TTL = 30;
$cache_ok  = isset($_SESSION['_dc_ts'], $_SESSION['_dc_data'])
          && $_SESSION['_dc_date'] === date('Y-m-d')
          && (time() - $_SESSION['_dc_ts']) < $CACHE_TTL;

if ($cache_ok) {
    ob_end_clean();
    header('Content-Type: application/json');
    echo $_SESSION['_dc_data'];
    exit();
}

// ── Revenue: 30-day ───────────────────────────────────────────────────────
// Sargable: payment_date >= DATE_SUB(CURDATE(), 30) avoids DATE() wrapper
$rev_rows = [];
$res = $conn->query("
    SELECT DATE(payment_date) AS date,
           SUM(amount)        AS revenue,
           COUNT(*)           AS tx_count
    FROM payments
    WHERE status       = 'COMPLETED'
      AND payment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE(payment_date)
    ORDER BY DATE(payment_date) ASC");
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $rev_rows[] = [
            'date'     => $r['date'],
            'revenue'  => (float)$r['revenue'],
            'tx_count' => (int)$r['tx_count'],
        ];
    }
}

// ── Procedure distribution: last 7 days ───────────────────────────────────
$proc_rows = [];
$res = $conn->query("
    SELECT ept.category, COUNT(*) AS count
    FROM patient_procedures pp
    JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
    WHERE pp.procedure_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY ept.category
    ORDER BY count DESC");
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $proc_rows[] = ['category' => $r['category'], 'count' => (int)$r['count']];
    }
}

// ── Common conditions this month ──────────────────────────────────────────
$cond_rows = [];
$month_start = date('Y-m-01');
$st = $conn->prepare("
    SELECT diagnosis_primary, COUNT(*) AS cnt
    FROM consultations
    WHERE started_at >= ?
      AND diagnosis_primary IS NOT NULL
      AND diagnosis_primary <> ''
    GROUP BY diagnosis_primary
    ORDER BY cnt DESC
    LIMIT 5");
$st->bind_param("s", $month_start);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
    $cond_rows[] = [
        'label' => ucwords(strtolower($r['diagnosis_primary'])),
        'count' => (int)$r['cnt'],
    ];
}
$st->close();

$payload = json_encode([
    'revenue'    => $rev_rows,
    'procedures' => $proc_rows,
    'conditions' => $cond_rows,
]);

// Cache in session
$_SESSION['_dc_data'] = $payload;
$_SESSION['_dc_ts']   = time();
$_SESSION['_dc_date'] = date('Y-m-d');

ob_end_clean();
header('Content-Type: application/json');
echo $payload;