<?php
/**
 * credentials.php — Reseller credentials: list, add, edit, and delete.
 *
 * A credential = username + password + DNS (server) + name + expiration date.
 * Any device logging in (api/device/login) with that
 * username/password receives the resolved Xtream playlist from the DNS.
 * Everything is stored via POST with CSRF and prepared statements.
 */

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 must exist (or set to NULL if 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 = 'Username and password are required.';
                $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 = 'Credential created.';
                } 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 = 'Credential updated.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM credentials WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'Credential deleted.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[credentials] ' . $ex->getMessage());
        $flash = 'Could not complete the operation.';
        $flashType = 'error';
    }
}

// Editing?
$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 = 'Credentials';
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 ? 'Edit Credential' : 'Add Credential' ?></h2></div>
    <div class="card-body">
        <?php if (count($dnsList) === 0): ?>
            <div class="alert alert-warning">No DNS servers found. Create at least one in <a href="dns.php" class="alert-link">DNS</a> before assigning it to a credential.</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">Username</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">Password</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">DNS Server</label>
                    <select class="form-select" id="dns_id" name="dns_id">
                        <option value="0">— No 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">Playlist Name</label>
                    <input type="text" class="form-control" id="name" name="name" value="<?= e($editing['name'] ?? '') ?>" placeholder="My List">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="expire">Expiration</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">Protected</label>
                    </div>
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Save Changes' : 'Add Credential' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="credentials.php">Cancel</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

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

    <?php if (count($creds) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">No credentials yet. Add one above.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Password</th>
                        <th>DNS</th>
                        <th>Name</th>
                        <th>Expires</th>
                        <th class="text-end">Actions</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> Edit</a>
                                <form method="post" action="credentials.php" onsubmit="return confirm('Delete this credential?');" 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> Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

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