<?php

require '../config.php';

ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

// mesmo “banco” usado no gerador
const PIX_DB_PATH = __DIR__ . '/dutty.json';

$raw = file_get_contents('php://input');          // pega o corpo cru (JSON)
$decoded = json_decode($raw, true);               // tenta decodificar (opcional)

$dir = __DIR__ . '/requests';
if (!is_dir($dir)) {
    @mkdir($dir, 0775, true);
}

// se existir data.id, usa no nome do arquivo; senão, usa timestamp
$id = $decoded['data']['id'] ?? null;
$fname = $id ? "req_{$id}.json" : ('req_' . date('Ymd_His') . '_' . bin2hex(random_bytes(3)) . '.json');

file_put_contents($dir . '/' . $fname, $raw, LOCK_EX);  // salva o JSON recebido, sem mexer

// ========== helpers ==========

function load_body(): array
{
    $raw = file_get_contents('php://input');
    @file_put_contents(__DIR__ . '/webhook_log.jsonl', $raw . "\n", FILE_APPEND);
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function normalize_payload(array $in): array
{
    $src = isset($in['data']) && is_array($in['data']) ? $in['data'] : $in;
    $id = $src['id'] ?? ($src['transactionId'] ?? null);
    $status = $src['status'] ?? null;

    if (is_string($id) && ctype_digit($id))
        $id = (int) $id;

    return [
        'id' => $id,
        'status' => is_string($status) ? strtolower($status) : null,
        'raw' => $in,
    ];
}

function db_load(string $path): array
{
    if (!file_exists($path) || filesize($path) === 0)
        return [];
    $json = file_get_contents($path);
    $arr = json_decode($json, true);
    return is_array($arr) ? $arr : [];
}

/**
 * Upsert do status no “banco” JSON
 */
function db_upsert_status(int $txid, string $newStatus, array $rawPayload, string $path = PIX_DB_PATH): bool
{
    date_default_timezone_set('America/Sao_Paulo');

    if (!file_exists($path)) {
        file_put_contents($path, "[]", LOCK_EX);
    }

    $fp = fopen($path, 'c+');
    if ($fp === false)
        return false;

    $ok = false;

    if (flock($fp, LOCK_EX)) {
        $size = filesize($path);
        rewind($fp);
        $json = $size > 0 ? fread($fp, $size) : '[]';
        $data = json_decode($json, true);
        if (!is_array($data)) {
            $data = [];
        }

        $foundIndex = -1;
        for ($i = count($data) - 1; $i >= 0; $i--) {
            $row = $data[$i] ?? null;
            if (!is_array($row))
                continue;
            if (($row['transactionId'] ?? null) == $txid) {
                $foundIndex = $i;
                break;
            }
        }

        if ($foundIndex >= 0) {
            if (!isset($data[$foundIndex]['resp']) || !is_array($data[$foundIndex]['resp'])) {
                $data[$foundIndex]['resp'] = [];
            }
            $data[$foundIndex]['resp']['status'] = $newStatus;
            $data[$foundIndex]['status'] = $newStatus;
            $data[$foundIndex]['updated_at'] = date('Y-m-d H:i:s');
            $data[$foundIndex]['webhook_last'] = $rawPayload;
        } else {
            $data[] = [
                'ts' => date('Y-m-d H:i:s'),
                'type' => 'upsert_from_webhook',
                'transactionId' => $txid,
                'status' => $newStatus,
                'resp' => ['status' => $newStatus],
                'webhook_last' => $rawPayload,
            ];
        }

        $out = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        ftruncate($fp, 0);
        rewind($fp);
        $ok = (fwrite($fp, $out) !== false);
        fflush($fp);
        flock($fp, LOCK_UN);
    }

    fclose($fp);
    return $ok;
}

/** procura e retorna o ÚLTIMO registro com transactionId = $txid */
function db_find_by_txid(int $txid, string $path = PIX_DB_PATH): ?array
{
    $all = db_load($path);
    for ($i = count($all) - 1; $i >= 0; $i--) {
        $row = $all[$i] ?? null;
        if (!is_array($row))
            continue;
        if (($row['transactionId'] ?? null) == $txid) {
            return $row;
        }
    }
    return null;
}

/** pega um token de clique (prioriza fbclid) */
function pick_click_token(array $meta): string
{
    if (!empty($meta['fbclid']))
        return (string) $meta['fbclid'];
    if (!empty($meta['gclid']))
        return (string) $meta['gclid'];
    if (!empty($meta['msclkid']))
        return (string) $meta['msclkid'];
    if (!empty($meta['ttclid']))
        return (string) $meta['ttclid'];
    return '';
}

// ========== fluxo do webhook ==========

$body = load_body();
$norm = normalize_payload($body);

if (!isset($norm['id']) || !isset($norm['status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Payload inválido: id/status ausentes']);
    exit;
}

$txid = (int) $norm['id'];
$status = $norm['status']; // paid | waiting_payment | refused | approved | authorized | ...

// Atualiza o “banco”
$ok = db_upsert_status($txid, $status, $body);

if (!$ok) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Falha ao atualizar banco JSON']);
    exit;
}

