<?php
require 'lock.php';   // Proteção de Senha
require 'config.php'; // Conexão Banco

// --- LÓGICA 1: GERENCIAR CATEGORIAS (Adicionar/Excluir) ---
if (isset($_POST['nova_categoria'])) {
    $nome = trim($_POST['nova_categoria']);
    if (!empty($nome)) {
        $pdo->prepare("INSERT INTO categorias (nome) VALUES (?)")->execute([$nome]);
    }
    header("Location: painel.php?msg=cat_ok"); exit;
}
if (isset($_GET['del_cat'])) {
    $pdo->prepare("DELETE FROM categorias WHERE id = ?")->execute([(int)$_GET['del_cat']]);
    header("Location: painel.php"); exit;
}

// --- LÓGICA 2: GERENCIAR FILIAIS (Adicionar/Excluir) ---
if (isset($_POST['nova_filial'])) {
    $nome = trim($_POST['nova_filial']);
    if (!empty($nome)) {
        $pdo->prepare("INSERT INTO filiais (nome) VALUES (?)")->execute([$nome]);
    }
    header("Location: painel.php?msg=filial_ok"); exit;
}
if (isset($_GET['del_filial'])) {
    $pdo->prepare("DELETE FROM filiais WHERE id = ?")->execute([(int)$_GET['del_filial']]);
    header("Location: painel.php"); exit;
}

// --- LÓGICA 3: ALTERAR STATUS (SUSPENDER/ATIVAR) ---
if (isset($_GET['toggle_id'])) {
    $id = (int)$_GET['toggle_id'];
    $status_atual = (int)$_GET['status_atual'];
    $novo_status = ($status_atual == 1) ? 0 : 1; // Inverte
    
    $stmt = $pdo->prepare("UPDATE ofertas SET ativo = ? WHERE id = ?");
    $stmt->execute([$novo_status, $id]);
    
    header("Location: painel.php"); exit;
}

// --- AÇÃO 4: EXCLUIR PRODUTO ---
if (isset($_GET['deletar'])) {
    $id = (int)$_GET['deletar'];
    $pdo->query("DELETE FROM ofertas WHERE id = $id");
    header("Location: painel.php"); exit;
}

// --- AÇÃO 5: LIMPAR TUDO ---
if (isset($_GET['acao']) && $_GET['acao'] == 'limpar_tudo') {
    $pdo->query("TRUNCATE TABLE ofertas");
    header("Location: painel.php?msg=tabela_limpa"); exit;
}

