<?php
declare(strict_types=1);

$pageTitle = 'MACs via DNS / Código';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);
$accessType = 'partner_code';
$typeLabel = 'Parceiro DNS';
$today = date('Y-m-d');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    if (($_POST['action'] ?? '') === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $mac = gpc_format_mac((string) ($_POST['mac_address'] ?? ''));
        $user = trim((string) ($_POST['username'] ?? ''));
        $pass = trim((string) ($_POST['password'] ?? ''));
        $dns = gpc_base_url(trim((string) ($_POST['dns'] ?? '')));
        $title = trim((string) ($_POST['title'] ?? 'Parceiro DNS'));
        $expire = trim((string) ($_POST['expire_date'] ?? ''));
        $notes = trim((string) ($_POST['notes'] ?? ''));

        if (strlen(str_replace(':', '', $mac)) !== 12) {
            gpc_flash('bad', 'MAC inválido');
        } else {
            $key = gpc_device_key($mac);
            $pl = ($user && $pass && $dns)
                ? rtrim($dns, '/') . '/get.php?username=' . rawurlencode($user)
                    . '&password=' . rawurlencode($pass) . '&type=m3u_plus&output=mpegts'
                : trim((string) ($_POST['playlist_url'] ?? ''));

            if ($id > 0) {
                $db->prepare('UPDATE devices SET mac_address=:m, username=:u, password=:p, dns=:d,
                    playlist_url=:pl, title=:t, expire_date=:e, device_key=:k, notes=:n, access_type=:a WHERE id=:id')
                    ->execute([
                        ':m' => $mac, ':u' => $user, ':p' => $pass, ':d' => $dns, ':pl' => $pl,
                        ':t' => $title, ':e' => $expire, ':k' => $key, ':n' => $notes, ':a' => $accessType, ':id' => $id,
                    ]);
                gpc_flash('ok', 'Salvo');
            } else {
                $db->prepare('INSERT INTO devices (mac_address, username, password, dns, playlist_url, title, expire_date, device_key, notes, access_type)
                    VALUES (:m,:u,:p,:d,:pl,:t,:e,:k,:n,:a)')
                    ->execute([
                        ':m' => $mac, ':u' => $user, ':p' => $pass, ':d' => $dns, ':pl' => $pl,
                        ':t' => $title, ':e' => $expire, ':k' => $key, ':n' => $notes, ':a' => $accessType,
                    ]);
                gpc_flash('ok', 'Cadastrado');
            }
        }
        header('Location: ' . $self);
        exit;
    }
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $db->prepare("DELETE FROM devices WHERE id = :id AND COALESCE(access_type,'app_license') = :a")->execute([':id' => (int) $_GET['delete'], ':a' => $accessType]);
    gpc_flash('ok', 'Removido');
    header('Location: ' . $self);
    exit;
}

$edit = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM devices WHERE id = :id AND COALESCE(access_type,'app_license') = :a");
    $stmt->execute([':id' => (int) $_GET['edit'], ':a' => $accessType]);
    $edit = $stmt->fetch() ?: null;
}

$search = trim((string) ($_GET['q'] ?? ''));
$sql = "SELECT * FROM devices WHERE COALESCE(access_type,'app_license') = :a";
$params = [':a' => $accessType];
if ($search !== '') {
    $sql .= ' AND (mac_address LIKE :q OR username LIKE :q OR title LIKE :q OR dns LIKE :q OR notes LIKE :q)';
    $params[':q'] = '%' . $search . '%';
}
$sql .= ' ORDER BY id DESC LIMIT 400';
$stmt = $db->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$stmt = $db->prepare("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = :a");
$stmt->execute([':a' => $accessType]);
$totalRows = (int)$stmt->fetchColumn();
$stmt = $db->prepare("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = :a AND expire_date >= :d");
$stmt->execute([':a' => $accessType, ':d' => $today]);
$activeRows = (int)$stmt->fetchColumn();
$expiredRows = max(0, $totalRows - $activeRows);

$csrf = gpc_csrf_token();
?>

<div class="section-title">
    <div>
        <span class="eyebrow">Acessos por código</span>
        <h2><?= gpc_h($pageTitle) ?></h2>
        <p>Dispositivos que entraram pelo login de código + usuário + senha. A validade segue a DNS/código parceiro.</p>
    </div>
    <span class="badge badge-purple"><?= gpc_h($typeLabel) ?></span>
