<?php
session_start();
require_once 'config.php';
$pdo = getConexaoAtiva();

// =========================================================================
// LÓGICA DE LOGIN DO CLIENTE FINAL
// =========================================================================
$erro_login = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_cliente'])) {
    $user = trim($_POST['username']);
    $pass = trim($_POST['password']);

    $stmt = $pdo->prepare("SELECT id, username, exp_date, max_connections, member_id FROM users WHERE username = ? AND password = ?");
    $stmt->execute([$user, $pass]);
    $cliente = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($cliente) {
        $_SESSION['cliente_logado'] = true;
        $_SESSION['cliente_id'] = $cliente['id'];
        $_SESSION['cliente_user'] = $cliente['username'];
        $_SESSION['dono_do_cliente'] = $cliente['member_id'];
        header("Location: ../xtreamui/");
        exit;
    } else {
        $erro_login = "Usuário ou senha incorretos!";
    }
}

if (isset($_GET['sair'])) {
    session_destroy();
    header("Location: ../xtreamui/");
    exit;
}

// =========================================================================
// 2. TELA DE LOGIN (SE NÃO ESTIVER LOGADO)
// =========================================================================
if (!isset($_SESSION['cliente_logado'])) {
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Área do Cliente - Login</title>
    <style>
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: #0f1114; display: flex; justify-content: center; align-items: center; height: 100vh; color: white; }
        .login-box { background: #1e2227; padding: 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); width: 100%; max-width: 350px; border: 1px solid #3a4149; text-align: center; }
        input { width: 100%; padding: 15px; margin-bottom: 20px; background: #121519; border: 1px solid #3a4149; color: white; border-radius: 8px; box-sizing: border-box; font-size: 15px; }
        button { width: 100%; padding: 15px; background: #007bff; border: none; color: white; border-radius: 8px; font-weight: bold; font-size: 16px; cursor: pointer; transition: 0.3s; }
        button:hover { background: #0056b3; }
        .erro { color: #ff4d4d; font-size: 14px; margin-bottom: 15px; background: rgba(220, 53, 69, 0.1); padding: 10px; border-radius: 5px; border: 1px solid #dc3545;}
    </style>
</head>
<body>
    <div class="login-box">
        <h2 style="margin-top:0;">Área do Cliente</h2>
        <p style="color: #8a94a1; font-size: 14px; margin-bottom: 30px;">Acesse para renovar sua assinatura</p>
        <?php if($erro_login) echo "<div class='erro'>$erro_login</div>"; ?>
        <form method="POST">
            <input type="hidden" name="login_cliente" value="1">
            <input type="text" name="username" placeholder="Seu Usuário" required autocomplete="off">
            <input type="password" name="password" placeholder="Sua Senha" required>
            <button type="submit">ACESSAR MEU PAINEL</button>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}

// =========================================================================
// 3. LÓGICA DE GERAÇÃO E CHECAGEM DE PIX (MERCADO PAGO) VIA AJAX
// =========================================================================
$id_do_revendedor = $_SESSION['dono_do_cliente'];

// AJAX: Gerar o PIX
if (isset($_POST['gerar_pix'])) {
    header('Content-Type: application/json');
    $plano_id = (int)$_POST['plano_id'];

    // 1. Puxa os dados do plano
    $stmtP = $pdo->prepare("SELECT * FROM billing_planos WHERE id = ? AND owner_id = ?");
    $stmtP->execute([$plano_id, $id_do_revendedor]);
    $plano = $stmtP->fetch(PDO::FETCH_ASSOC);

    if (!$plano) { echo json_encode(['erro' => 'Plano inválido.']); exit; }

    // 2. Puxa o Token do Mercado Pago do Dono do Cliente
    $stmtT = $pdo->prepare("SELECT mp_access_token FROM revendedor_configuracoes WHERE revendedor_id = ?");
    $stmtT->execute([$id_do_revendedor]);
    $token_mp = $stmtT->fetchColumn();

    if (empty($token_mp)) { echo json_encode(['erro' => 'O revendedor não configurou o Mercado Pago.']); exit; }

    // 3. Comunicação com a API do Mercado Pago
    $valor = (float)$plano['valor'];
    $data = [
        "transaction_amount" => $valor,
        "description" => "Renovação IPTV - " . $plano['meses'] . " Mes(es)",
        "payment_method_id" => "pix",
        "payer" => [ "email" => "cliente@iptv.com", "first_name" => $_SESSION['cliente_user'], "last_name" => "Cliente" ],
        "external_reference" => $_SESSION['cliente_user'] . "|||" . $plano['meses'] // Salva o nome do usuário e os meses pra renovar depois
    ];

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.mercadopago.com/v1/payments",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . $token_mp, "Content-Type: application/json" ],
    ]);

    $response = curl_exec($curl);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    $json = json_decode($response, true);

    if ($httpcode == 201 || $httpcode == 200) {
        $qr_code_base64 = $json['point_of_interaction']['transaction_data']['qr_code_base64'];
        $copia_cola = $json['point_of_interaction']['transaction_data']['qr_code'];
        $payment_id = $json['id'];
        
        echo json_encode([
            'sucesso' => true,
            'qr_code_base64' => $qr_code_base64,
            'copia_cola' => $copia_cola,
            'payment_id' => $payment_id
        ]);
    } else {
        echo json_encode(['erro' => 'Erro no Mercado Pago. Verifique seu Access Token.']);
    }
    exit;
}

// AJAX: Checar se o PIX foi pago e Renovar a Conta!
if (isset($_GET['checar_pagamento'])) {
    header('Content-Type: application/json');
    $payment_id = $_GET['checar_pagamento'];

    $stmtT = $pdo->prepare("SELECT mp_access_token FROM revendedor_configuracoes WHERE revendedor_id = ?");
    $stmtT->execute([$id_do_revendedor]);
    $token_mp = $stmtT->fetchColumn();

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.mercadopago.com/v1/payments/" . $payment_id,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . $token_mp ],
    ]);
    $response = curl_exec($curl);
    $json = json_decode($response, true);
    curl_close($curl);

    if (isset($json['status']) && $json['status'] === 'approved') {
        // PAGAMENTO APROVADO! VAMOS RENOVAR A CONTA!
        $ref = explode('|||', $json['external_reference']);
        $user_cli = $ref[0];
        $meses_comprados = (int)$ref[1];

        // Busca a conta do cliente para pegar o vencimento atual
        $stmtC = $pdo->prepare("SELECT id, exp_date FROM users WHERE username = ?");
        $stmtC->execute([$user_cli]);
        $cliData = $stmtC->fetch(PDO::FETCH_ASSOC);

        if ($cliData) {
            $data_atual = ($cliData['exp_date'] == 0 || $cliData['exp_date'] < time()) ? time() : $cliData['exp_date'];
            $nova_data = strtotime("+" . $meses_comprados . " months", $data_atual);

            // Atualiza no banco: Vencimento novo e status Ativo
            $pdo->prepare("UPDATE users SET exp_date = ?, enabled = 1 WHERE id = ?")->execute([$nova_data, $cliData['id']]);
            
            // Opcional: Se for revendedor, debita créditos
            // $pdo->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$meses_comprados, $id_do_revendedor]);
            
            echo json_encode(['pago' => true]);
        } else {
            echo json_encode(['pago' => false]);
        }
    } else {
        echo json_encode(['pago' => false]);
    }
    exit;
}

// =========================================================================
// 4. DASHBOARD DO CLIENTE (HTML)
// =========================================================================
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['cliente_id']]);
$dados_cliente = $stmt->fetch(PDO::FETCH_ASSOC);

