<?php
declare(strict_types=1);

ob_start();

$pageTitle = 'Banners';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/uploads.php';

$db = gpc_db();
$self = basename((string) ($_SERVER['PHP_SELF'] ?? 'banners.php'));
$self = $self !== '' ? $self : 'banners.php';

function gpc_banners_redirect(string $self): void
{
    if (!headers_sent()) {
        if (ob_get_length() !== false && ob_get_length() > 0) {
            ob_clean();
        }

        header('Location: ' . $self, true, 303);
    } else {
        echo '<script>window.location.href=' . json_encode($self, JSON_UNESCAPED_SLASHES) . ';</script>';
        echo '<noscript><meta http-equiv="refresh" content="0;url=' . gpc_h($self) . '"></noscript>';
    }

    exit;
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    if (!gpc_csrf_check($_GET['csrf'] ?? null)) {
        gpc_flash('bad', 'Token inválido');
        gpc_banners_redirect($self);
    }

    $id = (int) $_GET['delete'];

    try {
        $stmt = $db->prepare('SELECT image_path FROM banners WHERE id = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            gpc_upload_delete((string) $row['image_path']);

            $delete = $db->prepare('DELETE FROM banners WHERE id = :id');
            $delete->execute([':id' => $id]);

            gpc_flash('ok', 'Removido');
        } else {
            gpc_flash('bad', 'Banner não encontrado');
        }
    } catch (PDOException $e) {
        gpc_flash('bad', 'Erro ao remover banner');
    }

    gpc_banners_redirect($self);
}

if (isset($_GET['toggle']) && is_numeric($_GET['toggle'])) {
    if (!gpc_csrf_check($_GET['csrf'] ?? null)) {
        gpc_flash('bad', 'Token inválido');
        gpc_banners_redirect($self);
    }

    $id = (int) $_GET['toggle'];

    try {
        $stmt = $db->prepare('UPDATE banners SET active = CASE WHEN active = 1 THEN 0 ELSE 1 END WHERE id = :id');
        $stmt->execute([':id' => $id]);

        if ($stmt->rowCount() > 0) {
            gpc_flash('ok', 'Status atualizado');
        } else {
            gpc_flash('bad', 'Banner não encontrado');
        }
    } catch (PDOException $e) {
        gpc_flash('bad', 'Erro ao atualizar status');
    }

    gpc_banners_redirect($self);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!gpc_csrf_check($_POST['csrf'] ?? null)) {
        gpc_flash('bad', 'Token inválido');
        gpc_banners_redirect($self);
    }

    $title = trim((string) ($_POST['title'] ?? ''));

    if (!isset($_FILES['image']) || !is_array($_FILES['image']) || empty($_FILES['image']['tmp_name'])) {
        gpc_flash('bad', 'Selecione uma imagem');
    } else {
        try {
            $result = gpc_upload_image($_FILES['image'], 'ads');

            if (is_array($result) && !empty($result['ok']) && !empty($result['path'])) {
                $order = (int) $db->query('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM banners')->fetchColumn();

                $stmt = $db->prepare('INSERT INTO banners (title, image_path, sort_order) VALUES (:t, :p, :o)');
                $stmt->execute([
                    ':t' => $title,
                    ':p' => (string) $result['path'],
                    ':o' => $order,
                ]);

                gpc_flash('ok', 'Adicionado');
            } else {
                gpc_flash('bad', (string) ($result['error'] ?? 'Upload falhou'));
            }
        } catch (PDOException $e) {
            gpc_flash('bad', 'Erro ao salvar banner');
        } catch (Throwable $e) {
            gpc_flash('bad', 'Erro ao enviar imagem');
        }
    }

    gpc_banners_redirect($self);
}

try {
    $rows = $db->query('SELECT * FROM banners ORDER BY sort_order ASC, id ASC')->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $rows = [];
    gpc_flash('bad', 'Erro ao carregar banners');
}

$csrf = gpc_csrf_token();
?>

<div class="card">
    <div class="card-body">
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">

            <div class="form-grid">
                <div class="field">
                    <label>Título</label>
                    <input type="text" name="title" maxlength="120">
                </div>

                <div class="field">
                    <label>Imagem</label>
                    <input type="file" name="image" accept="image/jpeg,image/png,image/gif,image/webp" required>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn">
                    <i data-lucide="plus"></i> Adicionar
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body flush">
        <div class="table-scroll">
            <table>
                <thead>
                    <tr>
                        <th></th>
                        <th>Título</th>
                        <th>Status</th>
                        <th></th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($rows as $r): ?>
                        <?php
                        $id = (int) ($r['id'] ?? 0);
                        $title = (string) ($r['title'] ?? '');
                        $imagePath = (string) ($r['image_path'] ?? '');
                        $active = !empty($r['active']);
                        $thumb = $imagePath !== '' ? gpc_upload_public_path($imagePath) : '';
                        ?>
                        <tr>
                            <td>
                                <?php if ($thumb !== ''): ?>
                                    <img class="thumb" src="<?= gpc_h($thumb) ?>" alt="<?= gpc_h($title) ?>">
                                <?php endif; ?>
                            </td>

                            <td><?= gpc_h($title !== '' ? $title : 'Sem título') ?></td>

                            <td>
                                <span class="badge <?= $active ? 'badge-ok' : 'badge-bad' ?>">
                                    <?= $active ? 'On' : 'Off' ?>
                                </span>
                            </td>

                            <td class="row-actions">
                                <a class="btn btn-sm btn-ghost btn-icon"
                                   href="?toggle=<?= $id ?>&csrf=<?= urlencode((string) $csrf) ?>"
                                   title="Ativar ou desativar">
                                    <i data-lucide="power"></i>
                                </a>

                                <a class="btn btn-sm btn-danger btn-icon"
                                   href="?delete=<?= $id ?>&csrf=<?= urlencode((string) $csrf) ?>"
                                   data-confirm="Remover?"
                                   title="Remover">
                                    <i data-lucide="trash-2"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="4" class="empty">Nenhum banner</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>