<?php
/**
 * 💰 Sistema de Pagamentos PIX & WhatsApp — Versão Reforçada 2025
 * ✅ Compatibilidade Máxima | ✅ Blindagem de Erros | ✅ Link de Conversão WhatsApp
 */

ob_start();

// 1. Headers de Segurança e Cache
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Inclusão do Header
if (file_exists("includes/header.php")) {
    include "includes/header.php";
}

/* ============================
    CONFIGURAÇÃO DE CAMINHOS
============================ */
$folderRel  = "api/qr/";
$dirPath    = __DIR__ . "/" . $folderRel;
$filename   = "qr.png";
$waFile     = $dirPath . "wa_link.txt"; // Arquivo para salvar o link do Whats
$targetFile = $dirPath . $filename;

// Garante que o diretório existe e tem permissões corretas
if (!is_dir($dirPath)) {
    @mkdir($dirPath, 0755, true);
}

/* ============================
    PROCESSAMENTO DO POST
============================ */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["pix_link"])) {
    $pixLink = trim($_POST["pix_link"]);
    $waNumber = trim($_POST["wa_number"] ?? '');

    if (empty($pixLink)) {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => '❌ O código PIX está vazio.'];
    } else {
        // --- GERAÇÃO DO QR CODE PIX ---
        $apiUrl = "https://i.ibb.co/qFFCdFTr/ok-qrcode.png" . urlencode($pixLink);
        
        $qrData = false;
        $httpCode = 0;
        
        if (function_exists('curl_init')) {
            $ch = curl_init($apiUrl);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 15,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_USERAGENT      => 'PIX_WA_Manager_2025'
            ]);
            $qrData = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
        } 

        if ($qrData && $httpCode == 200 && bin2hex(substr($qrData, 0, 4)) === "89504e47") {
            @file_put_contents($targetFile, $qrData);
            
            // --- GERAÇÃO DO LINK DE WHATSAPP ---
            if (!empty($waNumber)) {
                // Remove caracteres não numéricos
                $waNumber = preg_replace('/\D/', '', $waNumber);
                $message = urlencode("Olá, realizei o pagamento via PIX. Segue o código utilizado: \n\n" . $pixLink);
                $waLink = "https://api.whatsapp.com/send?phone=" . $waNumber . "&text=" . $message;
                @file_put_contents($waFile, $waLink);
            }

            $_SESSION['alert'] = ['type' => 'success', 'message' => '✅ PIX e Link de WhatsApp atualizados!'];
        } else {
            $_SESSION['alert'] = ['type' => 'danger', 'message' => '❌ Erro ao gerar QR Code. Verifique sua conexão.'];
        }
    }

    header("Location: qrcode.php");
    exit;
}

$alert = $_SESSION['alert'] ?? null;
unset($_SESSION['alert']);

// Carrega link do Whats se existir
$currentWaLink = file_exists($waFile) ? file_get_contents($waFile) : "";
?>

<style>
    :root { --pix-color: #32b1a4; --wa-color: #25d366; --font-main: 'Inter', system-ui, sans-serif; }
    body { font-family: var(--font-main); background-color: #f4f7f6; }
    .card-pix { border: none; border-radius: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.1); background: #fff; }
    .card-pix-header { background: linear-gradient(135deg, #32b1a4 0%, #1a237e 100%); color: white; padding: 25px; border-radius: 20px 20px 0 0 !important; }
    .qr-container { background: #ffffff; border: 2px dashed #d1d5db; border-radius: 15px; padding: 20px; transition: 0.3s; }
    .img-pix { width: 100%; max-width: 220px; height: auto; border-radius: 12px; }
    .btn-pix { background-color: var(--pix-color); border: none; color: white; padding: 14px; font-weight: 700; border-radius: 12px; transition: 0.3s; width: 100%; }
    .btn-pix:hover { background-color: #288e84; box-shadow: 0 8px 20px rgba(50, 177, 164, 0.3); color: white; }
    .wa-badge { background-color: var(--wa-color); color: white; font-size: 11px; padding: 5px 12px; border-radius: 50px; text-decoration: none; display: inline-block; margin-top: 10px; }
    .wa-badge:hover { background-color: #1eb954; color: white; }
</style>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-9 col-lg-6">

            <?php if ($alert): ?>
                <div class="alert alert-<?= $alert['type'] ?> alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
                    <?= htmlspecialchars($alert['message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card card-pix">
                <div class="card-header card-pix-header text-center">
                    <h5 class="mb-0 fw-bold text-white"><i class="fas fa-wallet me-2"></i> PAGAMENTO & WHATSAPP</h5>
                </div>
                <div class="card-body p-4">
                    
                    <div class="row align-items-center mb-4">
                        <div class="col-sm-5 text-center border-end">
                            <small class="text-uppercase fw-bold text-muted d-block mb-2" style="font-size: 10px;">QR Code</small>
                            <?php $qr_src = file_exists($targetFile) ? $folderRel . $filename . "?v=" . time() : "https://via.placeholder.com/300x300?text=Aguardando"; ?>
                            <img src="<?= $qr_src ?>" class="img-pix" alt="QR Code PIX">
                        </div>
                        <div class="col-sm-7 ps-4">
                            <h6 class="fw-bold mb-1">Status do Link</h6>
                            <p class="small text-muted mb-2">O link de WhatsApp redireciona o cliente com o comprovante.</p>
                            <?php if (!empty($currentWaLink)): ?>
                                <a href="<?= $currentWaLink ?>" target="_blank" class="wa-badge">
                                    <i class="fab fa-whatsapp me-1"></i> Testar Link de Conversão
                                </a>
                            <?php else: ?>
                                <span class="badge bg-light text-secondary border">WhatsApp não configurado</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-secondary">NÚMERO DO WHATSAPP (COM DDD)</label>
                            <input type="text" name="wa_number" class="form-control bg-light" placeholder="Ex: 5511999999999" style="border-radius: 10px;">
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-bold text-secondary">CÓDIGO PIX "COPIA E COLA"</label>
                            <textarea name="pix_link" class="form-control bg-light" rows="3" placeholder="Insira o código PIX..." required style="border-radius: 10px;"></textarea>
                        </div>

                        <button type="submit" class="btn btn-pix">
                            <i class="fas fa-sync-alt me-2"></i> ATUALIZAR DADOS DE PAGAMENTO
                        </button>
                    </form>

                </div>
            </div>

            <div class="text-center mt-4">
                <a href="index.php" class="text-decoration-none text-muted small"><i class="fas fa-arrow-left me-1"></i> Painel Principal</a>
            </div>

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

<script>
    document.addEventListener("DOMContentLoaded", function() {
        setTimeout(() => {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(a => { new bootstrap.Alert(a).close(); });
        }, 5000);
    });
</script>

<?php 
if (file_exists("includes/footer.php")) { include "includes/footer.php"; }
ob_end_flush();
?>