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

// Proteção básica contra acesso direto se não logado
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

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

define('UPLOAD_DIR', 'uploads/');
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"]);
$msg_js = "";

// --- LÓGICA DE PROCESSAMENTO (CORRIGIDA) ---

// 1. CRIAR OU EDITAR
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['upload']) || isset($_POST['submit_edit']))) {
    
    // Validação de Token
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        die("Token de segurança inválido.");
    }

    $is_edit = isset($_POST['submit_edit']);
    $title = preg_replace("/[^a-zA-Z0-9\s]/", "-", trim($is_edit ? $_POST['editTitle'] : $_POST['title']));
    $image = $is_edit ? $_FILES['editBanner'] : $_FILES['banner'];

    // Se for edição e não enviou imagem nova, apenas renomeamos (se o título mudou)
    if ($is_edit && $image['error'] == UPLOAD_ERR_NO_FILE) {
        $old_path = UPLOAD_DIR . basename($_POST['old_filename']);
        $extension = pathinfo($old_path, PATHINFO_EXTENSION);
        $new_name = $title . '_' . time() . '.' . $extension;
        
        if (file_exists($old_path)) {
            rename($old_path, UPLOAD_DIR . $new_name);
            $_SESSION['flash_msg'] = "Título atualizado!";
            header("Location: $base_file"); exit;
        }
    } 
    // Se enviou imagem (Novo ou Edição com troca de arquivo)
    elseif ($image['error'] == UPLOAD_ERR_OK) {
        $file_info = getimagesize($image['tmp_name']);
        if ($file_info && in_array($file_info['mime'], ALLOWED_TYPES)) {
            $extension = pathinfo($image['name'], PATHINFO_EXTENSION);
            $new_name = $title . '_' . time() . '.' . $extension;
            $target = UPLOAD_DIR . $new_name;

            if (move_uploaded_file($image['tmp_name'], $target)) {
                if ($is_edit) {
                    $old = UPLOAD_DIR . basename($_POST['old_filename']);
                    if (file_exists($old)) unlink($old);
                }
                $_SESSION['flash_msg'] = "QR-Code salvo com sucesso!";
                header("Location: $base_file"); exit;
            }
        } else {
            $msg_js = "Swal.fire({icon:'error', title:'Erro', text:'Formato de imagem inválido!', background:'#070e1b', color:'#fff'});";
        }
    }
}

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

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

