<?php
/**
 * activate.php — Activación por MAC (flujo IBO del revendedor).
 *
 * El cliente lee su MAC en la pantalla de la app y te la pasa. Acá tecleás esa
 * MAC, elegís el DNS (servidor Xtream) + usuario/contraseña (o pegás una URL M3U)
 * y das "Activar": se da de alta el dispositivo por esa MAC (registrado, activo) y
 * se le asigna la playlist. Cuando la app hace su /auth, encuentra el device por
 * MAC y recibe la lista — sin códigos.
 */

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/device.php';
require_once __DIR__ . '/lib/settings.php';

require_login();

$pdo       = db();
$flash     = '';
$flashType = 'ok';
$doneId    = 0;
$doneKey   = '';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();

    $mac       = normalize_mac((string) ($_POST['mac'] ?? ''));
    $name      = trim((string) ($_POST['name'] ?? '')) ?: 'Lista';
    $type      = ($_POST['type'] ?? 'xtream') === 'm3u' ? 'm3u' : 'xtream';
    $dnsId     = (int) ($_POST['dns'] ?? 0);
    $username  = trim((string) ($_POST['username'] ?? ''));
    $password  = trim((string) ($_POST['password'] ?? ''));
    $m3u       = trim((string) ($_POST['m3u'] ?? ''));
    $protected = to_bool_int($_POST['protected'] ?? 0);

    // Validación
    if ($mac === null) {
        $flash = 'MAC inválida. Usá el formato AA:BB:CC:DD:EE:FF (la que muestra la app).';
        $flashType = 'err';
    } else {
        // Resolver playlist según tipo.
        $url = '';
        if ($type === 'm3u') {
            if ($m3u === '') {
                $flash = 'Falta la URL M3U.';
                $flashType = 'err';
            } else {
                $url = $m3u;
                $username = '';
                $password = '';
            }
        } else {
            $dnsUrl = '';
            $st = $pdo->prepare('SELECT url FROM dns WHERE id = ?');
            $st->execute([$dnsId]);
            $dnsUrl = (string) ($st->fetchColumn() ?: '');
            if ($dnsUrl === '' || $username === '' || $password === '') {
                $flash = 'Elegí un DNS y completá usuario y contraseña.';
                $flashType = 'err';
            } else {
                $url = $dnsUrl;
            }
        }

        if ($flash === '') {
            try {
                $pdo->beginTransaction();

                // Alta o búsqueda del device por MAC + marcar registrado/activo.
                $dev = device_find_by_mac($mac);
                if ($dev === null) {
                    $dev = device_create($mac, null, null, null);
                }
                $devId = (int) $dev['id'];
                $pdo->prepare('UPDATE devices SET registered = 1, locked = 0, sub_trial = 0 WHERE id = ?')
                    ->execute([$devId]);

                // Asignar playlist (sin duplicar la misma url+usuario en este device).
                $dup = $pdo->prepare('SELECT id FROM playlists WHERE device_id = ? AND url = ? AND username = ?');
                $dup->execute([$devId, $url, $username]);
                if ($dup->fetchColumn() === false) {
                    $sort = (int) $pdo->query('SELECT COALESCE(MAX(sort),-1)+1 FROM playlists WHERE device_id = ' . $devId)->fetchColumn();
                    $pdo->prepare(
                        'INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                    )->execute([$devId, $name, $type, $url, $username, $password, $protected, $sort]);
                }

                $pdo->commit();
                $doneId  = $devId;
                $doneKey = (string) ($dev['device_key'] ?? '');
                $flash   = 'Dispositivo activado y playlist asignada. Al abrir la app (o al reabrir Sports/Home) recibe la lista.';
            } catch (Throwable $ex) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $flash = 'Error al activar: ' . $ex->getMessage();
                $flashType = 'err';
            }
        }
    }
}

$dnsList = $pdo->query('SELECT id, title, url FROM dns ORDER BY title ASC, id ASC')->fetchAll();

