<?php
require_once __DIR__ . '/admin/includes/bootstrap.php';
require_once __DIR__ . '/admin/includes/data_providers.php';

$pdo = admin_pdo();

if (isset($_GET['skip'])) {
    admin_mark_token_setup_complete();
    header('Location: /admin.php');
    exit;
}

$errors = [];
$success = null;
$settings = admin_get_token_settings($pdo);
$csrfToken = admin_csrf_token('token_setup');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_validate_csrf('token_setup', $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid or expired security token. Please try again.';
    }

    $name = trim($_POST['token_name'] ?? '');
    $symbol = strtoupper(trim($_POST['token_symbol'] ?? ''));
    $plural = trim($_POST['token_plural'] ?? '');
    $description = trim($_POST['token_description'] ?? '');

    if ($name === '') {
        $errors[] = 'Please provide a token name.';
    }

    if ($symbol === '') {
        $symbol = strtoupper(substr($name, 0, 3));
    }

    if ($plural === '') {
        $plural = $name . 's';
    }

    if (empty($errors)) {
        admin_update_token_settings($pdo, [
            'name' => $name,
            'symbol' => $symbol,
            'plural' => $plural,
            'description' => $description !== '' ? $description : 'Platform currency for tips and donations',
        ]);

        $settings = admin_get_token_settings($pdo);

        if (!empty($_FILES['token_icon']['name'])) {
            $upload = admin_handle_token_icon_upload($pdo, $_FILES['token_icon']);
            if ($upload['success']) {
                $settings['icon'] = $upload['path'];
                $success = $upload['message'];
            } else {
                $errors[] = $upload['message'];
            }
        }

        if (empty($errors)) {
        admin_mark_token_setup_complete();
        unset($_SESSION['admin_csrf_token_setup']);
        header('Location: /admin.php');
        exit;
    }
}
}

admin_page_start('Token Setup', 'tokens', ['skip_token_setup_check' => true]);
?>

<section class="card">
    <div class="card__header">
        <h2>Welcome to the EasyStream Token Setup</h2>
        <a class="admin-button admin-button--ghost" href="?skip=1">Skip for now</a>
    </div>
    <p style="margin-bottom: 18px;">
        Choose how your platform currency appears across the site. You can adjust these settings later in the
        token customization panel.
    </p>

    <?php if ($errors): ?>
        <div class="empty-state" style="border-color: #fecdd3; background: #fff1f2; color: #b91c1c;">
            <?= admin_escape(implode(' ', $errors)) ?>
        </div>
    <?php elseif ($success): ?>
        <div class="empty-state" style="border-color: #bbf7d0; background: #f0fdf4; color: #15803d;">
            <?= admin_escape($success) ?>
        </div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" style="display: grid; gap: 18px; margin-top: 24px;">
        <div>
            <label for="token_name" style="display:block; font-weight:600; margin-bottom:6px;">Token Name</label>
            <input type="text" id="token_name" name="token_name" value="<?= admin_escape($settings['name']) ?>"
                   required maxlength="50"
                   style="width:100%; padding:10px 12px; border-radius:8px; border:1px solid #d1d5db;">
        </div>

        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px;">
            <div>
                <label for="token_symbol" style="display:block; font-weight:600; margin-bottom:6px;">Token Symbol</label>
                <input type="text" id="token_symbol" name="token_symbol" value="<?= admin_escape($settings['symbol']) ?>"
                       maxlength="6"
                       style="width:100%; padding:10px 12px; border-radius:8px; border:1px solid #d1d5db;">
            </div>
            <div>
                <label for="token_plural" style="display:block; font-weight:600; margin-bottom:6px;">Plural Name</label>
                <input type="text" id="token_plural" name="token_plural" value="<?= admin_escape($settings['plural']) ?>"
                       maxlength="50"
                       style="width:100%; padding:10px 12px; border-radius:8px; border:1px solid #d1d5db;">
            </div>
        </div>

        <div>
            <label for="token_description" style="display:block; font-weight:600; margin-bottom:6px;">Description</label>
            <textarea id="token_description" name="token_description" rows="3"
                      style="width:100%; padding:10px 12px; border-radius:8px; border:1px solid #d1d5db; resize:vertical;"><?= admin_escape($settings['description']) ?></textarea>
        </div>

        <div>
            <label for="token_icon" style="display:block; font-weight:600; margin-bottom:6px;">Token Icon</label>
            <div style="display:flex; align-items:center; gap:16px;">
                <img src="<?= admin_escape($settings['icon']) ?>" alt="Current token icon" style="width:64px; height:64px; object-fit:contain; border-radius:8px; border:1px solid #e5e7eb;">
                <input type="file" id="token_icon" name="token_icon" accept="image/png,image/jpeg,image/gif,image/svg+xml">
            </div>
            <p style="margin-top:8px; font-size:0.9rem; color:#6b7280;">PNG, JPG, GIF, or SVG up to 2MB.</p>
        </div>

        <input type="hidden" name="csrf_token" value="<?= admin_escape($csrfToken) ?>">

        <div style="display:flex; gap:12px; flex-wrap:wrap;">
            <button type="submit" class="admin-button admin-button--primary">Save and Continue</button>
            <a class="admin-button admin-button--ghost" href="/f_modules/m_backend/token_customization.php" target="_blank">Advanced settings</a>
        </div>
    </form>
</section>

<?php
admin_page_end();