<style>
    /* DESIGN SYSTEM MANUTIDO */
    html, body, .wrapper, .main-panel, .content, .container-fluid { background-color: #020617 !important; color: #f8fafc !important; overflow-x: hidden; }
    .navbar, .lua-icon, .fa-moon, .fa-sun, #dark-mode-switch { display: none !important; }

    #formContainer { display: none; min-height: 80vh; width: 100%; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; }
    .form-lux { width: 100%; max-width: 400px; background: #070e1b; border-radius: 28px; padding: 30px; border: 1px solid #1e293b; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); box-sizing: border-box; }

    .input-lux { width: 100%; box-sizing: border-box; background: #0f172a !important; border: 1px solid #1e293b !important; color: #fff !important; padding: 15px; border-radius: 14px; margin-bottom: 20px; display: block; }
    .btn-submit-lux { width: 100%; box-sizing: border-box; background: #f59e0b !important; color: #000 !important; padding: 16px; border-radius: 14px; font-weight: 800; border: none; cursor: pointer; text-transform: uppercase; display: block; }

    .visual-frame { width: 100%; aspect-ratio: 1 / 1; background: #ffffff; border-radius: 18px; display: flex; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; position: relative; box-shadow: inset 0px 0px 15px rgba(0,0,0,0.1); border: 4px solid #0f172a; }
    .visual-frame img { max-width: 100%; max-height: 100%; object-fit: contain; }

    .qr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 25px; max-width: 1200px; margin: 0 auto; }
    .card-qr-lux { background: #070e1b; border: 1px solid #1e293b; border-radius: 24px; padding: 12px; box-sizing: border-box; }

    .top-nav-lux { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; max-width: 1200px; margin: 0 auto 30px auto; }
    .btn-amber-lux { background: #f59e0b !important; color: #000 !important; padding: 12px 24px; border-radius: 14px; font-weight: 800; border: none; cursor: pointer; }
    .lux-title { font-size: 0.95rem; font-weight: 800; color: #fff; display: block; padding: 10px 5px; }
    .actions-footer { display: flex; justify-content: flex-end; gap: 10px; }
    .btn-circle-lux { width: 42px; height: 42px; border-radius: 12px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; }
    .btn-edit-qr { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
    .btn-del-qr { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
</style>

<div class="container-fluid">

    <div id="formContainer">
        <div class="form-lux">
            <h2 id="formHeader" style="margin-bottom: 25px; font-weight: 900; color: #fff; text-align: center;">Gerenciar QR</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:#f59e0b; font-size:0.7rem; font-weight:800; display:block; margin-bottom:8px;">TÍTULO</label>
                <input type="text" name="title" id="form_title" class="input-lux" placeholder="Ex: Pix Loja" required>

                <label style="color:#f59e0b; font-size:0.7rem; font-weight:800; display:block; margin-bottom:8px;">IMAGEM</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">SALVAR</button>
            </form>
            <button onclick="toggleForm()" style="width:100%; background:none; border:none; color:#64748b; font-weight:700; cursor:pointer; margin-top: 15px;">CANCELAR</button>
        </div>
    </div>

    <div id="listContainer">
        <div class="top-nav-lux">
            <div>
                <h1 style="font-weight: 900; margin: 0; font-size: 1.8rem;">Meus QR-Codes</h1>
                <p style="color: #f59e0b; font-size: 0.75rem; font-weight: 800;">REPOSITÓRIO DE PAGAMENTOS</p>
            </div>
            <button class="btn-amber-lux" onclick="showAddForm()"><i class="fas fa-plus-circle"></i> ADICIONAR</button>
        </div>

        <div class="qr-grid">
            <?php 
            $files = glob(UPLOAD_DIR . "*.{jpg,jpeg,png,gif}", GLOB_BRACE);
            if ($files) {
                foreach ($files as $file):
                    $fullname = basename($file);
                    // Pega o título removendo o timestamp e a extensão
                    $display_name = preg_replace('/_\d+$/', '', pathinfo($fullname, PATHINFO_FILENAME));
            ?>
                <div class="card-qr-lux">
                    <div class="visual-frame">
                        <img src="<?= $file ?>?v=<?= time() ?>" alt="QR">
                    </div>
                    <div class="info-overlay">
                        <span class="lux-title"><?= htmlspecialchars($display_name) ?></span>
                        <div class="actions-footer">
                            <button onclick="showEditForm('<?= $display_name ?>', '<?= $fullname ?>')" class="btn-circle-lux btn-edit-qr"><i class="fas fa-pen"></i></button>
                            <button onclick="confirmDelete('<?= $fullname ?>')" class="btn-circle-lux btn-del-qr"><i class="fas fa-trash-alt"></i></button>
                        </div>
                    </div>
                </div>
            <?php endforeach; 
            } else { echo "<p style='grid-column:1/-1; text-align:center; opacity:0.5;'>Nenhum QR-Code encontrado.</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: 'Sucesso', text: '<?= $_SESSION['flash_msg'] ?>', background: '#070e1b', color: '#fff', confirmButtonColor: '#f59e0b' });
        <?php unset($_SESSION['flash_msg']); ?>
    <?php endif; ?>
    <?= $msg_js ?>

    function toggleForm() {
        $('#listContainer').toggle();
        $('#formContainer').css('display', $('#formContainer').css('display') === 'none' ? 'flex' : 'none');
    }

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

    function showEditForm(title, fullname) {
        $('#formHeader').text('Editar QR-Code');
        $('#submitBtn').attr('name', 'submit_edit').text('ATUALIZAR');
        $('#form_title').attr('name', 'editTitle').val(title);
        $('#form_file').attr('name', 'editBanner').removeAttr('required');
        $('#old_filename').val(fullname);
        toggleForm();
    }

    function confirmDelete(filename) {
        Swal.fire({
            title: 'Remover?',
            text: "O arquivo será deletado permanentemente.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#f43f5e',
            confirmButtonText: 'Sim, deletar',
            background: '#070e1b', color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "<?= $base_file ?>?delete=" + filename;
            }
        });
    }
</script>

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