<?php
include('includes/auth.php');

$table_name = 'dns';
$page = 'main.php';

// Fetch record for update
$resU = null;
if (isset($_GET['update'])) {
    $resU = $db->select($table_name, '*', 'id = :id', '', [':id' => (int) $_GET['update']]);
}

// Handle update submission
if (isset($_POST['submitU'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $updateData = [
        'title' => sanitize($_POST['title'] ?? ''),
        'url' => trim($_POST['url'] ?? ''),
    ];
    $db->update($table_name, $updateData, 'id = :id', [':id' => (int) $_GET['update']]);
    header("Location: {$page}?status=1");
    exit;
}

// Handle new submission
if (isset($_POST['submit'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $insertData = [
        'title' => sanitize($_POST['title'] ?? ''),
        'url' => trim($_POST['url'] ?? ''),
    ];
    $db->insert($table_name, $insertData);
    header("Location: {$page}?status=1");
    exit;
}

// Handle delete
if (isset($_GET['delete'])) {
    $db->delete($table_name, 'id = :id', [':id' => (int) $_GET['delete']]);
    header("Location: {$page}?status=2");
    exit;
}

// --- All redirects handled, now output HTML ---
include('includes/header.php');

$res = $db->select($table_name, '*', '', '');
$csrfToken = generate_token();
?>

<?php if (isset($_GET['create'])): ?>
<!-- Create Form -->
<div class="md-card md-card--elevated" style="max-width: 700px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('add_circle', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Add Playlist</h2>
    </div>
    <div class="md-card__content">
        <form method="post" id="dnsForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="title" id="title" class="md-text-field__input" placeholder=" " required>
                <label for="title" class="md-text-field__label">Name</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="url" id="url" class="md-text-field__input" placeholder=" " required>
                <label for="url" class="md-text-field__label">Server URL</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <p class="md-helper-text">Enter the server URL. Users will log in with their own username and password.</p>

            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submit" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Save</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php elseif (isset($_GET['update']) && $resU): ?>
<!-- Update Form -->
<div class="md-card md-card--elevated" style="max-width: 700px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('edit', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Edit Playlist</h2>
    </div>
    <div class="md-card__content">
        <form method="post" id="dnsForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="title" id="title" class="md-text-field__input" placeholder=" " required
                       value="<?= htmlspecialchars($resU[0]['title'] ?? '') ?>">
                <label for="title" class="md-text-field__label">Name</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="url" id="url" class="md-text-field__input" placeholder=" " required
                       value="<?= htmlspecialchars($resU[0]['url'] ?? '') ?>">
                <label for="url" class="md-text-field__label">Server URL</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <p class="md-helper-text">Enter the server URL. Users will log in with their own username and password.</p>

            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submitU" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Update</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php else: ?>
<!-- Playlist List -->
<div class="md-card md-card--elevated">
    <div class="md-card__header">
        <?= icon('dns', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Playlists</h2>
        <a href="<?= $page ?>?create" class="md-button md-button--filled-tonal md-button--icon-right">
            <?= icon('add') ?>
            <span class="md-button__label">Add New</span>
        </a>
    </div>
    <div class="md-card__content md-card__content--table">
        <?php if (empty($res)): ?>
            <div class="md-empty-state">
                <?= icon('dns', 'md-empty-state__icon') ?>
                <p class="md-empty-state__text">No playlists configured yet.</p>
            </div>
        <?php else: ?>
        <div class="md-table-container">
            <table class="md-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Server URL</th>
                        <th class="md-table__actions-col">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($res as $row): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['title'] ?? '') ?></td>
                        <td class="md-table__mono" style="max-width:200px; overflow:hidden; text-overflow:ellipsis;"><?= htmlspecialchars($row['url'] ?? '') ?></td>
                        <td class="md-table__actions">
                            <a href="<?= $page ?>?update=<?= (int) $row['id'] ?>" class="md-icon-button" title="Edit">
                                <?= icon('edit') ?>
                            </a>
                            <button class="md-icon-button md-icon-button--error" title="Delete"
                                    onclick="showDeleteDialog('<?= $page ?>?delete=<?= (int) $row['id'] ?>')">
                                <?= icon('delete') ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php include('includes/footer.php'); ?>
