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

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

$page_title = "Gestão Avançada do Shop";
include '../includes/admin_header.php';

$msg = '';
$editMode = false;
$editData = [];

// --- 1. PROCESSAR FORMULÁRIO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // A. DELETAR
    if (isset($_POST['delete_id'])) {
        $stmt = $pdo->prepare("DELETE FROM shop_offers WHERE id = ?");
        $stmt->execute([$_POST['delete_id']]);
        $msg = '<div class="alert alert-success alert-dismissible fade show">Oferta removida! <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    }

    // B. SALVAR (ADD / EDIT)
    elseif (isset($_POST['action'])) {
        
        // Upload de Imagem
        $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('item_') . '.' . $ext;
            
            if(in_array($ext, ['png', 'jpg', 'jpeg', 'gif'])) {
                if(move_uploaded_file($_FILES['image_file']['tmp_name'], $target_dir . $new_name)) {
                    $image_path = "images/shop/" . $new_name;
                }
            } else {
                $msg = '<div class="alert alert-danger">Formato inválido!</div>';
            }
        } elseif (!empty($_POST['image_url'])) {
            $image_path = $_POST['image_url'];
        }

        // Se for serviço, itemid pode ser 0
        $itemid = empty($_POST['itemid']) ? 0 : $_POST['itemid'];

        if ($_POST['action'] == 'add') {
            $sql = "INSERT INTO shop_offers (offer_name, offer_desc, itemid, count, points, points_old, offer_type, image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$_POST['name'], $_POST['desc'], $itemid, $_POST['count'], $_POST['points'], $_POST['points_old'], $_POST['type'], $image_path]);
            $msg = '<div class="alert alert-success">Oferta cadastrada com sucesso!</div>';
        } 
        elseif ($_POST['action'] == 'edit') {
            $sql = "UPDATE shop_offers SET offer_name=?, offer_desc=?, itemid=?, count=?, points=?, points_old=?, offer_type=?, image=? WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$_POST['name'], $_POST['desc'], $itemid, $_POST['count'], $_POST['points'], $_POST['points_old'], $_POST['type'], $image_path, $_POST['id']]);
            $msg = '<div class="alert alert-success">Oferta atualizada! <a href="shop.php">Sair do modo edição</a></div>';
        }
    }
}

// --- 2. MODO EDIÇÃO ---
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM shop_offers WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editData = $stmt->fetch();
    if($editData) $editMode = true;
}

// --- 3. DADOS DO DASHBOARD ---
$statsProfit = $pdo->query("SELECT SUM(points_cost) FROM shop_history")->fetchColumn() ?: 0;
$statsCount = $pdo->query("SELECT COUNT(*) FROM shop_history")->fetchColumn() ?: 0;
$bestSeller = $pdo->query("SELECT offer_name, COUNT(*) as qtd FROM shop_history GROUP BY offer_name ORDER BY qtd DESC LIMIT 1")->fetch();
$offers = $pdo->query("SELECT * FROM shop_offers ORDER BY id DESC")->fetchAll();
?>

<style>
    .admin-shop-card {
        border: none; border-radius: 12px; transition: all 0.3s;
        background: white; overflow: hidden; position: relative;
        box-shadow: 0 4px 6px rgba(0,0,0,0.05);
    }
    .admin-shop-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
    .item-img-wrapper {
        height: 100px; background: radial-gradient(circle, #f8f9fa 0%, #ffffff 70%);
        display: flex; align-items: center; justify-content: center; padding: 10px;
    }
    .item-img-wrapper img { max-height: 80px; max-width: 80px; filter: drop-shadow(0 5px 5px rgba(0,0,0,0.1)); }
    .badge-promo { position: absolute; top: 10px; right: 10px; }
    .card-actions { background: #f8f9fa; border-top: 1px solid #eee; padding: 10px; }
    .service-badge { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-store"></i> Gestão de Produtos & Serviços</h1>
</div>

<?php echo $msg; ?>

<div class="row mb-4 g-3">
    <div class="col-md-4">
        <div class="card bg-success text-white border-0 shadow h-100">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-uppercase opacity-75 mb-1">Total Arrecadado</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($statsProfit, 0, ',', '.'); ?> Pts</h3>
                </div>
                <i class="fas fa-coins fa-3x opacity-25"></i>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card bg-primary text-white border-0 shadow h-100">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-uppercase opacity-75 mb-1">Itens Vendidos</h6>
                    <h3 class="mb-0 fw-bold"><?php echo $statsCount; ?></h3>
                </div>
                <i class="fas fa-box-open fa-3x opacity-25"></i>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card bg-dark text-white border-0 shadow h-100">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-uppercase opacity-75 mb-1">Best Seller</h6>
                    <h4 class="mb-0 fw-bold text-warning"><?php echo $bestSeller['offer_name'] ?? '-'; ?></h4>
                </div>
                <i class="fas fa-crown fa-3x opacity-25 text-warning"></i>
            </div>
        </div>
    </div>
</div>

<div class="row">
    
    <div class="col-lg-4 mb-4">
        <div class="card border-0 shadow border-top border-5 <?php echo $editMode ? 'border-warning' : 'border-primary'; ?>">
            <div class="card-header bg-white fw-bold py-3">
                <i class="fas <?php echo $editMode ? 'fa-edit text-warning' : 'fa-plus-circle text-primary'; ?>"></i> 
                <?php echo $editMode ? 'Editando: ' . htmlspecialchars($editData['offer_name']) : 'Cadastrar Oferta'; ?>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="<?php echo $editMode ? 'edit' : 'add'; ?>">
                    <?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 small fw-bold">Nome da Oferta</label>
                        <input type="text" name="name" class="form-control" placeholder="Ex: Premium 30 Dias" required value="<?php echo $editData['offer_name'] ?? ''; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Descrição</label>
                        <textarea name="desc" class="form-control" rows="2" placeholder="Ex: Acesso VIP completo..."><?php echo $editData['offer_desc'] ?? ''; ?></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold text-primary">Tipo de Produto</label>
                        <select name="type" class="form-select bg-light border-primary" id="offerType">
                            <option value="item" <?php echo ($editMode && $editData['offer_type'] == 'item') ? 'selected' : ''; ?>>Item Comum (Entregável)</option>
                            <option value="pokemon" <?php echo ($editMode && $editData['offer_type'] == 'pokemon') ? 'selected' : ''; ?>>Pokémon (Box/Item)</option>
                            <option disabled>--- SERVIÇOS ---</option>
                            <option value="vip" <?php echo ($editMode && $editData['offer_type'] == 'vip') ? 'selected' : ''; ?>>💎 VIP / Premium Days</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' : ''; ?>>🔑 Nova Recovery Key</option>
                        </select>
                    </div>

                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label small fw-bold">Item ID</label>
                            <input type="number" name="itemid" class="form-control" value="<?php echo $editData['itemid'] ?? ''; ?>">
                            <div class="form-text" style="font-size: 10px;">0 se for serviço</div>
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">Qtd / Dias</label>
                            <input type="number" name="count" class="form-control" required value="<?php echo $editData['count'] ?? 1; ?>">
                            <div class="form-text" style="font-size: 10px;">Dias VIP ou Qtd Item