$planos = [];
try {
    $stmtP = $pdo->prepare("SELECT * FROM billing_planos WHERE ativo = 1 AND owner_id = ? ORDER BY meses ASC");
    $stmtP->execute([$id_do_revendedor]);
    $planos = $stmtP->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$vencimento = ($dados_cliente['exp_date'] == 0) ? "Ilimitado" : date('d/m/Y H:i', $dados_cliente['exp_date']);
$status = ($dados_cliente['exp_date'] < time() && $dados_cliente['exp_date'] != 0) ? "<span style='color:#dc3545;'>VENCIDO</span>" : "<span style='color:#28a745;'>ATIVO</span>";

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minha Assinatura</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: #0f1114; color: #d1d5da; }
        .header { background: #1e2227; padding: 20px; text-align: center; border-bottom: 1px solid #3a4149; }
        .container { max-width: 900px; margin: 30px auto; padding: 0 20px; }
        
        .info-card { background: #272c33; padding: 25px; border-radius: 12px; border: 1px solid #3a4149; margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px; }
        .info-box { text-align: center; flex: 1; min-width: 150px; }
        .info-box span { display: block; font-size: 12px; color: #8a94a1; text-transform: uppercase; margin-bottom: 5px; }
        .info-box strong { font-size: 20px; color: white; }
        
        .planos-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
        .plano-card { background: #1e2227; border: 1px solid #3a4149; border-radius: 12px; padding: 25px; text-align: center; transition: 0.3s; position: relative; overflow: hidden; }
        .plano-card:hover { border-color: #007bff; transform: translateY(-5px); }
        .plano-nome { font-size: 18px; font-weight: bold; color: white; margin-bottom: 10px; }
        .plano-valor { font-size: 32px; font-weight: bold; color: #28a745; margin-bottom: 20px; }
        .btn-renovar { background: #007bff; color: white; border: none; padding: 12px; width: 100%; border-radius: 8px; font-weight: bold; font-size: 16px; cursor: pointer; transition: 0.2s; }
        .btn-renovar:hover { background: #0056b3; }
        
        .btn-sair { background: rgba(220, 53, 69, 0.1); border: 1px solid #dc3545; color: #dc3545; padding: 6px 12px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; transition: 0.2s;}
        .btn-sair:hover { background: #dc3545; color: white; }

        /* MODAL PIX */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.8); align-items: center; justify-content: center; }
        .modal-content { background: #1e2227; padding: 30px; border-radius: 12px; border: 1px solid #007bff; text-align: center; max-width: 350px; width: 90%; }
        .qr-code-img { width: 200px; height: 200px; border-radius: 8px; margin: 15px 0; border: 5px solid white; }
        .copia-cola { background: #121519; color: #28a745; padding: 10px; border-radius: 6px; border: 1px dashed #28a745; font-family: monospace; font-size: 12px; word-break: break-all; margin-bottom: 15px; }
        .btn-copiar { background: #28a745; color: white; border: none; padding: 10px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; margin-bottom: 10px; }
        .loader { border: 4px solid #3a4149; border-top: 4px solid #007bff; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto 15px auto; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

    <div class="header">
        <h2 style="margin:0; color:white;"><i class="fas fa-user-circle" style="color:#007bff;"></i> Portal do Cliente</h2>
        <div style="margin-top:15px; display:flex; justify-content:center; align-items:center; gap: 15px;">
            <span style="font-size: 14px;">Olá, <strong style="color:white;"><?php echo htmlspecialchars($dados_cliente['username']); ?></strong>!</span>
            <a href="?sair=1" class="btn-sair"><i class="fas fa-sign-out-alt"></i> SAIR</a>
        </div>
    </div>

    <div class="container">
        <h3 style="color:white; margin-top:0;"><i class="fas fa-info-circle"></i> Detalhes da sua Conta</h3>
        <div class="info-card">
            <div class="info-box"><span>Status</span><strong><?php echo $status; ?></strong></div>
            <div class="info-box" style="border-left: 1px solid #3a4149; border-right: 1px solid #3a4149;"><span>Vencimento</span><strong><?php echo $vencimento; ?></strong></div>
            <div class="info-box"><span>Telas Liberadas</span><strong><?php echo $dados_cliente['max_connections']; ?> Conexão(ões)</strong></div>
        </div>

        <h3 style="color:white; border-bottom: 1px solid #3a4149; padding-bottom: 10px; margin-bottom: 20px;"><i class="fas fa-bolt"></i> Renovar Assinatura (Pix Automático)</h3>
        
        <div class="planos-grid">
            <?php if(empty($planos)): ?>
                <div style="grid-column: 1 / -1; background: rgba(243, 156, 18, 0.1); border: 1px solid #f39c12; color: #f39c12; padding: 20px; border-radius: 8px; text-align:center;">Seu provedor ainda não configurou o pagamento automático. Entre em contato!</div>
            <?php else: foreach($planos as $p): ?>
                <div class="plano-card">
                    <div class="plano-nome"><?php echo htmlspecialchars($p['nome_plano']); ?></div>
                    <div style="color: #8a94a1; font-size: 14px; margin-bottom: 15px;">Adiciona +<?php echo $p['meses']; ?> Mês(es) de acesso</div>
                    <div class="plano-valor">R$ <?php echo number_format($p['valor'], 2, ',', '.'); ?></div>
                    <button class="btn-renovar" onclick="gerarPix(<?php echo $p['id']; ?>)"><i class="fas fa-qrcode"></i> RENOVAR COM PIX</button>
                </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <div id="pixModal" class="modal">
        <div class="modal-content" id="modalBox">
            <div id="loadingView">
                <div class="loader"></div>
                <h3 style="color:white;">Gerando PIX Seguro...</h3>
                <p style="color:#8a94a1; font-size:14px;">Conectando com o banco central.</p>
            </div>
            
            <div id="pixView" style="display:none;">
                <h3 style="color:#28a745; margin-top:0;"><i class="fas fa-check-circle"></i> PIX Gerado!</h3>
                <p style="color:white; font-size:14px;">Escaneie o QR Code abaixo com o app do seu banco para pagar e liberar seu acesso na hora.</p>
                <img id="imgQrCode" class="qr-code-img" src="">
                
                <p style="color:#8a94a1; font-size:12px; margin-bottom:5px;">Ou use o Copia e Cola:</p>
                <div class="copia-cola" id="txtCopiaCola"></div>
                <button class="btn-copiar" onclick="copiarChave()"><i class="fas fa-copy"></i> COPIAR CHAVE PIX</button>
                
                <div style="margin-top: 15px; font-size:12px; color:var(--info);">
                    <i class="fas fa-spinner fa-spin"></i> Aguardando pagamento... A tela irá atualizar sozinha.
                </div>
                <button onclick="fecharModal()" style="background:transparent; border:none; color:#dc3545; margin-top:15px; cursor:pointer;">Cancelar</button>
            </div>

            <div id="sucessoView" style="display:none;">
                <i class="fas fa-check-circle" style="color:#28a745; font-size:60px; margin-bottom:15px;"></i>
                <h2 style="color:white; margin:0;">PAGAMENTO APROVADO!</h2>
                <p style="color:#28a745; font-weight:bold;">Sua conta foi renovada com sucesso.</p>
                <button onclick="window.location.reload()" style="background:#007bff; color:white; border:none; padding:12px; width:100%; border-radius:6px; font-weight:bold; cursor:pointer; margin-top:15px;">ATUALIZAR PAINEL</button>
            </div>
        </div>
    </div>

    <script>
        let checkInterval;
        let pagamentoAtual = '';

        function gerarPix(planoId) {
            document.getElementById('pixModal').style.display = 'flex';
            document.getElementById('loadingView').style.display = 'block';
            document.getElementById('pixView').style.display = 'none';
            document.getElementById('sucessoView').style.display = 'none';

            let formData = new FormData();
            formData.append('gerar_pix', '1');
            formData.append('plano_id', planoId);

            fetch('', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.sucesso) {
                    document.getElementById('imgQrCode').src = "data:image/png;base64," + data.qr_code_base64;
                    document.getElementById('txtCopiaCola').innerText = data.copia_cola;
                    pagamentoAtual = data.payment_id;
                    
                    document.getElementById('loadingView').style.display = 'none';
                    document.getElementById('pixView').style.display = 'block';

                    // Começa a checar se pagou a cada 5 segundos
                    checkInterval = setInterval(checarPagamento, 5000);
                } else {
                    alert(data.erro);
                    fecharModal();
                }
            })
            .catch(() => {
                alert("Erro ao conectar com o banco. O revendedor configurou a chave Mercado Pago?");
                fecharModal();
            });
        }

        function checarPagamento() {
            if(!pagamentoAtual) return;
            fetch('?checar_pagamento=' + pagamentoAtual)
            .then(res => res.json())
            .then(data => {
                if (data.pago) {
                    clearInterval(checkInterval);
                    document.getElementById('pixView').style.display = 'none';
                    document.getElementById('sucessoView').style.display = 'block';
                    document.getElementById('modalBox').style.borderColor = '#28a745';
                }
            });
        }

        function copiarChave() {
            const texto = document.getElementById('txtCopiaCola').innerText;
            navigator.clipboard.writeText(texto).then(() => {
                alert("Chave Copia e Cola copiada para a área de transferência!");
            });
        }

        function fecharModal() {
            document.getElementById('pixModal').style.display = 'none';
            if (checkInterval) clearInterval(checkInterval);
        }
    </script>
</body>
</html>