// === se status for pago/confirmado, dispara UTMify ===
$paidStatuses = ['paid', 'approved', 'authorized']; // ajuste se necessário
if (in_array($status, $paidStatuses, true)) {
    // carrega o registro salvo
    $reg = db_find_by_txid($txid);
    if ($reg) {
        // monta os campos esperados pela sua add_utm(...)
        $lead = $reg['lead'] ?? [];
        $meta = $reg['meta'] ?? [];

        $nome = (string) ($lead['name'] ?? '');
        $cpf = (string) ($lead['document'] ?? '');
        $email = (string) ($lead['email'] ?? '');
        $telefone = (string) ($lead['phone'] ?? '');

        // valor: você pode passar em reais com vírgula que sua add_utm já trata; fica bonitinho:
        $valorCents = (int) ($reg['valor_centavos'] ?? ($reg['resp']['amount'] ?? 0));
        $valorReais = number_format($valorCents / 100, 2, ',', ''); // ex: "57,40"

        $utm_source = (string) ($meta['utm_source'] ?? '');
        $utm_campaign = (string) ($meta['utm_campaign'] ?? '');
        $utm_medium = (string) ($meta['utm_medium'] ?? '');
        $utm_content = (string) ($meta['utm_content'] ?? '');
        $utm_term = (string) ($meta['utm_term'] ?? '');

        $utm_token = $utmfy_token;
        $payment_id = (string) $txid;

        // chama tua função se existir
        if (function_exists('add_utm')) {
            try {
                $res = add_utm(
                    $nome,
                    $cpf,
                    $email,
                    $telefone,
                    $valorReais,     // ela converte p/ centavos internamente
                    $utm_source,
                    $utm_campaign,
                    $utm_medium,
                    $utm_content,
                    $utm_term,
                    $payment_id,     // token/id do pedido
                    $utm_token,      // click id (opcional, mas útil)
                );
                // opcional: loga o retorno
                @file_put_contents(
                    __DIR__ . '/utmify_dispatch.log',
                    '[' . date('Y-m-d H:i:s') . '] TX=' . $payment_id . ' RES=' . json_encode($res, JSON_UNESCAPED_UNICODE) . "\n",
                    FILE_APPEND
                );
            } catch (\Throwable $e) {
                @file_put_contents(
                    __DIR__ . '/utmify_dispatch.log',
                    '[' . date('Y-m-d H:i:s') . "] TX=$payment_id ERROR=" . $e->getMessage() . "\n",
                    FILE_APPEND
                );
            }
        } else {
            @file_put_contents(
                __DIR__ . '/utmify_dispatch.log',
                '[' . date('Y-m-d H:i:s') . "] TX=$payment_id add_utm() não encontrada\n",
                FILE_APPEND
            );
        }
    }
}

// resposta OK
echo json_encode([
    'success' => true,
    'transaction_id' => $txid,
    'status' => $status
]);



function add_utm($nome, $cpf, $email, $telefone, $valor, $utm_source, $utm_campaign, $utm_medium, $utm_content, $utm_term, $token, $utm_token)
{

    $apiUrl = 'https://api.utmify.com.br/api-credentials/orders';
    $apiToken = $utm_token;

    $amount = $valor; // em centavos
    $amount = number_format((float) str_replace(',', '.', $valor), 2, '.', '');

    $gatewayFee = 0;
    $userCommission = $amount - $gatewayFee;
    $amountCents = (int) preg_replace('/\D+/', '', (string) $amount);

    $createdAt = date('Y-m-d H:i:s');

    $telefone_limpo = preg_replace('/\D/', '', $telefone);
    $cpf_limpo = preg_replace('/\D/', '', $cpf);


    $payload = [
        "orderId" => rand(10000, 19999), // exemplo de token
        "platform" => "Pix",
        "paymentMethod" => "pix",
        "status" => "paid",
        "createdAt" => $createdAt,
        "approvedDate" => date("Y-m-d H:i:s"),
        "refundedAt" => null,
        "customer" => [
            "name" => "" . $nome . "",
            "email" => "" . $email . "",
            "phone" => "" . $telefone_limpo . "",
            "document" => "" . $cpf_limpo . "",
            "country" => "BR"
        ],
        "products" => [
            [
                "id" => "produto-externo",
                "name" => "Produto Externo",
                "planId" => 11,
                "planName" => 'externo',
                "quantity" => 1,
                "priceInCents" => $amount
            ]
        ],
        "trackingParameters" => [
            "utm_source" => "" . $utm_source . "",
            "utm_campaign" => "" . $utm_campaign . "",
            "utm_medium" => "" . $utm_medium . "",
            "utm_content" => "" . $utm_content . "",
            "utm_term" => "" . $utm_term . ""

        ],
        "commission" => [
            "totalPriceInCents" => $amountCents,
            "gatewayFeeInCents" => $gatewayFee,
            "userCommissionInCents" => $amountCents
        ],
        "isTest" => false
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'x-api-token: ' . $apiToken
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);

    //var_dump($response);

    if (curl_errno($ch)) {
        //echo 'Erro no cURL: ' . curl_error($ch);
    } else {
        //echo '✅ Resposta da UTMify:<br><pre>' . htmlentities($response) . '</pre>';
    }

    curl_close($ch);

}