<?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"; 
try { $conf = $connGeral->query("SELECT NomePainel FROM site_config LIMIT 1")->fetch(); if($conf) $nomePainel = $conf['NomePainel']; } catch(Exception $e){}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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: #7367f0; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #ffffff; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; }
        
        /* Sidebar Estilo Dashboard */
        .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; font-weight: 500; display:flex; align-items:center; gap:10px; margin-bottom:5px; text-decoration:none; 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; padding: 30px; transition: 0.3s; }
        .card-custom { background: var(--bg-card); border: 1px solid #2b2b40; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
        .form-control { background: #2b2b40; border: 1px solid #555; color: #fff; }
        .form-control:focus { background: #2b2b40; color: #fff; border-color: var(--primary); box-shadow: 0 0 0 0.2rem rgba(115, 103, 240, 0.25); }
        
        /* SELETOR DE LOGOS */
        .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; transition: 0.2s; position: relative; }
        .logo-option img { max-width: 100%; max-height: 100%; object-fit: contain; }
        .logo-option:hover { border-color: var(--primary); }
        .logo-option input { position: absolute; opacity: 0; cursor: pointer; inset: 0; }
        .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: 40px; height: 40px; object-fit: contain; background: #fff; border-radius: 5px; padding: 2px; }
        
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block; } }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; } .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <div class="nav flex-column mt-4">
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
        <?php endif; ?>
        
        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="clientes_online.php" class="nav-link"><i class="fas fa-wifi"></i> Online Agora</a>
        <a href="monitor.php" class="nav-link"><i class="fas fa-bell"></i> Monitor</a>
        
        <a href="gerenciar_planos.php" class="nav-link active"><i class="fas fa-tags"></i> Meus Planos</a>
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Config. Financeira</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <h3 class="fw-bold mb-4 text-white"><i class="fas fa-tags text-primary me-2"></i> Gerenciar Planos</h3>

    <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" 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">Nenhum plano criado ainda.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </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>
