<?php
// config_painel.php - Com Sidebar e Atualização da Tabela ADM
session_start();
require_once 'includes/db.php'; 

if (!isset($_SESSION['logged_in_fxtream']) || $_SESSION['logged_in_fxtream'] !== true) {
    header('Location: index.php');
    exit;
}

// === ATUALIZAR DADOS ===
if (isset($_POST['atualizar'])) {
    $novo_usuario = trim($_POST['usuario']);
    $nova_senha   = trim($_POST['senha']);
    $novo_zap     = $_POST['whatsapp'];
    $novo_dominio = trim($_POST['dominio']);
    $novo_nome    = trim($_POST['nome_servidor']);
    
    // Configurações Extras
    $confianca_ativo = isset($_POST['confianca_ativo']) ? 1 : 0;
    $confianca_dias  = intval($_POST['confianca_dias']);
    $senha_p2p       = $_POST['senha_p2p'];

    // Ajusta URL
    $novo_dominio = rtrim($novo_dominio, '/');
    if (!preg_match("~^(?:f|ht)tps?://~i", $novo_dominio)) $novo_dominio = "http://" . $novo_dominio;

    try {
        // 1. Atualiza tabela CONFIGURACOES
        $sql = "UPDATE configuracoes SET 
                usuario_adm = :user, 
                senha_adm = :pass, 
                whatsapp = :zap, 
                dominio_url = :dom,
                nome_servidor = :nome,
                confianca_ativo = :c_ativo,
                confianca_dias = :c_dias
                WHERE id = 1";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':user'    => $novo_usuario,
            ':pass'    => $nova_senha,
            ':zap'     => $novo_zap,
            ':dom'     => $novo_dominio,
            ':nome'    => $novo_nome,
            ':c_ativo' => $confianca_ativo,
            ':c_dias'  => $confianca_dias
        ]);

        // 2. Atualiza tabela ADM (IMPORTANTE: É aqui que o login é verificado)
        $sql_adm = "UPDATE adm SET username = :user, password = :pass WHERE id = 1";
        $stmt_adm = $pdo->prepare($sql_adm);
        $stmt_adm->execute([':user' => $novo_usuario, ':pass' => $nova_senha]);

        // 3. Atualiza Senha P2P
        $pdo->exec("CREATE TABLE IF NOT EXISTS settings (setting_name VARCHAR(50) PRIMARY KEY, setting_value TEXT)");
        $sql_p2p = "INSERT INTO settings (setting_name, setting_value) VALUES ('p2p_default_password', :p2p1) 
                    ON DUPLICATE KEY UPDATE setting_value = :p2p2";
        $stmt_p2p = $pdo->prepare($sql_p2p);
        $stmt_p2p->execute([':p2p1' => $senha_p2p, ':p2p2' => $senha_p2p]);
        
        echo "<script>alert('Configurações e Login do Admin atualizados com sucesso!'); window.location.href='config_painel.php';</script>";

    } catch (PDOException $e) { echo "<script>alert('Erro SQL: " . $e->getMessage() . "');</script>"; }
}

