<?php
/**
 * V4 Command Center — live ops KPIs + realtime feed summary.
 */
require_auth();
require_permission('command.view');

$pdo = db();
$live = [
    'active_bookings' => (int)$pdo->query("SELECT COUNT(*) FROM bookings WHERE status IN ('confirmed','checked_in')")->fetchColumn(),
    'arrivals_today' => (int)$pdo->query("SELECT COUNT(*) FROM bookings WHERE check_in=CURDATE() AND status IN ('confirmed','checked_in')")->fetchColumn(),
    'open_tickets' => (int)$pdo->query("SELECT COUNT(*) FROM tickets WHERE status IN ('open','assigned','in_progress')")->fetchColumn(),
    'revenue_mtd' => (float)$pdo->query("SELECT COALESCE(SUM(total),0) FROM bookings WHERE status NOT IN ('cancelled','no_show') AND check_in >= DATE_FORMAT(CURDATE(),'%Y-%m-01')")->fetchColumn(),
];

$ota_pending = 0;
$queue_depth = 0;
$unread = 0;
if (function_exists('hv4_table_exists')) {
    if (hv4_table_exists('ota_sync_queue')) {
        $queue_depth = (int)$pdo->query("SELECT COUNT(*) FROM ota_sync_queue WHERE status='pending'")->fetchColumn();
    }
    if (hv4_table_exists('notification_inbox')) {
        $u = current_user();
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM notification_inbox WHERE user_id=? AND read_at IS NULL');
        $stmt->execute([$u['id']]);
        $unread = (int)$stmt->fetchColumn();
    }
}

$events = [];
if (hv4_table_exists('system_events')) {
    $events = $pdo->query('SELECT id, event_type, payload, created_at FROM system_events ORDER BY id DESC LIMIT 15')->fetchAll();
    foreach ($events as &$e) {
        $e['payload'] = json_decode($e['payload'] ?? '{}', true);
    }
}

json_ok([
    'live' => $live,
    'ota_queue_depth' => $queue_depth,
    'notifications_unread' => $unread,
    'events' => $events,
    'v4' => true,
]);
