<?php
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 = $_POST['usuario'];
    $nova_senha   = $_POST['senha'];
    $novo_zap     = $_POST['whatsapp'];
    $novo_dominio = trim($_POST['dominio']);
    $novo_nome    = trim($_POST['nome_servidor']);
    
    // Configurações de Confiança
    $confianca_ativo = isset($_POST['confianca_ativo']) ? 1 : 0;
    $confianca_dias  = intval($_POST['confianca_dias']);

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

    try {
        $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->bindParam(':user', $novo_usuario);
        $stmt->bindParam(':pass', $nova_senha);
        $stmt->bindParam(':zap', $novo_zap);
        $stmt->bindParam(':dom', $novo_dominio);
        $stmt->bindParam(':nome', $novo_nome);
        $stmt->bindParam(':c_ativo', $confianca_ativo);
        $stmt->bindParam(':c_dias', $confianca_dias);
        
        if ($stmt->execute()) {
            echo "<script>alert('Salvo com sucesso!'); window.location.href='config_painel.php';</script>";
        }
    } catch (PDOException $e) { echo "<script>alert('Erro SQL: " . $e->getMessage() . "');</script>"; }
}

// === BUSCAR DADOS ===
try {
    $stmt = $pdo->query("SELECT * FROM configuracoes WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!$config) $config = [];
    
    // Valores padrão para evitar erro
    $nome_serv = $config['nome_servidor'] ?? 'TOP IPTV';
    $c_ativo = $config['confianca_ativo'] ?? 0;
    $c_dias = $config['confianca_dias'] ?? 3;

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

<!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://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <style>
        body { background-color: #1a1c23; color: #a6a7ad; }
        .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; }
        .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; }
    </style>
</head>
<body>
    <div class="container mt-5 mb-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow-lg">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fa fa-cogs"></i> Configurações Gerais</h5>
                        <a href="dashboard.php" class="btn btn-sm btn-secondary">Voltar</a>
                    </div>
                    <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-success mt-4"><i class="fa fa-user-shield"></i> Credenciais Admin</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($config['usuario_adm']); ?>" required>
                                </div>
                                <div class="col-md-6 form-group">
                                    <label>Senha</label>
                                    <input type="text" name="senha" class="form-control" value="<?php echo htmlspecialchars($config['senha_adm']); ?>" 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>
</body>
</html>
