<?php

require __DIR__ . '/vendor/autoload.php';

use App\Pix\PixStatusStorage;
use App\Pix\Sicoob as SP;

header('Content-Type: application/json');

$logFile = __DIR__ . '/storage/webhook-log.jsonl';
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

function appendWebhookLog(string $logFile, array $entry): void
{
    file_put_contents($logFile, json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$rawBody = '';
if ($method === 'POST') {
    $rawBody = (string) file_get_contents('php://input');
}

$requestPath = $_SERVER['REQUEST_URI'] ?? '';
$normalizedPath = preg_replace('#/+$#', '', $requestPath);
if ($normalizedPath === '/webhook.php/pix') {
    $normalizedPath = '/webhook.php';
}

appendWebhookLog($logFile, [
    'time' => date('c'),
    'method' => $method,
    'path' => $requestPath,
    'normalized_path' => $normalizedPath,
    'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
    'host' => $_SERVER['HTTP_HOST'] ?? null,
    'content_type' => $_SERVER['CONTENT_TYPE'] ?? null,
    'query' => $_GET,
    'body' => $rawBody,
]);

if ($method === 'POST') {
    $payload = json_decode($rawBody, true);
    if (!is_array($payload)) {
        echo json_encode(['ok' => false, 'message' => 'payload invalido']);
        exit;
    }

    $txid = PixStatusStorage::extractTxid($payload);
    $status = PixStatusStorage::normalizeStatus($payload);

    if ($txid) {
        $saved = PixStatusStorage::save($txid, $status, $payload);
        echo json_encode([
            'ok' => true,
            'txid' => $txid,
            'status' => $status,
            'received' => $payload,
            'saved' => $saved,
        ]);
    } else {
        echo json_encode(['ok' => false, 'message' => 'txid nao encontrado', 'received' => $payload]);
    }

    exit;
}

if ($method === 'GET') {
    $txid = $_GET['txid'] ?? null;
    if ($txid) {
        $data = PixStatusStorage::load($txid);
        echo json_encode($data ?: ['status' => 'pendente']);
    } else {
        echo json_encode(['message' => 'envie ?txid=...']);
    }
    exit;
}

echo json_encode(['ok' => false, 'message' => 'metodo nao suportado']);
