<?php
declare(strict_types=1);

$pageTitle = 'Clientes APP / Licenças MAC';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);
$accessType = 'app_license';
$typeLabel = 'Licença APP';
$today = date('Y-m-d');

if (isset($_GET['export_keys']) && $_GET['export_keys'] === '1') {
    gpc_no_cache_headers();
    header('Content-Type: text/plain; charset=utf-8');
    header('Content-Disposition: attachment; filename="syntra_licencas_mac_keys_' . date('Ymd_His') . '.txt"');
    $stmt = $db->prepare("SELECT mac_address, device_key, license_type, expire_date, key_created_at, key_expire_at, title, notes FROM devices WHERE COALESCE(access_type,'app_license') = :a ORDER BY id DESC");
    $stmt->execute([':a' => $accessType]);
    echo "SYNTRA - BACKUP DE LICENCAS MAC + KEY
";
    echo "Gerado em: " . date('Y-m-d H:i:s') . "

";
    while ($r = $stmt->fetch()) {
        echo "MAC: " . ($r['mac_address'] ?? '') . "
";
        echo "KEY: " . ($r['device_key'] ?? '') . "
";
        echo "Tipo: " . (($r['license_type'] ?? 'official') === 'trial' ? 'Teste gratis' : 'Licenca oficial') . "
";
        echo "Criada em: " . ($r['key_created_at'] ?? '') . "
";
        echo "Expira em: " . (($r['key_expire_at'] ?? '') ?: ($r['expire_date'] ?? '')) . "
";
        echo "Titulo: " . ($r['title'] ?? '') . "
";
        echo "Notas: " . ($r['notes'] ?? '') . "
";
        echo "----------------------------------------
";
    }
    exit;
}

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'] ?? 'Licença APP'));
        $expire = trim((string) ($_POST['expire_date'] ?? ''));
        $notes = trim((string) ($_POST['notes'] ?? ''));
        $licenseType = (($_POST['license_type'] ?? 'official') === 'trial') ? 'trial' : 'official';

        if (strlen(str_replace(':', '', $mac)) !== 12) {
            gpc_flash('bad', 'MAC inválido');
        } else {
            $keyCreated = date('Y-m-d H:i:s');
            $keyExpire = $expire;
            if ($id > 0) {
                $oldKeyStmt = $db->prepare('SELECT device_key, key_created_at FROM devices WHERE id=:id LIMIT 1');
                $oldKeyStmt->execute([':id'=>$id]);
                $oldKeyRow = $oldKeyStmt->fetch();
                $key = trim((string)($oldKeyRow['device_key'] ?? '')) ?: gpc_new_device_key();
                $keyCreated = trim((string)($oldKeyRow['key_created_at'] ?? '')) ?: $keyCreated;
                if (!empty($_POST['regenerate_key'])) { $key = gpc_new_device_key(); $keyCreated = date('Y-m-d H:i:s'); }
            } else {
                $key = gpc_new_device_key();
            }
            $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) {
                $existingStmt = $db->prepare("SELECT id, device_key, key_created_at, license_type FROM devices WHERE mac_address = :m AND COALESCE(access_type,'app_license') = :a ORDER BY CASE WHEN COALESCE(license_type,'official')='official' THEN 0 ELSE 1 END, id DESC LIMIT 1");
                $existingStmt->execute([':m' => $mac, ':a' => $accessType]);
                $existingRow = $existingStmt->fetch();
                if ($existingRow) {
                    $id = (int)$existingRow['id'];
                    $oldType = (string)($existingRow['license_type'] ?? 'trial');
                    $key = trim((string)($existingRow['device_key'] ?? '')) ?: $key;
                    $keyCreated = trim((string)($existingRow['key_created_at'] ?? '')) ?: $keyCreated;
                    if ($licenseType === 'official' && $oldType === 'trial') {
                        $key = gpc_new_device_key();
                        $keyCreated = date('Y-m-d H:i:s');
                    }
                }
            }

            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, license_type=:lt, key_created_at=:kc, key_expire_at=:ke, 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, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':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, license_type, key_created_at, key_expire_at, notes, access_type)
                    VALUES (:m,:u,:p,:d,:pl,:t,:e,:k,:lt,:kc,:ke,:n,:a)')
                    ->execute([
                        ':m' => $mac, ':u' => $user, ':p' => $pass, ':d' => $dns, ':pl' => $pl,
                        ':t' => $title, ':e' => $expire, ':k' => $key, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':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">Clientes por MAC</span>
        <h2><?= gpc_h($pageTitle) ?></h2>
        <p>Controle dos clientes que usam a licença do APP e precisam estar ativos para acessar o painel cliente.</p>
    </div>
    <span class="badge badge-ok"><?= 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' : 'Nova licença MAC' ?></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('+30 days'))) ?>">
                </div>
                <div class="field">
                    <label>Título</label>
                    <input type="text" name="title" value="<?= gpc_h($edit['title'] ?? 'Licença APP') ?>">
                </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">
                    <label>Tipo de licença</label>
                    <select name="license_type"><option value="official" <?= (($edit['license_type'] ?? 'official') !== 'trial') ? 'selected' : '' ?>>Licença oficial — exige MAC + KEY no Painel Cliente</option><option value="trial" <?= (($edit['license_type'] ?? '') === 'trial') ? 'selected' : '' ?>>Teste grátis — login simples por MAC</option></select>
                </div>
                <div class="field">
                    <label>KEY da licença</label>
                    <input type="text" readonly value="<?= gpc_h($edit['device_key'] ?? 'Gerada ao salvar') ?>">
                    <?php if ($edit): ?><label class="check"><input type="checkbox" name="regenerate_key" value="1"> Gerar nova KEY</label><?php endif; ?>
                </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>
        <a class="btn btn-sm btn-ghost" href="?export_keys=1"><i data-lucide="download"></i> Exportar MAC + KEY</a>
    </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>KEY</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><code><?= gpc_h($r['device_key'] ?? '') ?></code><br><small><?= (($r['license_type'] ?? 'official') === 'trial') ? 'Teste' : 'Oficial' ?></small></td>
                        <td><span class="badge badge-ok"><?= 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="9" class="empty">Nenhum registro nesta categoria</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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