<?php
/**
 * credentials.php — Credenciales reseller: listar, añadir, editar y borrar.
 *
 * Una credencial = username + password + DNS (servidor) + nombre + expiración.
 * Cualquier dispositivo que haga login (api/device/login) con ese
 * username/password recibe la playlist Xtream resuelta a partir del DNS.
 * Todo se guarda por POST con CSRF y sentencias preparadas.
 */

declare(strict_types=1);

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

require_login();

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

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

    try {
        if ($action === 'create' || $action === 'update') {
            $username = trim((string) ($_POST['username'] ?? ''));
            $password = trim((string) ($_POST['password'] ?? ''));
            $dnsId    = (int) ($_POST['dns_id'] ?? 0);
            $name     = trim((string) ($_POST['name'] ?? ''));
            $expire   = valid_date((string) ($_POST['expire'] ?? ''));
            $prot     = to_bool_int($_POST['protected'] ?? 0);

            // dns_id debe existir (o quedar NULL si 0).
            $dnsValue = null;
            if ($dnsId > 0) {
                $check = $pdo->prepare('SELECT 1 FROM dns WHERE id = ? LIMIT 1');
                $check->execute([$dnsId]);
                $dnsValue = $check->fetchColumn() !== false ? $dnsId : null;
            }

            if ($username === '' || $password === '') {
                $flash = 'Usuario y contraseña son obligatorios.';
                $flashType = 'error';
            } else {
                if ($action === 'create') {
                    $ins = $pdo->prepare(
                        'INSERT INTO credentials (username, password, dns_id, name, protected, expire, created_at)
                         VALUES (?, ?, ?, ?, ?, ?, ?)'
                    );
                    $ins->execute([$username, $password, $dnsValue, $name, $prot, $expire, now_iso()]);
                    $flash = 'Credencial creada.';
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $upd = $pdo->prepare(
                            'UPDATE credentials
                                SET username = ?, password = ?, dns_id = ?, name = ?, protected = ?, expire = ?
                              WHERE id = ?'
                        );
                        $upd->execute([$username, $password, $dnsValue, $name, $prot, $expire, $editId]);
                        $flash = 'Credencial actualizada.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM credentials WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'Credencial eliminada.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[credentials] ' . $ex->getMessage());
        $flash = 'No se pudo completar la operación.';
        $flashType = 'error';
    }
}

// ¿Editando?
$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM credentials WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

$dnsList = $pdo->query('SELECT id, title, url FROM dns ORDER BY title ASC, id ASC')->fetchAll();
$creds = $pdo->query(
    'SELECT c.id, c.username, c.password, c.name, c.protected, c.expire, c.created_at,
            d.title AS dns_title, d.url AS dns_url
       FROM credentials c
       LEFT JOIN dns d ON d.id = c.dns_id
      ORDER BY c.id DESC'
)->fetchAll();

$pageTitle = 'Credenciales';
require __DIR__ . '/lib/header.php';
?>

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

<div class="card mb-4">
    <div class="card-header"><h2 class="h6 mb-0"><?= $editing ? 'Editar credencial' : 'Añadir credencial' ?></h2></div>
    <div class="card-body">
        <?php if (count($dnsList) === 0): ?>
            <div class="alert alert-warning">No hay servidores DNS. Crea al menos uno en <a href="dns.php" class="alert-link">DNS</a> antes de asignarlo a una credencial.</div>
        <?php endif; ?>
        <form method="post" action="credentials.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="<?= $editing ? 'update' : 'create' ?>">
            <?php if ($editing): ?>
                <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
            <?php endif; ?>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label" for="username">Usuario</label>
                    <input type="text" class="form-control" id="username" name="username" value="<?= e($editing['username'] ?? '') ?>" placeholder="username" autocomplete="off" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="password">Contraseña</label>
                    <input type="text" class="form-control" id="password" name="password" value="<?= e($editing['password'] ?? '') ?>" placeholder="password" autocomplete="off" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="dns_id">Servidor DNS</label>
                    <select class="form-select" id="dns_id" name="dns_id">
                        <option value="0">— Sin DNS —</option>
                        <?php foreach ($dnsList as $dns): ?>
                            <option value="<?= (int) $dns['id'] ?>" <?= ((int) ($editing['dns_id'] ?? 0) === (int) $dns['id']) ? 'selected' : '' ?>>
                                <?= e($dns['title']) ?> · <?= e($dns['url']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="row g-3 mt-0">
                <div class="col-md-4">
                    <label class="form-label" for="name">Nombre de la lista</label>
                    <input type="text" class="form-control" id="name" name="name" value="<?= e($editing['name'] ?? '') ?>" placeholder="Mi Lista">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="expire">Expiración</label>
                    <input type="date" class="form-control" id="expire" name="expire" value="<?= e($editing['expire'] ?? '') ?>">
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="protected" name="protected" value="1" <?= (int) ($editing['protected'] ?? 0) === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label" for="protected">Protegida</label>
                    </div>
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Guardar cambios' : 'Añadir credencial' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="credentials.php">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header"><h2 class="h6 mb-0"><?= count($creds) ?> credencial<?= count($creds) === 1 ? '' : 'es' ?></h2></div>

    <?php if (count($creds) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">Aún no hay credenciales. Añade una arriba.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Usuario</th>
                        <th>Contraseña</th>
                        <th>DNS</th>
                        <th>Nombre</th>
                        <th>Expira</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($creds as $c): ?>
                        <tr>
                            <td class="mono"><?= e($c['username']) ?></td>
                            <td class="mono"><?= e($c['password']) ?></td>
                            <td class="mono">
                                <?php if (!empty($c['dns_url'])): ?>
                                    <?= e($c['dns_title']) ?> · <?= e($c['dns_url']) ?>
                                <?php else: ?>
                                    <span class="text-body-tertiary">—</span>
                                <?php endif; ?>
                            </td>
                            <td><?= e($c['name'] ?: '—') ?></td>
                            <td class="mono"><?= e($c['expire'] ?: '—') ?></td>
                            <td class="text-end actions-row">
                                <a class="btn btn-sm btn-outline-primary" href="credentials.php?edit=<?= (int) $c['id'] ?>"><i class="la la-edit"></i> Editar</a>
                                <form method="post" action="credentials.php" onsubmit="return confirm('¿Eliminar esta credencial?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $c['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'; ?>
