<?php
session_start();
include 'auth.php';

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

// Configurações de Diretório específicas para o Plano 3
define('UPLOAD_DIR', 'uploads4/');
define('ALLOWED_TYPES', ['image/jpeg', 'image/png', 'image/gif']);

if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Processamento de PHP (Lógica preservada e segura)
if (isset($_POST['upload']) || isset($_POST['submit'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php"); exit();
    }

    $is_edit = isset($_POST['submit']);
    $title = basename(trim($is_edit ? $_POST['editTitle'] : $_POST['title']));
    $image = $is_edit ? $_FILES['editBanner'] : $_FILES['banner'];

    if ($image['error'] == UPLOAD_ERR_OK) {
        $file_info = getimagesize($image['tmp_name']);
        if (in_array($file_info['mime'], ALLOWED_TYPES)) {
            $new_name = $title . '_' . time() . '.' . pathinfo($image['name'], PATHINFO_EXTENSION);
            $target = UPLOAD_DIR . $new_name;

            if (move_uploaded_file($image['tmp_name'], $target)) {
                if ($is_edit) {
                    $old = basename($_POST['old_filename']);
                    if (file_exists(UPLOAD_DIR . $old)) unlink(UPLOAD_DIR . $old);
                }
                $_SESSION['flash_msg'] = "Plano 3 atualizado com sucesso!";
                header("Location: $base_file"); exit;
            }
        }
    }
}

if (isset($_GET['delete'])) {
    $file_del = basename($_GET['delete']);
    if (file_exists(UPLOAD_DIR . $file_del)) {
        unlink(UPLOAD_DIR . $file_del);
        $_SESSION['flash_msg'] = "QR-Code removido!";
    }
    header("Location: $base_file"); exit;
}

include ('includes/header.php');
?>

<style>
    /* DESIGN SYSTEM ULTRA DARK PINK (PLANO 3) */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #f8fafc !important;
    }
    .navbar, .lua-icon, .fa-moon, .fa-sun { display: none !important; }
    .container-fluid { padding: 15px !important; }

    /* TOPO */
    .top-nav-lux {
        display: flex; justify-content: space-between; align-items: center;
        margin-bottom: 25px;
    }

    .btn-pink {
        background: linear-gradient(135deg, #db2777 0%, #be185d 100%);
        color: #fff !important; padding: 12px 24px; border-radius: 14px;
        font-weight: 800; font-size: 0.75rem; text-transform: uppercase;
        box-shadow: 0 10px 20px rgba(219, 39, 119, 0.2); border: none; cursor: pointer;
    }

    /* GRID */
    .qr-grid { display: grid; grid-template-columns: 1fr; gap: 20px; }

    .card-qr-lux {
        background: #0f172a; border: 1px solid #1e293b;
        border-radius: 26px; overflow: hidden; position: relative;
    }

    .visual-frame {
        width: 100%; aspect-ratio: 1 / 1; background: #fff;
        position: relative; overflow: hidden; display: flex; align-items: center; justify-content: center;
        padding: 30px;
    }
    .visual-frame img { max-width: 100%; height: auto; object-fit: contain; }

    .info-overlay { padding: 20px; background: #0f172a; border-top: 1px solid #1e293b; }

    .lux-title { font-size: 1.1rem; font-weight: 800; color: #fff; display: block; margin-bottom: 5px; }
    .badge-pink {
        background: rgba(219, 39, 119, 0.1); color: #f472b6;
        padding: 4px 10px; border-radius: 8px; font-size: 0.6rem;
        font-weight: 900; text-transform: uppercase; display: inline-block;
        border: 1px solid rgba(219, 39, 119, 0.2);
    }

    /* BOTÕES DE AÇÃO */
    .actions-footer {
        padding: 15px 20px; display: flex; justify-content: flex-end;
        gap: 12px; background: #0f172a; border-top: 1px solid rgba(255,255,255,0.03);
    }

    .btn-circle-lux {
        width: 44px; height: 44px; border-radius: 12px;
        display: flex; align-items: center; justify-content: center;
        border: none; cursor: pointer; transition: 0.2s;
    }
    .btn-edit-pk { background: #1e293b; color: #f472b6; }
    .btn-del-pk { background: #1e293b; color: #fb7185; }

    /* FORMULÁRIOS */
    .form-lux { background: #070e1b; border-radius: 30px; padding: 30px; border: 1px solid #1e293b; margin-bottom: 20px; }
    .input-lux {
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important;
        color: #fff !important; padding: 18px; border-radius: 16px; margin-bottom: 20px;
    }
    .btn-submit-lux {
        width: 100%; background: #db2777; color: #fff; padding: 20px;
        border-radius: 18px; font-weight: 800; text-transform: uppercase; border: none;
        box-shadow: 0 10px 20px rgba(219, 39, 119, 0.3); cursor: pointer;
    }

    @media (min-width: 768px) { .qr-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); } }
</style>

<div class="container-fluid">

    <div id="formContainer" style="display: none;">
        <div class="top-nav-lux">
            <button onclick="toggleForm()" style="background:none; border:none; color:#64748b; font-weight:700; cursor:pointer;">
                <i class="fas fa-arrow-left"></i> VOLTAR
            </button>
        </div>
        
        <div class="form-lux">
            <h2 id="formHeader" style="font-weight: 900; margin-bottom: 30px; letter-spacing: -1px;">Novo QR Plano 3</h2>
            <form id="mainForm" method="post" enctype="multipart/form-data">
                <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
                <input type="hidden" name="old_filename" id="old_filename">
                
                <label style="color:#db2777; font-size:0.65rem; font-weight:900; margin-left:5px; letter-spacing:1px;">NOME DO PLANO 3</label>
                <input type="text" name="title" id="form_title" class="input-lux" placeholder="Ex: Combo Master" required>

                <label style="color:#db2777; font-size:0.65rem; font-weight:900; margin-left:5px; letter-spacing:1px;">IMAGEM DO QR-CODE</label>
                <input type="file" name="banner" id="form_file" class="input-lux" accept=".jpg,.jpeg,.png,.gif">

                <button type="submit" id="submitBtn" name="upload" class="btn-submit-lux">
                    Finalizar Configuração
                </button>
            </form>
        </div>
    </div>

    <div id="listContainer">
        <div class="top-nav-lux">
            <div>
                <h1 style="font-weight: 900; font-size: 1.5rem; margin: 0; letter-spacing: -1px;">QR Plano-3</h1>
                <p style="color: #db2777; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; opacity: 0.8;">Pasta: uploads4/</p>
            </div>
            <button class="btn-pink" onclick="showAddForm()"><i class="fas fa-plus"></i> ADICIONAR QR</button>
        </div>

        <div class="qr-grid">
            <?php 
            if (is_dir(UPLOAD_DIR)) {
                $files = glob(UPLOAD_DIR . "*.{jpg,jpeg,png,gif}", GLOB_BRACE);
                foreach ($files as $file):
                    $fullname = basename($file);
                    $filename = pathinfo($file, PATHINFO_FILENAME);
            ?>
                <div class="card-qr-lux">
                    <div class="visual-frame">
                        <img src="<?= $file ?>?v=<?= time() ?>" alt="QR-Code">
                    </div>
                    <div class="info-overlay">
                        <span class="badge-pink">Premium Ativo</span>
                        <span class="lux-title"><?= htmlspecialchars($filename) ?></span>
                    </div>
                    <div class="actions-footer">
                        <button onclick="showEditForm('<?= $filename ?>', '<?= $fullname ?>')" class="btn-circle-lux btn-edit-pk">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="confirmDelete('<?= $fullname ?>')" class="btn-circle-lux btn-del-pk">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            <?php endforeach; 
                if(empty($files)) echo "<p style='opacity:0.3; text-align:center; grid-column: 1/-1; padding: 50px;'>Aguardando novos QR-Codes.</p>";
            } 
            ?>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    <?php if (isset($_SESSION['flash_msg'])): ?>
        Swal.fire({
            icon: 'success', title: 'Excelente!', text: '<?= $_SESSION['flash_msg'] ?>',
            background: '#020617', color: '#fff', confirmButtonColor: '#db2777'
        });
        <?php unset($_SESSION['flash_msg']); ?>
    <?php endif; ?>

    function toggleForm() {
        $('#listContainer').fadeToggle(200);
        $('#formContainer').fadeToggle(200);
    }

    function showAddForm() {
        $('#formHeader').text('Novo QR Plano 3');
        $('#submitBtn').attr('name', 'upload');
        $('#form_title').attr('name', 'title').val('');
        $('#form_file').attr('name', 'banner').attr('required', true);
        toggleForm();
    }

    function showEditForm(name, fullname) {
        $('#formHeader').text('Ajustar QR Plano 3');
        $('#submitBtn').attr('name', 'submit');
        $('#form_title').attr('name', 'editTitle').val(name);
        $('#form_file').attr('name', 'editBanner').removeAttr('required');
        $('#old_filename').val(fullname);
        toggleForm();
    }

    function confirmDelete(filename) {
        Swal.fire({
            title: 'Excluir QR-Code?',
            text: "Esta ação removerá permanentemente o arquivo da pasta uploads4/",
            icon: 'warning',
            showCancelButton: true,
            background: '#020617', color: '#fff',
            confirmButtonColor: '#fb7185', cancelButtonColor: '#1e293b',
            confirmButtonText: 'APAGAR AGORA', cancelButtonText: 'MANTER'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "<?= $base_file ?>?delete=" + filename;
            }
        });
    }
</script>

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