<?php
session_start();
if(!isset($_SESSION['rev_logado'])){ header("Location: index_rev.php"); exit(); }
include('../api/conexao_rev.php');

$id_rev = $_SESSION['rev_logado'];
$base_file = basename($_SERVER["SCRIPT_NAME"]);

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$jsonFile = "../api/db/banner_rev_" . $id_rev . ".json";
$banners = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

// LÓGICA DE SALVAMENTO
if (isset($_POST['submit']) || isset($_POST['submitU'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) { exit('Erro'); }

    $novoBanner = [
        'id' => isset($_POST['id']) ? $_POST['id'] : uniqid(),
        'url' => $_POST['url']
    ];

    if (isset($_POST['submitU'])) {
        foreach ($banners as $key => $b) {
            if ($b['id'] == $_POST['id']) { $banners[$key] = $novoBanner; break; }
        }
        $_SESSION['msg_ok'] = "Banner atualizado!";
    } else {
        $banners[] = $novoBanner;
        $_SESSION['msg_ok'] = "Banner adicionado!";
    }

    file_put_contents($jsonFile, json_encode(array_values($banners), JSON_UNESCAPED_SLASHES));
    header("Location: $base_file"); exit;
}

// LÓGICA DE EXCLUSÃO
if (isset($_GET['delete_confirmed'])) {
    $target_id = $_GET['delete_confirmed'];
    $banners = array_filter($banners, function($b) use ($target_id) { return $b['id'] != $target_id; });
    file_put_contents($jsonFile, json_encode(array_values($banners), JSON_UNESCAPED_SLASHES));
    $_SESSION['msg_ok'] = "Banner removido!";
    header("Location: $base_file"); exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Banners</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { box-sizing: border-box; }
        html, body { background-color: #020617 !important; color: #e2e8f0 !important; font-family: 'Inter', sans-serif; margin: 0; padding: 0; }
        .container-fluid { padding: 30px 15px !important; max-width: 1000px; margin: 0 auto; }
        
        .btn-back-nav { display: inline-flex; align-items: center; gap: 8px; color: #64748b; text-decoration: none !important; font-size: 0.85rem; font-weight: 600; margin-bottom: 20px; transition: 0.3s; }
        .btn-back-nav:hover { color: #3b82f6; }
        
        /* HEADER */
        .top-nav { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .btn-create-new { background: #3b82f6; color: #fff !important; padding: 12px 20px; border-radius: 12px; font-weight: 800; font-size: 0.8rem; text-transform: uppercase; text-decoration: none !important; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2); }

        /* GRID E CARDS */
        .ads-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
        .banner-card { background: #070e1b; border: 1px solid #1e293b; border-radius: 20px; overflow: hidden; }
        
        .banner-preview-container { width: 100%; aspect-ratio: 16 / 9; background: #000; position: relative; }
        .banner-preview-container img { width: 100%; height: 100%; object-fit: cover; }
        
        .banner-actions { display: flex; padding: 15px 20px; background: #070e1b; justify-content: space-between; align-items: center; border-top: 1px solid rgba(255,255,255,0.05); }
        
        .btn-action-premium { width: 42px; height: 42px; border-radius: 12px; display: flex; align-items: center; justify-content: center; border: none; cursor: pointer; transition: 0.2s; text-decoration: none; }
        .btn-edit-lux { background: #1e293b; color: #3b82f6; }
        .btn-delete-lux { background: #1e293b; color: #ef4444; }

        /* FORMULÁRIO */
        .form-lux { background: #070e1b; border: 1px solid #1e293b; border-radius: 24px; padding: 30px; max-width: 600px; margin: 0 auto; }
        label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; }
        .input-lux { width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; color: #fff !important; padding: 16px; border-radius: 14px; margin-bottom: 20px; outline: none; }
        .btn-save-lux { width: 100%; background: #3b82f6; color: #fff; padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase; border: none; cursor: pointer; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2); }
    </style>
</head>
<body>

<div class="container-fluid">

    <?php if (isset($_GET['create']) || isset($_GET['update'])): 
        $edit_data = null;
        if (isset($_GET['update'])) {
            foreach ($banners as $b) { if ($b['id'] == $_GET['update']) { $edit_data = $b; break; } }
        }
    ?>
        <a href="<?= $base_file ?>" class="btn-back-nav"><i class="fas fa-arrow-left"></i> VOLTAR</a>
        <div class="form-lux">
            <h2 style="font-weight: 800; margin-bottom: 25px;"><?= isset($edit_data) ? 'Editar' : 'Novo' ?> Banner</h2>
            <form method="post">
                <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
                <?php if($edit_data): ?><input type="hidden" name="id" value="<?= $edit_data['id'] ?>"><?php endif; ?>

                <label>URL DIRETA DA IMAGEM</label>
                <input type="text" name="url" class="input-lux" value="<?= $edit_data['url'] ?? '' ?>" placeholder="https://linkdaimagem.com/foto.jpg" required>

                <button type="submit" name="<?= isset($edit_data) ? 'submitU' : 'submit' ?>" class="btn-save-lux">
                    Confirmar e Salvar
                </button>
            </form>
        </div>

    <?php else: ?>
        <a href="dashboard_rev.php" class="btn-back-nav"><i class="fas fa-columns"></i> VOLTAR AO DASHBOARD</a>
        
        <div class="top-nav">
            <h1 style="font-weight: 900; font-size: 1.4rem; margin: 0;">Banners Rotativos</h1>
            <a href="?create" class="btn-create-new"><i class="fas fa-plus"></i> Novo</a>
        </div>

        <div class="ads-grid">
            <?php foreach ($banners as $row): ?>
                <div class="banner-card">
                    <div class="banner-preview-container">
                        <img src="<?= htmlspecialchars($row['url']) ?>" onerror="this.src='https://placehold.co/600x337/0f172a/334155?text=Preview+Indisponível'">
                    </div>

                    <div class="banner-actions">
                        <span style="font-size: 0.65rem; color: #475569; font-weight: 700;">ID: #<?= substr($row['id'], 0, 5) ?></span>
                        <div style="display: flex; gap: 10px;">
                            <a href="?update=<?= $row['id'] ?>" class="btn-action-premium btn-edit-lux">
                                <i class="fas fa-pen"></i>
                            </a>
                            <button onclick="confirmarExclusao('<?= $row['id'] ?>')" class="btn-action-premium btn-delete-lux">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script>
    <?php if (isset($_SESSION['msg_ok'])): ?>
        Swal.fire({ icon: 'success', title: 'Sucesso', text: '<?= $_SESSION['msg_ok'] ?>', background: '#070e1b', color: '#fff', confirmButtonColor: '#3b82f6' });
        <?php unset($_SESSION['msg_ok']); ?>
    <?php endif; ?>

    function confirmarExclusao(id) {
        Swal.fire({
            title: 'Excluir banner?', text: "A imagem sairá imediatamente do aplicativo.", icon: 'warning',
            showCancelButton: true, background: '#070e1b', color: '#fff',
            confirmButtonColor: '#ef4444', cancelButtonColor: '#1e293b',
            confirmButtonText: 'SIM', cancelButtonText: 'NÃO'
        }).then((result) => { if (result.isConfirmed) { window.location.href = '<?= $base_file ?>?delete_confirmed=' + id; } });
    }
</script>
</body>
</html>
