<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_admin();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'delete') {
            $stmt = db()->prepare('DELETE FROM devices WHERE id=?');
            $stmt->execute([(int)($_POST['id'] ?? 0)]);
            flash('success', 'Dispositivo removido do historico.');
        } elseif ($action === 'clear') {
            db()->exec('DELETE FROM devices');
            flash('success', 'Historico de dispositivos limpo.');
        } elseif ($action === 'save_device') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Dispositivo invalido.');
            }

            $server = find_server_by_id_or_url((int)($_POST['dns_id'] ?? 0));
            $dnsId = $server ? (int)$server['id'] : null;
            $dnsName = $server ? (string)$server['name'] : '';
            $dnsUrl = $server ? normalize_url((string)$server['url']) : '';

            $stmt = db()->prepare(
                'UPDATE devices
                 SET dns_id = ?,
                     dns_name = ?,
                     dns_url = ?,
                     username = ?,
                     password = ?,
                     auto_login = ?,
                     auto_activate = ?,
                     activation_status = ?,
                     last_seen_at = last_seen_at
                 WHERE id = ?'
            );
            $stmt->execute([
                $dnsId,
                $dnsName,
                $dnsUrl,
                trim((string)($_POST['username'] ?? '')),
                (string)($_POST['password'] ?? ''),
                (int)($_POST['auto_login'] ?? 0) === 1 ? 1 : 0,
                (int)($_POST['auto_activate'] ?? 0) === 1 ? 1 : 0,
                (int)($_POST['auto_activate'] ?? 0) === 1 ? 'active' : 'pending',
                $id,
            ]);
            flash('success', 'Configuracao do dispositivo salva.');
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
    redirect('devices.php');
}

$devices = db()->query('SELECT * FROM devices ORDER BY last_seen_at DESC, id DESC')->fetchAll();
$servers = db()->query('SELECT * FROM servers WHERE active=1 AND authorized=1 ORDER BY priority ASC, name ASC')->fetchAll();
$pageTitle = 'Dispositivos Registrados';
$pageSubtitle = 'Acompanhe aparelhos, configure autoativacao e credenciais automaticas por DNS.';
$pageIcon = 'fa-tv';
require __DIR__ . '/includes/header.php';
?>
<style>
.device-config-grid{display:grid;grid-template-columns:minmax(180px,1.2fr) minmax(140px,.8fr) minmax(140px,.8fr) auto auto;gap:10px;align-items:end}
.device-id-line{display:flex;flex-direction:column;gap:4px}
.device-id-line code{white-space:normal;overflow-wrap:anywhere}
.device-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
.device-meta .badge{font-size:11px}
.device-actions{display:flex;gap:8px;align-items:center}
@media(max-width:980px){.device-config-grid{grid-template-columns:1fr}.device-actions{justify-content:flex-start}}
</style>
<section class="panel-card">
    <div class="panel-card-head">
        <div class="panel-card-icon"><i class="fa-solid fa-tv"></i></div>
        <div><h2>Aparelhos detectados</h2><p><?=count($devices)?> dispositivo(s) registrado(s) pela API.</p></div>
    </div>
    <?php if ($devices): ?>
        <div class="panel-card-body" style="display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap">
            <div class="muted">O mesmo ID exibido no aplicativo deve aparecer nesta lista.</div>
            <form method="post" onsubmit="return confirm('Limpar todo o historico de dispositivos?')">
                <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
                <input type="hidden" name="action" value="clear">
                <button class="button danger" type="submit"><i class="fa-solid fa-trash"></i> Limpar historico</button>
            </form>
        </div>
        <div class="table-wrap">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Dispositivo</th>
                        <th>Autoativacao / Login automatico</th>
                        <th>Conexoes</th>
                        <th>Acao</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($devices as $device): ?>
                    <tr>
                        <td>
                            <div class="device-id-line">
                                <strong>#<?=e($device['id'])?></strong>
                                <code><?=e($device['device_id'] ?: $device['name'])?></code>
                            </div>
                            <div class="device-meta">
                                <span class="badge active">Primeiro: <?=e($device['created_at'])?> UTC</span>
                                <span class="badge active">Ultima: <?=e($device['last_seen_at'])?> UTC</span>
                                <?php if (!empty($device['ip_address'])): ?><span class="badge inactive">IP <?=e($device['ip_address'])?></span><?php endif; ?>
                            </div>
                        </td>
                        <td colspan="2">
                            <form method="post" class="device-config-grid">
                                <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
                                <input type="hidden" name="action" value="save_device">
                                <input type="hidden" name="id" value="<?=e($device['id'])?>">
                                <div class="form-field">
                                    <label>DNS/Servidor</label>
                                    <select name="dns_id">
                                        <option value="">Selecione...</option>
                                        <?php foreach ($servers as $server): ?>
                                            <option value="<?=e($server['id'])?>" <?=((int)($device['dns_id'] ?? 0) === (int)$server['id']) ? 'selected' : ''?>>
                                                <?=e($server['name'])?> - <?=e($server['url'])?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-field">
                                    <label>Usuario</label>
                                    <input name="username" value="<?=e($device['username'] ?? '')?>" autocomplete="off">
                                </div>
                                <div class="form-field">
                                    <label>Senha</label>
                                    <input name="password" value="<?=e($device['password'] ?? '')?>" autocomplete="off">
                                </div>
                                <label class="toggle-line" style="margin-bottom:12px">
                                    <input type="checkbox" name="auto_login" value="1" <?=((int)($device['auto_login'] ?? 0) === 1) ? 'checked' : ''?>>
                                    <span>Login automatico</span>
                                </label>
                                <label class="toggle-line" style="margin-bottom:12px">
                                    <input type="checkbox" name="auto_activate" value="1" <?=((int)($device['auto_activate'] ?? 0) === 1) ? 'checked' : ''?>>
                                    <span>Autoativar</span>
                                </label>
                                <div class="device-actions">
                                    <button class="button primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> Salvar</button>
                                    <span class="badge <?=((int)($device['auto_activate'] ?? 0) === 1) ? 'active' : 'inactive'?>"><?=e($device['activation_status'] ?? 'pending')?></span>
                                </div>
                            </form>
                        </td>
                        <td>
                            <form method="post" onsubmit="return confirm('Remover este dispositivo?')">
                                <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?=e($device['id'])?>">
                                <button class="button danger" type="submit"><i class="fa-solid fa-trash"></i></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <div class="empty-state"><i class="fa-solid fa-tv"></i>Nenhum dispositivo registrado ate o momento.</div>
    <?php endif; ?>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