$pageTitle = 'Activar MAC';
require __DIR__ . '/lib/header.php';
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="h4 mb-0">Activar por MAC</h1>
    <a class="btn btn-outline-secondary btn-sm" href="devices.php"><i class="la la-tv"></i> Dispositivos</a>
</div>

<?php if ($flash !== ''): ?>
    <div class="alert <?= $flashType === 'ok' ? 'alert-success' : 'alert-danger' ?>">
        <?= e($flash) ?>
        <?php if ($doneId > 0): ?>
            · <a href="device_edit.php?id=<?= $doneId ?>" class="alert-link">Ver dispositivo</a><?= $doneKey !== '' ? ' (' . e($doneKey) . ')' : '' ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<div class="row">
    <div class="col-lg-7">
        <form method="post" autocomplete="off">
            <?= csrf_field() ?>
            <div class="card mb-3">
                <div class="card-header"><h2 class="h6 mb-0">Cliente</h2></div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">MAC del cliente</label>
                        <input type="text" name="mac" class="form-control mono" placeholder="AA:BB:CC:DD:EE:FF"
                               value="<?= e((string) ($_POST['mac'] ?? '')) ?>" required>
                        <div class="form-text">La que muestra la app en pantalla.</div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label">Nombre de la lista</label>
                        <input type="text" name="name" class="form-control" placeholder="Lista"
                               value="<?= e((string) ($_POST['name'] ?? '')) ?>">
                    </div>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header"><h2 class="h6 mb-0">Playlist</h2></div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Tipo</label>
                        <select name="type" class="form-select" id="type">
                            <option value="xtream">Xtream (DNS + usuario/contraseña)</option>
                            <option value="m3u">M3U (URL directa)</option>
                        </select>
                    </div>

                    <div id="xtream-fields">
                        <div class="mb-3">
                            <label class="form-label">DNS / Servidor</label>
                            <select name="dns" class="form-select">
                                <option value="0">— Elegir DNS —</option>
                                <?php foreach ($dnsList as $d): ?>
                                    <option value="<?= (int) $d['id'] ?>"><?= e($d['title']) ?> · <?= e($d['url']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (!$dnsList): ?>
                                <div class="form-text text-warning">No hay DNS cargados. Agregá uno en <a href="dns.php">DNS</a>.</div>
                            <?php endif; ?>
                        </div>
                        <div class="row g-2">
                            <div class="col-sm-6">
                                <label class="form-label">Usuario</label>
                                <input type="text" name="username" class="form-control" value="<?= e((string) ($_POST['username'] ?? '')) ?>">
                            </div>
                            <div class="col-sm-6">
                                <label class="form-label">Contraseña</label>
                                <input type="text" name="password" class="form-control" value="<?= e((string) ($_POST['password'] ?? '')) ?>">
                            </div>
                        </div>
                    </div>

                    <div id="m3u-fields" style="display:none">
                        <label class="form-label">URL M3U</label>
                        <input type="text" name="m3u" class="form-control mono" placeholder="http://host/get.php?...&type=m3u_plus"
                               value="<?= e((string) ($_POST['m3u'] ?? '')) ?>">
                    </div>

                    <div class="form-check mt-3">
                        <input class="form-check-input" type="checkbox" name="protected" value="1" id="prot">
                        <label class="form-check-label" for="prot">Proteger lista (el cliente no ve las credenciales)</label>
                    </div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary"><i class="la la-bolt"></i> Activar</button>
        </form>
    </div>
</div>

<script>
(function () {
    var t = document.getElementById('type'), x = document.getElementById('xtream-fields'), m = document.getElementById('m3u-fields');
    function upd() { var m3u = t.value === 'm3u'; x.style.display = m3u ? 'none' : ''; m.style.display = m3u ? '' : 'none'; }
    t.addEventListener('change', upd); upd();
})();
</script>

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