<?php
// admin/shop_config.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }
$stmt = $pdo->prepare("SELECT page_access FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();
if (!$acc || $acc['page_access'] < 3) die("Acesso Negado.");

$page_title = "Gestão Avançada do Shop";

if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';
$editMode = false;
$editData = [];
$tab = $_GET['tab'] ?? 'offers'; 

// --- PROCESSAMENTOS (Mantido igual) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['delete_offer_id'])) {
        $stmt = $pdo->prepare("DELETE FROM shop_offers WHERE id = ?");
        $stmt->execute([$_POST['delete_offer_id']]);
        $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-trash me-2"></i> Oferta removida!</div>';
    }
    elseif (isset($_POST['action']) && $_POST['action'] == 'save_offer') {
        $image_path = $_POST['current_image'] ?? 'default_item.png'; 
        if (!empty($_FILES['image_file']['name'])) {
            $target_dir = "../images/shop/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            $ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
            $new_name = uniqid('shop_') . '.' . $ext;
            if(in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp'])) {
                if(move_uploaded_file($_FILES['image_file']['tmp_name'], $target_dir . $new_name)) $image_path = "images/shop/" . $new_name;
            }
        } elseif (!empty($_POST['image_url'])) { $image_path = $_POST['image_url']; }

        $itemid = empty($_POST['itemid']) ? 0 : $_POST['itemid'];
        $cat_id = (int)$_POST['category_id'];

        if (empty($_POST['id'])) { 
            $sql = "INSERT INTO shop_offers (offer_name, offer_desc, itemid, count, points, points_old, offer_type, image, category_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$_POST['name'], $_POST['desc'], $itemid, $_POST['count'], $_POST['points'], $_POST['points_old'], $_POST['type'], $image_path, $cat_id]);
            $msg = '<div class="alert alert-success shadow-sm border-0">Oferta cadastrada!</div>';
        } else { 
            $sql = "UPDATE shop_offers SET offer_name=?, offer_desc=?, itemid=?, count=?, points=?, points_old=?, offer_type=?, image=?, category_id=? WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$_POST['name'], $_POST['desc'], $itemid, $_POST['count'], $_POST['points'], $_POST['points_old'], $_POST['type'], $image_path, $cat_id, $_POST['id']]);
            $msg = '<div class="alert alert-info shadow-sm border-0">Oferta atualizada! <a href="shop_config.php" class="fw-bold text-white">Voltar</a></div>';
        }
    }
    elseif (isset($_POST['action']) && $_POST['action'] == 'save_category') {
        $name = trim($_POST['cat_name']);
        $icon = trim($_POST['cat_icon']);
        $prio = (int)$_POST['cat_priority'];
        
        if(empty($_POST['cat_id'])) { 
            $pdo->prepare("INSERT INTO shop_categories (name, icon, priority) VALUES (?, ?, ?)")->execute([$name, $icon, $prio]);
            $msg = '<div class="alert alert-success shadow-sm border-0">Categoria criada!</div>';
        } else { 
            $pdo->prepare("UPDATE shop_categories SET name=?, icon=?, priority=? WHERE id=?")->execute([$name, $icon, $prio, $_POST['cat_id']]);
            $msg = '<div class="alert alert-info shadow-sm border-0">Categoria atualizada!</div>';
        }
        $tab = 'categories';
    }
    elseif (isset($_POST['delete_cat_id'])) {
        $pdo->prepare("DELETE FROM shop_categories WHERE id=?")->execute([$_POST['delete_cat_id']]);
        $msg = '<div class="alert alert-warning shadow-sm border-0">Categoria removida.</div>';
        $tab = 'categories';
    }
}

if (isset($_GET['edit_offer'])) {
    $stmt = $pdo->prepare("SELECT * FROM shop_offers WHERE id = ?");
    $stmt->execute([$_GET['edit_offer']]);
    $editData = $stmt->fetch();
    if($editData) $editMode = true;
}

