<?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"]);
$dir_img = '../api/img_qrcodes/';

if (!is_dir($dir_img)) mkdir($dir_img, 0777, true);
if (!isset($_SESSION['admin_token'])) { $_SESSION['admin_token'] = bin2hex(random_bytes(32)); }

// 1. CRIAR OU EDITAR
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['upload']) || isset($_POST['submit_edit']))) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) { die("Token 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'];

    // Lógica para novo arquivo ou troca de imagem
    if ($image['error'] == UPLOAD_ERR_OK) {
        $ext = pathinfo($image['name'], PATHINFO_EXTENSION);
        $new_name = "qr_" . $id_rev . "_" . $title . "_" . time() . "." . $ext;
        
        if (move_uploaded_file($image['tmp_name'], $dir_img . $new_name)) {
            if ($is_edit) {
                $old = $dir_img . basename($_POST['old_filename']);
                if (file_exists($old)) unlink($old);
            }
            $_SESSION['msg_ok'] = "QR-Code salvo!";
            header("Location: $base_file"); exit;
        }
    } 
    // Apenas renomear título (se editou e não enviou nova imagem)
    elseif ($is_edit && $image['error'] == UPLOAD_ERR_NO_FILE) {
        $old_filename = basename($_POST['old_filename']);
        $ext = pathinfo($old_filename, PATHINFO_EXTENSION);
        $new_name = "qr_" . $id_rev . "_" . $title . "_" . time() . "." . $ext;
        rename($dir_img . $old_filename, $dir_img . $new_name);
        $_SESSION['msg_ok'] = "Título atualizado!";
        header("Location: $base_file"); exit;
    }
}

// 2. DELETAR
if (isset($_GET['delete'])) {
    $file_del = basename($_GET['delete']);
    // Segurança: só deleta se o arquivo começar com o ID da revenda
    if (strpos($file_del, "qr_" . $id_rev . "_") === 0) {
        if (file_exists($dir_img . $file_del)) unlink($dir_img . $file_del);
        $_SESSION['msg_ok'] = "Removido com sucesso!";
    }
    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 QR-Codes</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: #f8fafc !important; font-family: 'Inter', sans-serif; margin: 0; padding: 0; }
        
        .container-fluid { padding: 30px 15px !important; max-width: 1200px; 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; }

        /* FORMULÁRIO (OCULTO POR PADRÃO) */
        #formContainer { display: none; min-height: 70vh; width: 100%; align-items: center; justify-content: center; padding: 20px; }
        .form-lux { width: 100%; max-width: 450px; background: #070e1b; border-radius: 28px; padding: 35px; border: 1px solid #1e293b; box-shadow: 0 25px 50px rgba(0,0,0,0.5); }
        
        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: 15px; border-radius: 14px; margin-bottom: 20px; outline: none; }
        .btn-submit-lux { width: 100%; background: #3b82f6 !important; color: #fff !important; padding: 16px; border-radius: 14px; font-weight: 800; border: none; cursor: pointer; text-transform: uppercase; }

        /* GRID E CARDS (DESIGN SOLICITADO) */
        .top-nav-lux { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .qr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 25px; }
        
        .card-qr-lux { background: #070e1b; border: 1px solid #1e293b; border-radius: 24px; padding: 15px; transition: 0.3s; }
        .card-qr-lux:hover { border-color: #3b82f6; }

        /* FRAME BRANCO DO QR */
        .visual-frame { width: 100%; aspect-ratio: 1 / 1; background: #ffffff; border-radius: 18px; display: flex; align-items: center; justify-content: center; padding: 15px; border: 4px solid #0f172a; }
        .visual-frame img { max-width: 100%; max-height: 100%; object-fit: contain; }

        .lux-title { font-size: 0.9rem; font-weight: 800; color: #fff; display: block; padding: 15px 5px 10px 5px; text-transform: uppercase; text-align: center;}
        
        .actions-footer { display: flex; justify-content: center; gap: 12px; margin-top: 5px; }
        .btn-circle-lux { width: 42px; height: 42px; border-radius: 12px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1rem; transition: 0.2s; }
        .btn-edit-qr { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
        .btn-del-qr { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
        
        .btn-add-main { background: #3b82f6; color: #fff; padding: 12px 24px; border-radius: 14px; font-weight: 800; border: none; cursor: pointer; text-transform: uppercase; font-size: 0.8rem;}
    </style>
</head>
<body>

<div class="container-fluid">

    <div id="formContainer">
        <div class="form-lux">
            <h2 id="formHeader" style="margin-bottom: 25px; font-weight: 900; text-align: center;">Gerenciar QR-Code</h2>
            <form id="mainForm" method="post" enctype="multipart/form-data">
                <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
                <input type="hidden" name="old_filename" id="old_filename">
                
                <label>Título do QR-Code</label>
                <input type="text" name="title" id="form_title" class="input-lux" placeholder="Ex: Pix Pagamento" required>

                <label>Imagem do QR-Code</label>
                <input type="file" name="banner" id="form_file" class="input-lux" accept="image/*">

                <button type="submit" id="submitBtn" name="upload" class="btn-submit-lux">Salvar QR-Code</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">
        <a href="dashboard_rev.php" class="btn-back-nav"><i class="fas fa-columns"></i> VOLTAR AO DASHBOARD</a>

        <div class="top-nav-lux">
            <div>
                <h1 style="font-weight: 900; margin: 0; font-size: 1.6rem;">Meus QR-Codes</h1>
                <p style="color: #3b82f6; font-size: 0.7rem; font-weight: 800; text-transform: uppercase;">Central de Recebimentos</p>
            </div>
            <button class="btn-add-main" onclick="showAddForm()"><i class="fas fa-plus"></i> Adicionar</button>
        </div>

        <div class="qr-grid">
            <?php 
            $files = glob($dir_img . "qr_" . $id_rev . "_*.*");
            if ($files):
                foreach ($files as $file):
                    $fullname = basename($file);
                    // Extrai o título (padrão: qr_ID_TITULO_TIME.ext)
                    $parts = explode('_', pathinfo($fullname, PATHINFO_FILENAME));
                    $display_name = isset($parts[2]) ? $parts[2] : "QR-Code";
            ?>
                <div class="card-qr-lux">
                    <div class="visual-frame">
                        <img src="<?= $file ?>?v=<?= time() ?>">
                    </div>
                    <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"></i></button>
                    </div>
                </div>
            <?php endforeach; 
            else: echo "<p style='grid-column:1/-1; text-align:center; opacity:0.5; padding: 50px;'>Nenhum QR-Code encontrado.</p>"; 
            endif; ?>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    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('ADICIONAR AGORA');
        $('#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 DADOS');
        $('#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: 'Excluir QR?', text: "Esta ação é permanente!", icon: 'warning',
            showCancelButton: true, confirmButtonColor: '#f43f5e', confirmButtonText: 'SIM, APAGAR',
            cancelButtonText: 'CANCELAR', background: '#070e1b', color: '#fff'
        }).then((result) => { if (result.isConfirmed) { window.location.href = "<?= $base_file ?>?delete=" + filename; } });
    }

    <?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; ?>
</script>
</body>
</html>
