<?php

require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/admin/config_.php';

use App\Pix\Payload as PP;
use App\Pix\PixStatusStorage;
use App\Pix\Sicoob as SP;
use Mpdf\QrCode\QrCode;
use Mpdf\QrCode\Output\Png;

$objPix = new SP();

$cobranca = [
    'calendario' => [
        'expiracao' => 3600
    ],
    'devedor' => [
        'cpf' => '81265980420',
        'nome' => 'MIGUEL ARCANJO'
    ],
    'valor' => [
        'original' => '0.01'
    ],
    'chave' => SICOOBPIX_CHAVE,
    'solicitacaoPagador' => 'Mensagem teste Mensalidade'
];

$resposta = [];

$rawResponse = $_POST['response'] ?? $_GET['response'] ?? $_REQUEST['response'] ?? null;
$externalPayload = $_POST['payload'] ?? $_GET['payload'] ?? $_REQUEST['payload'] ?? null;
$externalTxid = $_POST['txid'] ?? $_GET['txid'] ?? $_REQUEST['txid'] ?? null;
$externalValor = $_POST['valor'] ?? $_GET['valor'] ?? $_REQUEST['valor'] ?? null;
$externalLocation = $_POST['location'] ?? $_GET['location'] ?? $_REQUEST['location'] ?? null;
$externalBrcode = $_POST['brcode'] ?? $_GET['brcode'] ?? $_REQUEST['brcode'] ?? null;

if (!empty($rawResponse)) {
    if (is_string($rawResponse)) {
        $decodedResponse = json_decode($rawResponse, true);
        if (is_array($decodedResponse)) {
            $resposta = $decodedResponse;
        }
    } elseif (is_array($rawResponse)) {
        $resposta = $rawResponse;
    }
} elseif (!empty($externalPayload)) {
    if (is_string($externalPayload)) {
        $decodedPayload = json_decode($externalPayload, true);
        if (is_array($decodedPayload)) {
            $resposta = $decodedPayload;
        }
    } elseif (is_array($externalPayload)) {
        $resposta = $externalPayload;
    }
}

if (empty($resposta)) {
    try {
        $resposta = $objPix->criarCob($cobranca);
    } catch (\Throwable $e) {
        echo 'Problema ao gerar PIX';
        echo '<pre>';
        echo $e->getMessage();
        echo '</pre>';
        exit;
    }
}

$payloadResposta = $resposta;
if (isset($resposta['raw']) && is_string($resposta['raw']) && $resposta['raw'] !== '') {
    $decodedRaw = json_decode($resposta['raw'], true);
    if (is_array($decodedRaw)) {
        $payloadResposta = $decodedRaw;
    }
}

$valorOriginal = $payloadResposta['valor']['original'] ?? $payloadResposta['valor'] ?? $cobranca['valor']['original'] ?? $externalValor ?? '0.00';
$txid = $payloadResposta['txid'] ?? $externalTxid ?? null;
$location = $payloadResposta['location'] ?? $externalLocation ?? null;
$brcode = $payloadResposta['brcode'] ?? $externalBrcode ?? null;

if (!empty($location)) {
    $objPayload = (new PP)
        ->__set('titularConta', SICOOBPIX_TITULAR)
        ->__set('cidTitular', SICOOBPIX_CID_TITULAR)
        ->__set('cep', SICOOBPIX_CEP)
        ->__set('valor', $valorOriginal)
        ->__set('txid', $txid)
        ->__set('url', $location)
        ->__set('pagamentoUnico', true);

    $payloadQrCode = $objPayload->getPayloadQR();
} elseif (!empty($brcode)) {
    $payloadQrCode = $brcode;
} else {
    echo 'Problema ao gerar PIX';
    echo '<pre>';
    print_r($payloadResposta);
    echo '</pre>';
    exit;
}

$qrCode = new QrCode($payloadQrCode);
$image = (new Png)->output($qrCode, 350);

$statusInfo = [];
if (!empty($txid)) {
    $statusInfo = PixStatusStorage::load((string) $txid) ?? [];
}
$statusText = $statusInfo['status'] ?? 'pendente';
?>

<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QrCode Pix Sicoob</title>
</head>
<body style="text-align: center">
    <h1>QR CODE DINÂMICO DO PIX</h1>
    <br>

    <img src="data:image/png;base64, <?= base64_encode($image) ?>" >
    <br>

    Código pix: <br>
    <strong><?= $payloadQrCode ?></strong><br>
    <strong><?= htmlspecialchars((string) $txid) ?></strong>
    <br><br>
    <strong>Status do pagamento:</strong> <span id="status-pagamento" style="font-weight: bold; color: #d97706;"><?= htmlspecialchars($statusText) ?></span>
    <br>
    <small>O status muda automaticamente quando o webhook do Sicoob notificar o pagamento.</small>

    <script>
        const txid = <?= json_encode((string) ($txid ?? '')) ?>;
        const statusEl = document.getElementById('status-pagamento');
        let lastStatus = <?= json_encode($statusText) ?>;

        function applyStatus(status) {
            const normalized = (status || '').toLowerCase();
            if (normalized === 'pago') {
                statusEl.textContent = 'pago';
                statusEl.style.color = '#16a34a';
            } else if (normalized === 'cancelado') {
                statusEl.textContent = 'cancelado';
                statusEl.style.color = '#dc2626';
            } else {
                statusEl.textContent = 'pendente';
                statusEl.style.color = '#d97706';
            }
            lastStatus = normalized;
        }

        function refreshStatus() {
            if (!txid) {
                return;
            }

            fetch('webhook.php?txid=' + encodeURIComponent(txid))
                .then(response => response.json())
                .then(data => {
                    if (data && data.status) {
                        applyStatus(data.status);
                    }
                })
                .catch(() => {});
        }

        if (txid) {
            applyStatus(<?= json_encode($statusText) ?>);
            refreshStatus();
            setInterval(refreshStatus, 2000);
        }
    </script>
</body>
</html>