$categories = $pdo->query("SELECT * FROM shop_categories ORDER BY priority ASC")->fetchAll(PDO::FETCH_ASSOC);
$offers = $pdo->query("SELECT o.*, c.name as cat_name FROM shop_offers o LEFT JOIN shop_categories c ON o.category_id = c.id ORDER BY o.id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    /* Admin Dark Theme Pro - CORREÇÃO DE CORES */
    body { background-color: #0f172a; color: #e2e8f0; font-family: 'Poppins', sans-serif; }
    
    .card { 
        background-color: #1e293b; 
        border: 1px solid rgba(255,255,255,0.1); 
        color: #fff; 
        border-radius: 12px; 
    }
    
    .nav-tabs .nav-link { color: #94a3b8; border: none; font-weight: 600; padding: 12px 20px; }
    .nav-tabs .nav-link.active { background-color: #1e293b; color: #3b82f6; border-bottom: 3px solid #3b82f6; }
    
    /* INPUTS FORÇADOS PARA DARK MODE */
    .form-control, .form-select, .input-group-text { 
        background-color: #0b1120 !important; 
        border: 1px solid rgba(255,255,255,0.15) !important; 
        color: #ffffff !important; 
    }
    .form-control::placeholder { color: rgba(255,255,255,0.4) !important; }
    .form-control:focus, .form-select:focus { 
        border-color: #3b82f6 !important; 
        box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25) !important; 
    }
    
    .form-label { color: #e2e8f0 !important; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-text { color: rgba(255,255,255,0.6) !important; }

    /* TABELAS FORÇADAS PARA DARK MODE */
    .table { color: #e2e8f0 !important; --bs-table-color: #e2e8f0; --bs-table-bg: transparent; }
    .table thead th { 
        background-color: #0f172a; 
        color: #94a3b8; 
        border-bottom: 2px solid #334155; 
        text-transform: uppercase; 
        font-size: 0.8rem; 
    }
    .table tbody tr:hover { background-color: rgba(255,255,255,0.05); }
    .table td { border-bottom: 1px solid rgba(255,255,255,0.05); }
    
    .admin-shop-card { background: #0f172a; border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; overflow: hidden; transition: transform 0.2s; }
    .admin-shop-card:hover { transform: translateY(-3px); border-color: #3b82f6; }
    .item-img { width: 64px; height: 64px; object-fit: contain; }
</style>

<div class="container my-5">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold text-white mb-0"><i class="fas fa-store text-primary me-2"></i>Gestão do Shop</h2>
        <a href="../shop.php" target="_blank" class="btn btn-outline-light btn-sm"><i class="fas fa-external-link-alt me-1"></i> Ver Loja</a>
    </div>

    <?php echo $msg; ?>

    <ul class="nav nav-tabs mb-4 border-secondary">
        <li class="nav-item">
            <a class="nav-link <?php echo $tab == 'offers' ? 'active' : ''; ?>" href="?tab=offers"><i class="fas fa-box-open me-2"></i> Produtos</a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo $tab == 'categories' ? 'active' : ''; ?>" href="?tab=categories"><i class="fas fa-tags me-2"></i> Categorias</a>
        </li>
    </ul>

    <?php if ($tab == 'offers'): ?>
    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="card shadow border-top border-4 <?php echo $editMode ? 'border-warning' : 'border-primary'; ?>">
                <div class="card-header bg-transparent fw-bold py-3 text-white border-bottom border-secondary">
                    <?php echo $editMode ? 'Editando Oferta' : 'Nova Oferta'; ?>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="save_offer">
                        <?php if($editMode): ?>
                            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
                            <input type="hidden" name="current_image" value="<?php echo $editData['image']; ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label">Nome</label>
                            <input type="text" name="name" class="form-control" required value="<?php echo $editData['offer_name'] ?? ''; ?>" placeholder="Ex: Master Ball">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Categoria</label>
                            <select name="category_id" class="form-select">
                                <?php foreach($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo ($editMode && $editData['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Tipo</label>
                            <select name="type" class="form-select">
                                <option value="item" <?php echo ($editMode && $editData['offer_type'] == 'item') ? 'selected' : ''; ?>>📦 Item Comum</option>
                                <option value="pokemon" <?php echo ($editMode && $editData['offer_type'] == 'pokemon') ? 'selected' : ''; ?>>🐲 Pokémon</option>
                                <option value="vip" <?php echo ($editMode && $editData['offer_type'] == 'vip') ? 'selected' : ''; ?>>💎 VIP (Dias)</option>
                                <option value="changename" <?php echo ($editMode && $editData['offer_type'] == 'changename') ? 'selected' : ''; ?>>📝 Troca de Nick</option>
                                <option value="rk" <?php echo ($editMode && $editData['offer_type'] == 'rk') ? 'selected' : ''; ?>>🔑 Recovery Key</option>
                            </select>
                        </div>

                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label">Item ID</label>
                                <input type="number" name="itemid" class="form-control" value="<?php echo $editData['itemid'] ?? 0; ?>">
                            </div>
                            <div class="col-6">
                                <label class="form-label">Qtd / Dias</label>
                                <input type="number" name="count" class="form-control" value="<?php echo $editData['count'] ?? 1; ?>">
                            </div>
                        </div>

                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label text-success">Preço (Pts)</label>
                                <input type="number" name="points" class="form-control fw-bold border-success" required value="<?php echo $editData['points'] ?? ''; ?>">
                            </div>
                            <div class="col-6">
                                <label class="form-label text-danger">Promo (De)</label>
                                <input type="number" name="points_old" class="form-control border-danger" value="<?php echo $editData['points_old'] ?? 0; ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Imagem</label>
                            <input type="file" name="image_file" class="form-control mb-1">
                            <input type="text" name="image_url" class="form-control form-control-sm" placeholder="Ou URL..." value="<?php echo $editData['image'] ?? ''; ?>">
                        </div>
                         
                         <div class="mb-3">
                            <label class="form-label">Descrição</label>
                            <textarea name="desc" class="form-control" rows="2" placeholder="Detalhes do item..."><?php echo $editData['offer_desc'] ?? ''; ?></textarea>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn fw-bold <?php echo $editMode ? 'btn-warning text-dark' : 'btn-success'; ?>">
                                <i class="fas fa-save me-2"></i> <?php echo $editMode ? 'SALVAR' : 'CADASTRAR'; ?>
                            </button>
                            <?php if($editMode): ?>
                                <a href="shop_config.php" class="btn btn-outline-light btn-sm">Cancelar</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <h5 class="text-white fw-bold mb-3">Ofertas Ativas (<?php echo count($offers); ?>)</h5>
            <div class="row g-3">
                <?php foreach($offers as $item): 
                    $imgSrc = (strpos($item['image'], 'http') !== false) ? $item['image'] : "../" . $item['image'];
                    if($item['image'] == 'default_item.png' && $item['itemid'] > 0) $imgSrc = "https://raw.githubusercontent.com/ot-net/ot-client/master/data/images/game/items/{$item['itemid']}.png";
                ?>
                <div class="col-md-6 col-xl-4">
                    <div class="admin-shop-card p-3 d-flex align-items-center">
                        <img src="<?php echo $imgSrc; ?>" class="item-img rounded bg-dark border border-secondary me-3" onerror="this.src='../images/no_item.png'">
                        <div class="flex-grow-1 overflow-hidden">
                            <div class="badge bg-primary mb-1" style="font-size: 0.65rem;"><?php echo htmlspecialchars($item['cat_name'] ?? 'Sem Categoria'); ?></div>
                            <h6 class="text-white mb-1 text-truncate" title="<?php echo htmlspecialchars($item['offer_name']); ?>"><?php echo htmlspecialchars($item['offer_name']); ?></h6>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-warning fw-bold small"><?php echo $item['points']; ?> Pts</span>
                                <div>
                                    <a href="?edit_offer=<?php echo $item['id']; ?>" class="text-info me-2"><i class="fas fa-pen"></i></a>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Excluir?');">
                                        <input type="hidden" name="delete_offer_id" value="<?php echo $item['id']; ?>">
                                        <button class="btn btn-link p-0 text-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <?php elseif ($tab == 'categories'): ?>
    <div class="row">
        <div class="col-lg-4">
            <div class="card shadow border-top border-4 border-success">
                <div class="card-header bg-transparent text-white fw-bold py-3 border-bottom border-secondary">
                    <i class="fas fa-folder-plus me-2"></i> Nova Categoria
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="save_category">
                        
                        <div class="mb-3">
                            <label class="form-label">Nome da Categoria</label>
                            <input type="text" name="cat_name" class="form-control" required placeholder="Ex: Pokémons">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Ícone (FontAwesome)</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-icons"></i></span>
                                <input type="text" name="cat_icon" class="form-control" placeholder="fa-dragon" required>
                            </div>
                            <div class="form-text">Use ícones do FontAwesome 5.</div>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">Prioridade</label>
                            <input type="number" name="cat_priority" class="form-control" value="10">
                        </div>
                        
                        <button class="btn btn-success w-100 fw-bold">CRIAR CATEGORIA</button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <div class="card shadow">
                <div class="card-header bg-dark text-white fw-bold border-bottom border-secondary">Categorias Existentes</div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th class="ps-3">Ícone</th>
                                <th>Nome</th>
                                <th>Ordem</th>
                                <th class="text-end pe-3">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($categories as $cat): ?>
                            <tr>
                                <td class="ps-3"><i class="fas <?php echo $cat['icon']; ?> fa-lg text-info"></i></td>
                                <td class="fw-bold text-white"><?php echo htmlspecialchars($cat['name']); ?></td>
                                <td class="text-white"><?php echo $cat['priority']; ?></td>
                                <td class="text-end pe-3">
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Apagar categoria?');">
                                        <input type="hidden" name="delete_cat_id" value="<?php echo $cat['id']; ?>">
                                        <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

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