<?php
// ─── Dashboard API ─────────────────────────────────────────────────────────

function stats() {
    $uid = require_login();
    global $conn;
    
    $admin = is_admin($uid);
    $uidok = $admin ? '' : "AND uid='$uid'";

    // Order stats
    $os = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total, SUM(CASE WHEN status='1' THEN 1 ELSE 0 END) as active, SUM(CASE WHEN status='0' THEN 1 ELSE 0 END) as pending FROM h_order WHERE status!='4' $uidok"));
    
    // Invoice stats
    $is = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(CASE WHEN status='1' THEN 1 ELSE 0 END) as paid, SUM(CASE WHEN status!='1' AND status!='4' THEN 1 ELSE 0 END) as unpaid FROM h_invoice WHERE 1=1 $uidok"));
    
    // Support stats
    $ss = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as open FROM (SELECT rid, MAX(id) as max_id FROM h_support WHERE 1=1 $uidok GROUP BY rid) l JOIN h_support ON l.rid=h_support.rid AND l.max_id=h_support.id WHERE h_support.status='0'"));
    
    // Active domains
    $ad = 0;
    $ids = [];
    $ir = mysqli_query($conn, "SELECT id FROM h_invoice WHERE domp IS NOT NULL AND domp!='' AND domp!='0' AND CAST(domp AS DECIMAL)>0" . (!$admin ? " AND uid='$uid'" : ''));
    while ($r = mysqli_fetch_assoc($ir)) $ids[] = $r['id'];
    if ($ids) {
        $astr = implode(',', $ids);
        $ad = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM h_order WHERE iid IN ($astr) AND status!='4'" . (!$admin ? " AND uid='$uid'" : '')))['c'];
    }
    
    success_response([
        'orders'         => (int)$os['total'],
        'active_orders'  => (int)$os['active'],
        'pending_orders' => (int)$os['pending'],
        'paid_invoices'  => (int)$is['paid'],
        'unpaid_invoices'=> (int)$is['unpaid'],
        'open_tickets'   => (int)$ss['open'],
        'active_domains' => (int)$ad
    ]);
}