// === BUSCAR DADOS ===
try {
    // Busca Configurações
    $stmt = $pdo->query("SELECT * FROM configuracoes WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!$config) $config = [];
    
    // Busca Login Real da Tabela ADM (para garantir que mostra o atual)
    $stmt_adm = $pdo->query("SELECT username, password FROM adm WHERE id = 1");
    $adm_data = $stmt_adm->fetch(PDO::FETCH_ASSOC);
    
    // Se achou na tabela ADM, usa esses dados. Se não, usa da tabela configuracoes
    $usuario_atual = $adm_data ? $adm_data['username'] : ($config['usuario_adm'] ?? 'admin');
    $senha_atual   = $adm_data ? $adm_data['password'] : ($config['senha_adm'] ?? 'admin');

    // Valores padrão
    $nome_serv = $config['nome_servidor'] ?? 'TOP IPTV';
    $c_ativo = $config['confianca_ativo'] ?? 0;
    $c_dias = $config['confianca_dias'] ?? 3;

    // Busca Senha P2P
    $stmt_p2p = $pdo->query("SELECT setting_value FROM settings WHERE setting_name = 'p2p_default_password'");
    $senha_p2p_atual = $stmt_p2p->fetchColumn();
    if(!$senha_p2p_atual) $senha_p2p_atual = '1234';

} catch (PDOException $e) { die("Erro configs: " . $e->getMessage()); }
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Configurações</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">

    <style>
        body { background-color: #1a1c23; color: #a6a7ad; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .card { background-color: #24262d; border: 1px solid #2f323a; }
        .form-control { background-color: #1a1c23; border: 1px solid #4c4f5a; color: white; }
        .form-control:focus { background-color: #1a1c23; color: white; border-color: #7e3af2; }
        label { color: #ccc; margin-bottom: 5px; font-weight: 500; }
        .btn-success { background-color: #7e3af2; border-color: #7e3af2; }
        .section-title { border-bottom: 1px solid #444; padding-bottom: 10px; margin-bottom: 20px; color: #fff; font-weight: bold; font-size: 1.1em; }
        .custom-switch .custom-control-label::before { background-color: #4c4f5a; border-color: #4c4f5a; }
        .custom-control-input:checked ~ .custom-control-label::before { background-color: #7e3af2; border-color: #7e3af2; }

        /* ============================================================
           LAYOUT RESPONSIVO (SIDEBAR + CONTEÚDO)
           ============================================================ */
        
        /* PC (Telas Grandes) */
        @media (min-width: 992px) {
            #sidebar { 
                display: block !important; 
                width: 240px; 
                position: fixed; top: 0; left: 0; height: 100vh; 
                z-index: 1000; overflow-y: auto; 
            }
            .right-column { 
                margin-left: 240px; 
                width: calc(100% - 240px); 
                padding: 0;
            }
            .btn-voltar-mobile { display: none; }
        }

        /* CELULAR (Telas Pequenas) */
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { 
                margin-left: 0 !important; 
                width: 100% !important; 
                padding: 0;
            }
            .btn-voltar-mobile {
                display: inline-block;
                margin-right: 10px;
                color: #fff;
                font-size: 1.2rem;
            }
        }

        /* Cabeçalho Customizado */
        .page-header {
            padding: 20px; 
            border-bottom: 1px solid #333; 
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #24262d;
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0"><i class="fa fa-cogs mr-2"></i> Configurações Gerais</h4>
                </div>
                <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block">Voltar</a>
            </div>

            <div class="container-fluid px-4 pb-5">
                <div class="row justify-content-center">
                    <div class="col-md-10 col-lg-8">
                        
                        <div class="card shadow-lg">
                            <div class="card-body p-4">
                                <form method="POST">
                                    
                                    <h6 class="section-title text-warning"><i class="fa fa-desktop"></i> Aparência</h6>
                                    <div class="form-group mb-3">
                                        <label>Nome do Servidor (Painel)</label>
                                        <input type="text" name="nome_servidor" class="form-control" value="<?php echo htmlspecialchars($nome_serv); ?>" required>
                                    </div>

                                    <h6 class="section-title text-info mt-4"><i class="fa fa-handshake"></i> Renovação de Confiança</h6>
                                    <div class="row">
                                        <div class="col-md-6 d-flex align-items-center">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="switchConfianca" name="confianca_ativo" <?php echo ($c_ativo == 1) ? 'checked' : ''; ?>>
                                                <label class="custom-control-label font-weight-bold" for="switchConfianca">Ativar Botão "Confiança"</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <label>Dias de Confiança (Grátis)</label>
                                            <input type="number" name="confianca_dias" class="form-control" value="<?php echo $c_dias; ?>" min="1" max="30">
                                        </div>
                                    </div>

                                    <h6 class="section-title text-danger mt-4"><i class="fa fa-share-alt"></i> Configuração P2P</h6>
                                    <div class="form-group">
                                        <label>Senha Padrão P2P (Para novos clientes)</label>
                                        <input type="text" name="senha_p2p" class="form-control" value="<?php echo htmlspecialchars($senha_p2p_atual); ?>" required>
                                    </div>

                                    <h6 class="section-title text-success mt-4"><i class="fa fa-user-shield"></i> Credenciais Admin (Login do Painel)</h6>
                                    <div class="row">
                                        <div class="col-md-6 form-group">
                                            <label>Usuário</label>
                                            <input type="text" name="usuario" class="form-control" value="<?php echo htmlspecialchars($usuario_atual); ?>" required>
                                        </div>
                                        <div class="col-md-6 form-group">
                                            <label>Senha</label>
                                            <input type="text" name="senha" class="form-control" value="<?php echo htmlspecialchars($senha_atual); ?>" required>
                                        </div>
                                    </div>

                                    <h6 class="section-title text-primary mt-4"><i class="fa fa-globe"></i> Conexão</h6>
                                    <div class="form-group">
                                        <label>Domínio DNS</label>
                                        <input type="text" name="dominio" class="form-control" value="<?php echo htmlspecialchars($config['dominio_url']); ?>" placeholder="http://url:porta" required>
                                    </div>
                                    <div class="form-group">
                                        <label>WhatsApp Suporte</label>
                                        <input type="text" name="whatsapp" class="form-control" value="<?php echo htmlspecialchars($config['whatsapp']); ?>">
                                    </div>

                                    <div class="mt-4 text-right">
                                        <button type="submit" name="atualizar" class="btn btn-success btn-lg btn-block font-weight-bold">SALVAR ALTERAÇÕES</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                    </div>
                </div>
            </div>

        </div> </div>
</div>

<script src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
<script src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
</body>
</html>