<?php
session_start();
require_once 'conexao.php';

// Verifica se está logado
if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }
$usuarioLogado = $_SESSION['usuario'];

// Verifica se é Admin (ajustado para garantir que funcione em maiúsculo ou minúsculo)
$isAdmin = (isset($_SESSION['nivel']) && strtolower($_SESSION['nivel']) === 'admin');

// --- LISTA DE LOGOS ---
$logos_disponiveis = [
    'claro.png' => 'Claro',
    'net.png'   => 'NET',
    'sky.png'   => 'Sky',
    'vivo.png'  => 'Vivo',
    'iptv.png'  => 'Genérico'
];

// --- 1. ATUALIZAR PLANO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['atualizar_plano'])) {
    $id_plano = (int)$_POST['id_plano'];
    $nome = trim($_POST['nome']);
    $dias = (int)$_POST['dias'];
    $valor = str_replace(',', '.', $_POST['valor']); 
    $logo = $_POST['logo_perfil'];

    if ($nome && $dias > 0 && $valor > 0) {
        $sql = "UPDATE planos_revenda SET nome_plano=?, dias=?, valor=?, logo_perfil=? WHERE id=? AND id_revendedor=?";
        $connUser->prepare($sql)->execute([$nome, $dias, $valor, $logo, $id_plano, $usuarioLogado]);
        echo "<script>alert('✅ Plano atualizado!'); location.href='gerenciar_planos.php';</script>";
    }
}

// --- 2. CRIAR NOVO PLANO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['criar_plano'])) {
    $nome = trim($_POST['nome']);
    $dias = (int)$_POST['dias'];
    $valor = str_replace(',', '.', $_POST['valor']); 
    $logo = $_POST['logo_perfil'];

    if ($nome && $dias > 0 && $valor > 0) {
        $sql = "INSERT INTO planos_revenda (id_revendedor, nome_plano, dias, valor, logo_perfil) VALUES (?, ?, ?, ?, ?)";
        $connUser->prepare($sql)->execute([$usuarioLogado, $nome, $dias, $valor, $logo]);
        echo "<script>alert('✅ Plano criado!'); location.href='gerenciar_planos.php';</script>";
    }
}

// --- 3. EXCLUIR ---
if (isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    $connUser->prepare("DELETE FROM planos_revenda WHERE id = ? AND id_revendedor = ?")->execute([$id, $usuarioLogado]);
    header("Location: gerenciar_planos.php"); exit;
}

// --- CARREGAR EDIÇÃO ---
$plano_editar = null;
if (isset($_GET['edit'])) {
    $id_edit = (int)$_GET['edit'];
    $stmt = $connUser->prepare("SELECT * FROM planos_revenda WHERE id=? AND id_revendedor=?");
    $stmt->execute([$id_edit, $usuarioLogado]);
    $plano_editar = $stmt->fetch(PDO::FETCH_ASSOC);
}

// --- LISTAR ---
$stmt = $connUser->prepare("SELECT * FROM planos_revenda WHERE id_revendedor = ? ORDER BY dias ASC");
$stmt->execute([$usuarioLogado]);
$meus_planos = $stmt->fetchAll(PDO::FETCH_ASSOC);

$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try { 
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(); 
    if($conf) {
        $nomePainel = $conf['NomePainel'] ?? $nomePainel;
        $corPrimaria = $conf['TemaPainel'] ?? $corPrimaria;
    }
} catch(Exception $e){}



// --- 3. CORREÇÃO DO MENU LATERAL (MENSAGENS NÃO LIDAS) ---
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { }





