<?php
require 'lock.php';   
require 'config.php'; 

// ID do usuário logado
$meu_id = $_SESSION['usuario_id'];
// Nome da empresa (com fallback se estiver vazio)
$nome_empresa = $_SESSION['nome_empresa'] ?? 'Minha Empresa';

// --- AÇÕES CRUD (Seguras) ---
if (isset($_POST['nova_categoria'])) {
    $nome = trim($_POST['nova_categoria']);
    if (!empty($nome)) {
        $stmt = $pdo->prepare("INSERT INTO categorias (nome, usuario_id) VALUES (?, ?)");
        $stmt->execute([$nome, $meu_id]);
    }
    header("Location: painel.php?msg=cat_ok"); exit;
}
if (isset($_GET['del_cat'])) {
    $stmt = $pdo->prepare("DELETE FROM categorias WHERE id = ? AND usuario_id = ?");
    $stmt->execute([(int)$_GET['del_cat'], $meu_id]);
    header("Location: painel.php"); exit;
}

if (isset($_POST['nova_filial'])) {
    $nome = trim($_POST['nova_filial']);
    if (!empty($nome)) {
        $stmt = $pdo->prepare("INSERT INTO filiais (nome, usuario_id) VALUES (?, ?)");
        $stmt->execute([$nome, $meu_id]);
    }
    header("Location: painel.php?msg=filial_ok"); exit;
}
if (isset($_GET['del_filial'])) {
    $stmt = $pdo->prepare("DELETE FROM filiais WHERE id = ? AND usuario_id = ?");
    $stmt->execute([(int)$_GET['del_filial'], $meu_id]);
    header("Location: painel.php"); exit;
}

if (isset($_GET['toggle_id'])) {
    $id = (int)$_GET['toggle_id'];
    $novo_status = ($_GET['status_atual'] == 1) ? 0 : 1;
    $stmt = $pdo->prepare("UPDATE ofertas SET ativo = ? WHERE id = ? AND usuario_id = ?");
    $stmt->execute([$novo_status, $id, $meu_id]);
    header("Location: painel.php"); exit;
}

if (isset($_GET['deletar'])) {
    $id = (int)$_GET['deletar'];
    $stmt = $pdo->prepare("DELETE FROM ofertas WHERE id = ? AND usuario_id = ?");
    $stmt->execute([$id, $meu_id]);
    header("Location: painel.php"); exit;
}

if (isset($_GET['acao']) && $_GET['acao'] == 'limpar_tudo') {
    $stmt = $pdo->prepare("DELETE FROM ofertas WHERE usuario_id = ?");
    $stmt->execute([$meu_id]);
    header("Location: painel.php?msg=tabela_limpa"); exit;
}

// --- BUSCAS ---
$stmt = $pdo->prepare("SELECT * FROM categorias WHERE usuario_id = ? ORDER BY nome ASC");
$stmt->execute([$meu_id]);
$listaCategorias = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("SELECT * FROM filiais WHERE usuario_id = ? ORDER BY nome ASC");
$stmt->execute([$meu_id]);
$listaFiliais = $stmt->fetchAll(PDO::FETCH_ASSOC);

$termo = isset($_GET['busca']) ? $_GET['busca'] : '';
$sql = "SELECT ofertas.*, filiais.nome as nome_filial 
        FROM ofertas 
        LEFT JOIN filiais ON ofertas.filial_id = filiais.id 
        WHERE ofertas.usuario_id = :uid 
        AND (ofertas.produto LIKE :termo OR ofertas.codigo_balanca LIKE :termo) 
        ORDER BY ofertas.id DESC";

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

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$urlTv = "$protocol://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . "/tv/tvdual.php?uid=" . $meu_id;
$urlTv141 = "$protocol://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . "/tv/tv141.php?uid=" . $meu_id;
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Painel 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%); }
        .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 Ofertas - <?= htmlspecialchars($nome_empresa) ?>
        </span>
        <div>
            <?php if(isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1): ?>
                <a href="admin_master.php" class="btn btn-sm btn-danger fw-bold me-2 border-white">
                    <i class="bi bi-shield-lock"></i> ADMIN
                </a>
            <?php endif; ?>
            
            <a href="lock.php?sair=true" class="btn btn-sm btn-outline-light">Sair</a>
        </div>
    </div>
</nav>

<div class="container">
    
    <div class="row mb-3 g-2">
        <div class="col-md-6">
            <div class="alert alert-primary d-flex justify-content-between align-items-center shadow-sm m-0">
                <div class="text-truncate">
                    <i class="bi bi-layout-split"></i> <strong>TV Padrão:</strong> 
                    <a href="<?= $urlTv ?>" target="_blank" class="fw-bold ms-2 text-decoration-none small"><?= $urlTv ?></a>
                </div>
                <button class="btn btn-sm btn-light border" onclick="navigator.clipboard.writeText('<?= $urlTv ?>'); alert('Copiado!');">Copiar</button>
            </div>
        </div>
        <div class="col-md-6">
            <div class="alert alert-warning d-flex justify-content-between align-items-center shadow-sm m-0">
                <div class="text-truncate">
                    <i class="bi bi-grid-3x3-gap"></i> <strong>TV Encarte (1-4-1):</strong> 
                    <a href="<?= $urlTv141 ?>" target="_blank" class="fw-bold ms-2 text-decoration-none small text-dark"><?= $urlTv141 ?></a>
                </div>
                <button class="btn btn-sm btn-light border" onclick="navigator.clipboard.writeText('<?= $urlTv141 ?>'); alert('Copiado!');">Copiar</button>
            </div>
        </div>
    </div>

    <?php if(isset($_GET['msg'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            Sucesso! Ação realizada.
            <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</a>
                    <a href="excel_manager.php?exportar=true" class="btn btn-outline-success" title="Baixar Planilha"><i class="bi bi-file-earmark-excel"></i> Exportar</a>
                    <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalImportar" title="Subir Planilha"><i class="bi bi-upload"></i> Importar</button>
                </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> Cats</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</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</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';
                            ?>
                            <tr class="<?= $classeRow ?>">
                                <td class="ps-3 badge-status">
                                    <a href="?toggle_id=<?= $item['id'] ?>&status_atual=<?= $ativo ?>" class="text-decoration-none">
                                        <?= $ativo ? '<i class="bi bi-toggle-on text-success fs-3"></i>' : '<i class="bi bi-toggle-off text-secondary fs-3"></i>' ?>
                                    </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"><?= $item['categoria'] ?? 'Geral' ?></span>
                                        <span class="badge bg-dark bg-opacity-75 text-white border"><?= $nomeFilial ?></span>
                                    </div>
                                </td>
                                <td class="fw-bold text-success">
                                    R$ <?= number_format($item['preco'], 2, ',', '.') ?> <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?')"><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 cadastrado.</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">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">Add</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"><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">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">Add</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"><i class="bi bi-trash"></i></a></li><?php endforeach; ?></ul></div></div></div></div>
<div class="modal fade" id="modalImportar" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5>Importar CSV</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><form action="excel_manager.php" method="POST" enctype="multipart/form-data"><div class="mb-3"><label>Arquivo CSV</label><input type="file" name="arquivo_excel" class="form-control" accept=".csv" required></div><button class="btn btn-primary w-100">Enviar</button></form></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>Apagar SEUS 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>