<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../config.php';
require_once __DIR__ . '/../../../db.php';
require_once __DIR__ . '/../../../includes/auth.php';
require_once __DIR__ . '/../../../includes/functions.php';

require_login();
$user = current_user();
$pdo  = db();

$stmt = $pdo->prepare("
    SELECT p.*,
           (SELECT COUNT(*) FROM ubiquiti_alerts a
            WHERE a.panel_id = p.id AND a.created_at >= NOW() - INTERVAL '24 hours') AS alerts_24h
    FROM ubiquiti_panels p
    WHERE p.user_id = ?
    ORDER BY p.last_status ASC, p.name ASC
");
$stmt->execute([$user['id']]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$panels = array_map(fn($p) => [
    'id'           => (int)$p['id'],
    'name'         => $p['name'],
    'hostname'     => $p['hostname'],
    'location'     => $p['location'] ?? '',
    'status'       => $p['last_status'],
    'client_count' => $p['last_client_count'] !== null ? (int)$p['last_client_count'] : null,
    'iface_speed'  => $p['last_iface_speed']  !== null ? (int)$p['last_iface_speed']  : null,
    'iface_status' => $p['last_iface_status'] ?? null,
    'ccq'          => $p['last_ccq']          !== null ? (int)$p['last_ccq']          : null,
    'signal'       => $p['last_signal']        !== null ? (int)$p['last_signal']       : null,
    'alerts_24h'   => (int)$p['alerts_24h'],
    'last_check'   => $p['last_check_at'],
    'url'          => UBNT_URL . '?page=ubnt_panel_detail&id=' . (int)$p['id'],
], $rows);

$totRow = $pdo->prepare("
    SELECT COUNT(*) AS total,
           COALESCE(SUM(CASE WHEN last_status='online'  THEN 1 END), 0) AS online,
           COALESCE(SUM(CASE WHEN last_status='offline' THEN 1 END), 0) AS offline
    FROM ubiquiti_panels WHERE user_id = ?
");
$totRow->execute([$user['id']]);
$tot = $totRow->fetch(PDO::FETCH_ASSOC);

echo json_encode([
    'panels'         => $panels,
    'total_panels'   => (int)$tot['total'],
    'total_online'   => (int)$tot['online'],
    'total_offline'  => (int)$tot['offline'],
    'ts'             => date('H:i:s'),
], JSON_UNESCAPED_UNICODE);