?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>


    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Gerenciar Planos | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* Sidebar Estilo Padronizado */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        
        /* SELETOR DE LOGOS COMPACTO */
        .logo-selector { display: flex; gap: 10px; flex-wrap: wrap; }
        .logo-option { cursor: pointer; border: 2px solid #444; border-radius: 8px; padding: 5px; background: #252535; width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; position: relative; transition: 0.2s; }
        .logo-option img { max-width: 35px !important; max-height: 35px !important; height: auto !important; width: auto !important; object-fit: contain; }
        .logo-option input { position: absolute; opacity: 0; inset: 0; cursor: pointer; }
        .logo-option:has(input:checked) { border-color: var(--primary); background: rgba(115, 103, 240, 0.2); box-shadow: 0 0 10px var(--primary); }
        
        .logo-preview-table { width: 22px !important; height: 22px !important; object-fit: contain; }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; } .mobile-toggle { display: block !important; margin-right: 15px; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Gerenciar Planos</div>
        </div>
        <div class="small text-white-50 d-none d-md-block">Painel Administrativo</div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <div class="row">
            <div class="col-md-5 mb-4">
                <div class="card card-custom p-4">
                    <h5 class="mb-3 text-white fw-bold border-bottom border-secondary pb-2">
                        <?= $plano_editar ? '<i class="fas fa-edit text-warning"></i> Editar Plano' : '<i class="fas fa-plus text-success"></i> Novo Plano' ?>
                    </h5>
                    
                    <form method="POST">
                        <?php if($plano_editar): ?>
                            <input type="hidden" name="id_plano" value="<?= $plano_editar['id'] ?>">
                            <input type="hidden" name="atualizar_plano" value="1">
                        <?php else: ?>
                            <input type="hidden" name="criar_plano" value="1">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label text-white small fw-bold">NOME DO PLANO</label>
                            <input type="text-white" name="nome" class="form-control" placeholder="Ex: Mensal Claro" value="<?= $plano_editar['nome_plano'] ?? '' ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label text-white small fw-bold">LOGO / MARCA</label>
                            <div class="logo-selector">
                                <?php foreach($logos_disponiveis as $img => $nome_img): 
                                    $checked = ($plano_editar && $plano_editar['logo_perfil'] == $img) ? 'checked' : '';
                                    if(!$plano_editar && $img == 'iptv.png') $checked = 'checked';
                                ?>
                                <label class="logo-option" title="<?= $nome_img ?>">
                                    <input type="radio" name="logo_perfil" value="<?= $img ?>" <?= $checked ?>>
                                    <img src="img/<?= $img ?>" alt="<?= $nome_img ?>" onerror="this.src='https://via.placeholder.com/50?text=Icon'">
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-6 mb-3">
                                <label class="form-label text-white small fw-bold">DIAS</label>
                                <input type="number" name="dias" class="form-control" placeholder="30" value="<?= $plano_editar['dias'] ?? '' ?>" required>
                            </div>
                            <div class="col-6 mb-3">
                                <label class="form-label text-white small fw-bold">VALOR (R$)</label>
                                <input type="text" name="valor" class="form-control" placeholder="25.00" value="<?= $plano_editar['valor'] ?? '' ?>" required>
                            </div>
                        </div>

                        <?php if($plano_editar): ?>
                            <button type="submit" class="btn btn-warning w-100 fw-bold py-2 mt-2 text-dark">
                                <i class="fas fa-save me-2"></i> SALVAR ALTERAÇÕES
                            </button>
                            <a href="gerenciar_planos.php" class="btn btn-outline-secondary w-100 mt-2">Cancelar</a>
                        <?php else: ?>
                            <button type="submit" class="btn btn-primary w-100 fw-bold py-2 mt-2">
                                <i class="fas fa-plus-circle me-2"></i> CRIAR PLANO
                            </button>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <div class="col-md-7">
                <div class="card card-custom p-4">
                    <h5 class="mb-3 text-white fw-bold border-bottom border-secondary pb-2">Planos Ativos</h5>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover align-middle" style="background:transparent; --bs-table-bg: transparent;">
                            <thead>
                                <tr class="text-white-50 small">
                                    <th>MARCA</th>
                                    <th>DETALHES</th>
                                    <th>VALOR</th>
                                    <th class="text-end">AÇÕES</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(count($meus_planos) > 0): ?>
                                    <?php foreach($meus_planos as $p): ?>
                                    <tr>
                                        <td>
                                            <div class="bg-light rounded p-1 d-inline-block">
                                                <img src="img/<?= $p['logo_perfil'] ?>" class="logo-preview-table" onerror="this.style.opacity='0.5'">
                                            </div>
                                        </td>
                                        <td>
                                            <div class="fw-bold text-white"><?= htmlspecialchars($p['nome_plano']) ?></div>
                                            <div class="badge bg-secondary"><?= $p['dias'] ?> dias</div>
                                        </td>
                                        <td>
                                            <span class="text-success fw-bold fs-5">R$ <?= number_format($p['valor'], 2, ',', '.') ?></span>
                                        </td>
                                        <td class="text-end">
                                            <a href="?edit=<?= $p['id'] ?>" class="btn btn-warning btn-sm me-1" title="Editar"><i class="fas fa-pen text-dark"></i></a>
                                            <a href="?del=<?= $p['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Excluir este plano?')" title="Excluir"><i class="fas fa-trash"></i></a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="4" class="text-center py-5 text-muted small">Nenhum plano criado ainda. Seus clientes verão apenas o plano padrão de 30 dias.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
</script>
</body>
</html>