<?php
/**
 * devices.php — Listado/búsqueda de dispositivos + borrado.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/themes.php';

require_login();

$pdo = db();
$flash = '';

// Borrado de dispositivo (POST + CSRF).
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    csrf_check();
    $id = (int) ($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare('DELETE FROM devices WHERE id = ?');
        $stmt->execute([$id]);
        $flash = 'Dispositivo eliminado.';
    }
}

// Búsqueda por MAC, device_key o modelo.
$q = trim((string) ($_GET['q'] ?? ''));
if ($q !== '') {
    $like = '%' . $q . '%';
    $stmt = $pdo->prepare(
        'SELECT id, account_name, mac, device_key, model, registered, theme, sub_expire, last_seen
           FROM devices
          WHERE mac LIKE ? OR device_key LIKE ? OR model LIKE ?
          ORDER BY (last_seen IS NULL), last_seen DESC, id DESC'
    );
    $stmt->execute([$like, $like, $like]);
    $devices = $stmt->fetchAll();
} else {
    $devices = $pdo->query(
        'SELECT id, account_name, mac, device_key, model, registered, theme, sub_expire, last_seen
           FROM devices
          ORDER BY (last_seen IS NULL), last_seen DESC, id DESC'
    )->fetchAll();
}

$themes = theme_names();
$today = gmdate('Y-m-d');
$pageTitle = 'Dispositivos';
require __DIR__ . '/lib/header.php';
?>

<?php if ($flash !== ''): ?>
    <div class="alert alert-success"><?= e($flash) ?></div>
<?php endif; ?>

<form class="mb-3" method="get" action="devices.php" role="search">
    <div class="input-group">
        <span class="input-group-text"><i class="la la-search"></i></span>
        <input type="search" class="form-control" name="q" value="<?= e($q) ?>" placeholder="Buscar por MAC, device key o modelo…" aria-label="Buscar dispositivos">
        <button class="btn btn-primary" type="submit">Buscar</button>
        <?php if ($q !== ''): ?>
            <a class="btn btn-outline-secondary" href="devices.php">Limpiar</a>
        <?php endif; ?>
    </div>
</form>

<div class="card">
    <div class="card-header">
        <h2 class="h6 mb-0"><?= count($devices) ?> dispositivo<?= count($devices) === 1 ? '' : 's' ?></h2>
    </div>

    <?php if (count($devices) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">No hay resultados.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Nombre</th>
                        <th>MAC</th>
                        <th>Device key</th>
                        <th>Estado</th>
                        <th>Expira</th>
                        <th>Último acceso</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($devices as $d): ?>
                        <?php
                            $expire = (string) ($d['sub_expire'] ?? '');
                            $isExpired = $expire !== '' && $expire < $today;
                        ?>
                        <tr>
                            <td><?= e($d['account_name'] ?: '—') ?></td>
                            <td class="mono"><?= e($d['mac']) ?></td>
                            <td class="mono"><?= e($d['device_key']) ?></td>
                            <td>
                                <?php if ((int) $d['registered'] === 1): ?>
                                    <span class="badge bg-success">Registrado</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Sin registrar</span>
                                <?php endif; ?>
                            </td>
                            <td class="mono">
                                <?php if ($expire === ''): ?>
                                    <span class="text-body-tertiary">—</span>
                                <?php elseif ($isExpired): ?>
                                    <span class="badge bg-danger"><?= e($expire) ?></span>
                                <?php else: ?>
                                    <?= e($expire) ?>
                                <?php endif; ?>
                            </td>
                            <td class="mono"><?= e($d['last_seen'] ?: '—') ?></td>
                            <td class="text-end actions-row">
                                <a class="btn btn-sm btn-outline-primary" href="device_edit.php?id=<?= (int) $d['id'] ?>"><i class="la la-edit"></i> Editar</a>
                                <form method="post" action="devices.php" onsubmit="return confirm('¿Eliminar este dispositivo y sus playlists?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $d['id'] ?>">
                                    <button class="btn btn-sm btn-danger" type="submit"><i class="la la-trash"></i> Borrar</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>
