<?php
/**
 * سودانا — KPI Dashboard API v21
 * بيانات الأداء للوحة الأدمن
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../../engine/Logger.php';

// Admin only
// session_start() removed — Kernel::handle manages sessions
// M4 FIX: Accept Authorization header or session (avoid plain key in URL logs)
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['HTTP_X_ADMIN_KEY'] ?? '';
$adminOk = !empty($_SESSION['admin'])
    || $authHeader === 'Bearer ' . ADMIN_PASSWORD
    || $authHeader === ADMIN_PASSWORD
    || ($_POST['key'] ?? '') === ADMIN_PASSWORD; // POST only, not GET
if (!$adminOk) Kernel::fail('unauthorized', '', 401);

$period  = $_GET['period'] ?? 'today'; // today|week|month|custom
$dateFrom = $_GET['date_from'] ?? date('Y-m-d');
$dateTo   = $_GET['date_to']   ?? date('Y-m-d');

if ($period === 'today')  { $dateFrom = $dateTo = date('Y-m-d'); }
if ($period === 'week')   { $dateFrom = date('Y-m-d', strtotime('-7 days')); $dateTo = date('Y-m-d'); }
if ($period === 'month')  { $dateFrom = date('Y-m-d', strtotime('-30 days')); $dateTo = date('Y-m-d'); }

// ── AI METRICS ───────────────────────────────────────────────
$ai = ['total_requests'=>0,'ie_hits'=>0,'cache_hits'=>0,'ai_calls'=>0,'cost_usd'=>0,'avg_latency_ms'=>0,'no_ai_pct'=>0];
try {
    $isToday = $dateFrom === date('Y-m-d') && $dateTo === date('Y-m-d');
    if ($isToday) {
        // Live from ai_requests
        $st = db()->prepare("SELECT COUNT(*) AS total, SUM(ie_hit) AS ie, SUM(cache_hit) AS cache, SUM(ai_used) AS ai_calls, SUM(cost_usd) AS cost, AVG(latency_ms) AS latency FROM ai_requests WHERE DATE(created_at)=CURDATE()");
        $st->execute();
        $row = $st->fetch();
        if ($row) {
            $ai['total_requests'] = (int)$row['total'];
            $ai['ie_hits']        = (int)$row['ie'];
            $ai['cache_hits']     = (int)$row['cache'];
            $ai['ai_calls']       = (int)$row['ai_calls'];
            $ai['cost_usd']       = round((float)$row['cost'], 6);
            $ai['avg_latency_ms'] = (int)$row['latency'];
            $ai['no_ai_pct']      = $ai['total_requests'] > 0 ? round(100 - ($ai['ai_calls'] / $ai['total_requests'] * 100), 1) : 0;
        }
    } else {
        // From kpi_daily (faster)
        $st = db()->prepare("SELECT SUM(total_requests) AS total, SUM(ie_hits) AS ie, SUM(cache_hits) AS cache, SUM(ai_calls) AS ai_calls, SUM(cost_usd_total) AS cost, AVG(avg_latency_ms) AS latency FROM kpi_daily WHERE kpi_date BETWEEN ? AND ?");
        $st->execute([$dateFrom, $dateTo]);
        $row = $st->fetch();
        if ($row && $row['total']) {
            $ai['total_requests'] = (int)$row['total'];
            $ai['ie_hits']        = (int)$row['ie'];
            $ai['cache_hits']     = (int)$row['cache'];
            $ai['ai_calls']       = (int)$row['ai_calls'];
            $ai['cost_usd']       = round((float)$row['cost'], 6);
            $ai['avg_latency_ms'] = (int)$row['latency'];
            $ai['no_ai_pct']      = $ai['total_requests'] > 0 ? round(100 - ($ai['ai_calls'] / $ai['total_requests'] * 100), 1) : 0;
        }
    }
} catch (Throwable $e) { error_log('[KPI AI] '.$e->getMessage()); }

// ── USERS ─────────────────────────────────────────────────────
$users = ['new'=>0,'total'=>0,'providers'=>0,'paid'=>0];
try {
    $st = db()->prepare("SELECT COUNT(*) AS new_users FROM users WHERE DATE(created_at) BETWEEN ? AND ?");
    $st->execute([$dateFrom, $dateTo]);
    $users['new'] = (int)$st->fetchColumn();
    $users['total']     = (int)db()->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $users['providers'] = (int)db()->query("SELECT COUNT(*) FROM users WHERE provider_verified=1")->fetchColumn();
    $users['paid']      = (int)db()->query("SELECT COUNT(*) FROM users WHERE subscription_tier='paid'")->fetchColumn();
} catch (Throwable $ignored) {}

// ── REVENUE ───────────────────────────────────────────────────
$revenue = ['subscriptions_sdg'=>0,'commissions_sdg'=>0,'total_sdg'=>0];
try {
    $sub = db()->prepare("SELECT SUM(amount_sdg) FROM subscription_requests WHERE status='approved' AND DATE(created_at) BETWEEN ? AND ?");
    $sub->execute([$dateFrom, $dateTo]);
    $revenue['subscriptions_sdg'] = (float)$sub->fetchColumn();

    $comm = db()->prepare("SELECT SUM(commission_sdg) FROM provider_earnings WHERE DATE(created_at) BETWEEN ? AND ?");
    $comm->execute([$dateFrom, $dateTo]);
    $revenue['commissions_sdg'] = (float)$comm->fetchColumn();
    $revenue['total_sdg'] = $revenue['subscriptions_sdg'] + $revenue['commissions_sdg'];
} catch (Throwable $ignored) {}

// ── BOOKINGS ──────────────────────────────────────────────────
$bookings = ['created'=>0,'completed'=>0,'pending'=>0];
try {
    $bk = db()->prepare("SELECT status, COUNT(*) AS cnt FROM bookings WHERE DATE(created_at) BETWEEN ? AND ? GROUP BY status");
    $bk->execute([$dateFrom, $dateTo]);
    foreach ($bk->fetchAll() as $row) {
        if ($row['status'] === 'completed') $bookings['completed'] = (int)$row['cnt'];
        if ($row['status'] === 'pending')   $bookings['pending']   = (int)$row['cnt'];
        $bookings['created'] += (int)$row['cnt'];
    }
} catch (Throwable $ignored) {}

// ── SYSTEM ────────────────────────────────────────────────────
$system = ['load_level'=>0,'cache_size'=>0,'pending_providers'=>0,'open_tickets'=>0,'data_gaps'=>0];
try {
    $sm = db()->query("SELECT load_level FROM system_metrics ORDER BY metric_minute DESC LIMIT 1")->fetchColumn();
    $system['load_level'] = (int)($sm ?? 0);
    $system['cache_size'] = (int)db()->query("SELECT COUNT(*) FROM ai_cache WHERE is_valid=1 AND expires_at > NOW()")->fetchColumn();
    $system['pending_providers'] = (int)db()->query("SELECT COUNT(*) FROM provider_applications WHERE status='pending'")->fetchColumn();
    $system['open_tickets'] = (int)db()->query("SELECT COUNT(*) FROM support_tickets WHERE status IN ('open','escalated')")->fetchColumn();
    $system['data_gaps'] = (int)db()->query("SELECT COUNT(*) FROM data_gaps WHERE is_resolved=0 AND priority IN ('P0','P1')")->fetchColumn();
} catch (Throwable $ignored) {}

// ── BDE ───────────────────────────────────────────────────────
$bde = ['generated'=>0,'ready'=>0];
try {
    $bd = db()->prepare("SELECT status, COUNT(*) AS cnt FROM bde_documents WHERE DATE(created_at) BETWEEN ? AND ? GROUP BY status");
    $bd->execute([$dateFrom, $dateTo]);
    foreach ($bd->fetchAll() as $row) {
        $bde['generated'] += (int)$row['cnt'];
        if ($row['status'] === 'ready') $bde['ready'] += (int)$row['cnt'];
    }
} catch (Throwable $ignored) {}

json_response([
    'success' => true,
    'period'  => ['from'=>$dateFrom,'to'=>$dateTo,'label'=>$period],
    'ai'      => $ai,
    'users'   => $users,
    'revenue' => $revenue,
    'bookings'=> $bookings,
    'bde'     => $bde,
    'system'  => $system,
    'generated_at' => date('Y-m-d H:i:s'),
]);
