<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['eggzie_iboPlayer']) || !isset($_SESSION['admin_name'])) {
    echo json_encode(['error' => 'Não autenticado']);
    exit();
}

$admin_name = $_SESSION['admin_name'];
$mac = isset($_GET['mac']) ? strtoupper(trim($_GET['mac'])) : '';

if (empty($mac) || !preg_match('/^([0-9A-F]{2}:){7}[0-9A-F]{2}$/', $mac)) {
    echo json_encode(['error' => 'MAC inválido', 'can_add' => false]);
    exit();
}

$db = new SQLite3('./a/.eggziedb.db');

$stmt = $db->prepare("SELECT id, title, extra, expire_date, is_test, username 
                      FROM ibo 
                      WHERE mac_address = :mac AND seller = :seller 
                      ORDER BY id ASC");
$stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
$stmt->bindValue(':seller', $admin_name, SQLITE3_TEXT);
$result = $stmt->execute();

$playlists = [];
$total = 0;
$first_cliente = '';
$first_validade = '';
$first_tipo = '';
$first_status = '';
$is_expired = false;

while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $total++;
    $expire = $row['expire_date'];
    $is_test = (int)$row['is_test'];
    $today = date('Y-m-d');
    
    if ($is_test) {
        $status = 'MODO TESTE';
        $status_class = 'warning';
        $expired_flag = false;
    } elseif ($expire < $today) {
        $status = 'EXPIRADO';
        $status_class = 'danger';
        $expired_flag = true;
        $is_expired = true;
    } else {
        $status = 'ATIVO ANUAL';
        $status_class = 'success';
        $expired_flag = false;
    }
    
    $playlists[] = [
        'id' => $row['id'],
        'title' => htmlspecialchars($row['title']),
        'cliente' => htmlspecialchars($row['extra']),
        'validade' => date('d/m/Y', strtotime($expire)),
        'status' => $status,
        'status_class' => $status_class,
        'username' => htmlspecialchars($row['username'])
    ];
    
    if ($total === 1) {
        $first_cliente = htmlspecialchars($row['extra']);
        $first_validade = date('d/m/Y', strtotime($expire));
        $first_tipo = $is_test ? 'teste' : 'anual';
        $first_status = $status;
    }
}

$can_add = ($total < 8);
$can_renew = ($is_expired && $total > 0); // Admin renova sem custo

$status_geral = ($total === 0) ? 'NÃO REGISTRADO - NOVO' : 
                 ($can_add ? 'PARCIALMENTE OCUPADO' : 'LIMITE ATINGIDO (8/8)');

$consistent = true;
if ($total > 1) {
    $first_extra = $playlists[0]['cliente'];
    $first_expire_date = $playlists[0]['validade'];
    $first_is_test = ($playlists[0]['status'] === 'MODO TESTE');
    foreach ($playlists as $p) {
        if ($p['cliente'] !== $first_extra || $p['validade'] !== $first_expire_date || 
            ($p['status'] === 'MODO TESTE') !== $first_is_test) {
            $consistent = false;
            break;
        }
    }
}

echo json_encode([
    'exists' => ($total > 0),
    'total' => $total,
    'can_add' => $can_add,
    'can_renew' => $can_renew,
    'status_geral' => $status_geral,
    'first_cliente' => $first_cliente,
    'first_validade' => $first_validade,
    'first_tipo' => $first_tipo,
    'first_status' => $first_status,
    'playlists' => $playlists,
    'consistent' => $consistent,
    'is_expired' => $is_expired
]);
?>