// --- BUSCAR DADOS ---
// Busca Categorias e Filiais para exibir nos modais
$listaCategorias = $pdo->query("SELECT * FROM categorias ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);
$listaFiliais    = $pdo->query("SELECT * FROM filiais ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);

// Busca Produtos (AGORA COM O NOME DA FILIAL)
$termo = isset($_GET['busca']) ? $_GET['busca'] : '';

// SQL Atualizado com JOIN na tabela filiais
$sql = "SELECT ofertas.*, filiais.nome as nome_filial 
        FROM ofertas 
        LEFT JOIN filiais ON ofertas.filial_id = filiais.id 
        WHERE (ofertas.produto LIKE :termo OR ofertas.codigo_balanca LIKE :termo) 
        ORDER BY ofertas.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute([':termo' => "%$termo%"]);
$produtos = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Painel Avançado MGA</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .img-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 6px; border: 1px solid #ddd; }
        .bg-gradient-primary { background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%); }
        /* Estilo para item suspenso (opacidade reduzida) */
        .item-suspenso td { opacity: 0.5; background-color: #f8f9fa; }
        .item-suspenso .badge-status { opacity: 1; }
    </style>
</head>
<body class="bg-light">

<nav class="navbar navbar-dark bg-gradient-primary shadow mb-4">
    <div class="container">
        <span class="navbar-brand fw-bold mb-0 h1"><i class="bi bi-tv"></i> MGA Play Ofertas</span>
        <div><a href="lock.php?sair=true" class="btn btn-sm btn-outline-light">Sair</a></div>
    </div>
</nav>

<div class="container">
    
    <?php if(isset($_GET['msg'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php 
                if($_GET['msg']=='cat_ok') echo "Categoria criada com sucesso!";
                elseif($_GET['msg']=='filial_ok') echo "Filial adicionada com sucesso!";
                else echo "Operação realizada com sucesso!";
            ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm mb-4">
        <div class="card-body">
            
            <div class="d-flex flex-wrap gap-2 mb-3 justify-content-between align-items-center">
                <div class="d-flex gap-2">
                    <a href="formulario.php" class="btn btn-success fw-bold"><i class="bi bi-plus-circle"></i> Novo Produto</a>
                    <a href="importar-mgv.php" class="btn btn-primary"><i class="bi bi-cloud-upload"></i> Importar</a>
                </div>
                
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#modalCategorias">
                        <i class="bi bi-tags"></i> Categorias
                    </button>
                    <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#modalFiliais">
                        <i class="bi bi-shop"></i> Filiais
                    </button>
                    <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#modalLimpar">
                        <i class="bi bi-trash3"></i> Limpar Tudo
                    </button>
                </div>
            </div>

            <form method="GET" action="painel.php">
                <div class="input-group">
                    <span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
                    <input type="text" name="busca" class="form-control" placeholder="Buscar..." value="<?= htmlspecialchars($termo) ?>">
                    <button class="btn btn-dark" type="submit">Pesquisar</button>
                    <?php if(!empty($termo)): ?>
                        <a href="painel.php" class="btn btn-secondary"><i class="bi bi-x-lg"></i></a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th class="ps-3">Status</th> 
                            <th>Img</th>
                            <th>Produto / Categoria / Filial</th> <th>Preço</th>
                            <th class="text-center">Destaque</th>
                            <th class="text-end pe-3">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($produtos) > 0): ?>
                            <?php foreach($produtos as $item): 
                                $ativo = isset($item['ativo']) ? $item['ativo'] : 1; 
                                $classeRow = ($ativo == 0) ? 'item-suspenso' : '';
                                $nomeFilial = !empty($item['nome_filial']) ? $item['nome_filial'] : 'Todas as Lojas';
                            ?>
                            <tr class="<?= $classeRow ?>">
                                <td class="ps-3 badge-status">
                                    <a href="?toggle_id=<?= $item['id'] ?>&status_atual=<?= $ativo ?>" class="text-decoration-none" title="Clique para Suspender/Ativar">
                                        <?php if($ativo == 1): ?>
                                            <i class="bi bi-toggle-on text-success fs-3"></i>
                                            <div style="font-size:10px; color:green; margin-top:-5px; font-weight:bold;">ATIVO</div>
                                        <?php else: ?>
                                            <i class="bi bi-toggle-off text-secondary fs-3"></i>
                                            <div style="font-size:10px; color:grey; margin-top:-5px; font-weight:bold;">SUSPENSO</div>
                                        <?php endif; ?>
                                    </a>
                                </td>

                                <td>
                                    <?php if(!empty($item['imagem'])): ?>
                                        <img src="<?= $item['imagem'] ?>" class="img-thumb">
                                    <?php else: ?>
                                        <div class="img-thumb bg-secondary d-flex align-items-center justify-content-center text-white"><i class="bi bi-camera-off"></i></div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="fw-bold text-dark"><?= $item['produto'] ?></div>
                                    
                                    <div class="mt-1">
                                        <span class="badge bg-secondary bg-opacity-25 text-dark border me-1">
                                            <i class="bi bi-tag-fill"></i> <?= $item['categoria'] ?? 'Geral' ?>
                                        </span>
                                        <span class="badge bg-dark bg-opacity-75 text-white border">
                                            <i class="bi bi-shop"></i> <?= $nomeFilial ?>
                                        </span>
                                    </div>

                                    <?php if($item['codigo_balanca'] > 0): ?>
                                        <small class="text-muted ms-1 d-block" style="font-size:11px;">Cód. Balança: <?= $item['codigo_balanca'] ?></small>
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold text-success">
                                    R$ <?= $item['preco'] ?> <small class="text-muted fw-normal">/<?= $item['unidade'] ?></small>
                                </td>
                                <td class="text-center">
                                    <?= $item['destaque'] ? '<i class="bi bi-star-fill text-warning fs-5"></i>' : '<i class="bi bi-star text-muted opacity-25"></i>' ?>
                                </td>
                                <td class="text-end pe-3">
                                    <a href="formulario.php?id=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil-square"></i></a>
                                    <a href="?deletar=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Excluir definitivamente?')"><i class="bi bi-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6" class="text-center py-5 text-muted">Nenhum produto encontrado.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCategorias" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Gerenciar Categorias</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" class="input-group mb-3">
                    <input type="text" name="nova_categoria" class="form-control" placeholder="Nova Categoria..." required>
                    <button class="btn btn-success" type="submit">Adicionar</button>
                </form>
                <ul class="list-group">
                    <?php foreach($listaCategorias as $cat): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <?= $cat['nome'] ?>
                        <a href="?del_cat=<?= $cat['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Excluir categoria?')"><i class="bi bi-trash"></i></a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalFiliais" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Gerenciar Filiais</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" class="input-group mb-3">
                    <input type="text" name="nova_filial" class="form-control" placeholder="Nome da Filial..." required>
                    <button class="btn btn-success" type="submit">Adicionar</button>
                </form>
                <ul class="list-group">
                    <?php foreach($listaFiliais as $fil): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <?= $fil['nome'] ?>
                        <a href="?del_filial=<?= $fil['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Excluir filial?')"><i class="bi bi-trash"></i></a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalLimpar" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">CUIDADO!</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <p>Deseja APAGAR TODOS os produtos?</p>
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <a href="?acao=limpar_tudo" class="btn btn-danger fw-bold">SIM, LIMPAR</a>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>