</div>

<div class="stats stats-compact">
    <div class="stat"><div class="stat-label">Total</div><div class="stat-value"><?= $totalRows ?></div></div>
    <div class="stat stat-green"><div class="stat-label">Ativos</div><div class="stat-value"><?= $activeRows ?></div></div>
    <div class="stat stat-red"><div class="stat-label">Vencidos</div><div class="stat-value"><?= $expiredRows ?></div></div>
</div>

<div class="card">
    <div class="card-head">
        <h2><?= $edit ? 'Editar cadastro' : 'Novo MAC via código' ?></h2>
        <?php if ($edit): ?><a href="<?= gpc_h($self) ?>" class="btn btn-sm btn-ghost">Cancelar</a><?php endif; ?>
    </div>
    <div class="card-body">
        <form method="post">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
            <div class="form-grid">
                <div class="field">
                    <label>MAC</label>
                    <input type="text" name="mac_address" required placeholder="AA:BB:CC:DD:EE:FF" value="<?= gpc_h($edit['mac_address'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>Validade</label>
                    <input type="date" name="expire_date" value="<?= gpc_h($edit['expire_date'] ?? date('Y-m-d', strtotime('+1 year'))) ?>">
                </div>
                <div class="field">
                    <label>Título</label>
                    <input type="text" name="title" value="<?= gpc_h($edit['title'] ?? 'Parceiro DNS') ?>">
                </div>
                <div class="field">
                    <label>Usuário</label>
                    <input type="text" name="username" value="<?= gpc_h($edit['username'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>Senha</label>
                    <input type="text" name="password" value="<?= gpc_h($edit['password'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>DNS</label>
                    <input type="url" name="dns" placeholder="http://servidor:8080" value="<?= gpc_h($edit['dns'] ?? '') ?>">
                </div>
                <div class="field" style="grid-column:1/-1">
                    <label>Playlist URL</label>
                    <input type="text" name="playlist_url" value="<?= gpc_h($edit['playlist_url'] ?? '') ?>">
                </div>
                <div class="field" style="grid-column:1/-1">
                    <label>Notas</label>
                    <input type="text" name="notes" placeholder="Observações internas" value="<?= gpc_h($edit['notes'] ?? '') ?>">
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn"><i data-lucide="check"></i> Salvar</button>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-head">
        <h2>Lista de registros</h2>
    </div>
    <div class="card-body">
        <form method="get" class="toolbar">
            <input type="search" name="q" placeholder="Buscar por MAC, usuário, título ou DNS..." value="<?= gpc_h($search) ?>">
            <button type="submit" class="btn btn-sm"><i data-lucide="search"></i></button>
        </form>
        <div class="table-scroll">
            <table>
                <thead>
                    <tr><th>MAC</th><th>Tipo</th><th>Título</th><th>User</th><th>DNS</th><th>Vence</th><th>Status</th><th></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $r):
                        $ok = ($r['expire_date'] ?? '') >= $today;
                    ?>
                    <tr>
                        <td><code><?= gpc_h($r['mac_address']) ?></code></td>
                        <td><span class="badge badge-purple"><?= gpc_h($typeLabel) ?></span></td>
                        <td><?= gpc_h($r['title']) ?></td>
                        <td><?= gpc_h($r['username']) ?></td>
                        <td><code><?= gpc_h($r['dns']) ?></code></td>
                        <td><?= gpc_h($r['expire_date']) ?></td>
                        <td><span class="badge <?= $ok ? 'badge-ok' : 'badge-bad' ?>"><?= $ok ? 'Ativo' : 'Vencido' ?></span></td>
                        <td class="row-actions">
                            <a class="btn btn-sm btn-ghost btn-icon" href="?edit=<?= (int) $r['id'] ?>" title="Editar"><i data-lucide="pencil"></i></a>
                            <a class="btn btn-sm btn-danger btn-icon" href="?delete=<?= (int) $r['id'] ?>" data-confirm="Remover este MAC?" title="Excluir"><i data-lucide="trash-2"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$rows): ?>
                    <tr><td colspan="8" class="empty">Nenhum registro nesta categoria</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
