<?php
require '../config.php';
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

define('PIX_DB_PATH', __DIR__ . '/dutty.json');
define('UTM_SENT_DIR', __DIR__ . '/utm_sent');

$paradise_secret = isset($paradise_secret_key) ? (string)$paradise_secret_key : (string)($token_payment ?? '');
if ($paradise_secret === '') {
  echo json_encode(['success' => false, 'status' => 'UNKNOWN', 'isPaid' => false, 'error' => 'Chave Paradise não configurada em checkout/config.php']);
  exit;
}

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

function map_status_for_front(?string $raw): string
{
  $raw = strtoupper(trim((string)$raw));
  if (in_array($raw, ['COMPLETED', 'PAID', 'APPROVED', 'SUCCEEDED', 'CONCLUDED', 'AUTHORIZED'], true)) return 'APPROVED';
  if (in_array($raw, ['PENDING', 'WAITING_PAYMENT', 'PENDING_PAYMENT'], true)) return 'PENDING';
  if (in_array($raw, ['REFUSED', 'DECLINED'], true)) return 'DECLINED';
  if (in_array($raw, ['CANCELED', 'CANCELLED'], true)) return 'CANCELLED';
  return $raw !== '' ? $raw : 'UNKNOWN';
}

function paradise_status(string $id, string $secret): array
{
  $action = 'get_transaction';
  $param = 'id';
  if (!ctype_digit((string)$id)) {
    $action = 'list_transactions';
    $param = 'external_id';
  }

  $url = "https://multi.paradisepags.com/api/v1/query.php?action={$action}&{$param}=" . rawurlencode($id);

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_HTTPGET => true,
    CURLOPT_HTTPHEADER => [
      'Accept: application/json',
      'X-API-Key: ' . $secret,
    ],
  ]);
  $res = curl_exec($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $err = curl_error($ch);
  curl_close($ch);

  if ($err) return ['error' => 'Erro de rede: ' . $err, '_http' => $code];
  $json = json_decode((string)$res, true);
  if ($action === 'list_transactions' && is_array($json) && isset($json[0])) return $json[0];
  if (!is_array($json)) $json = ['error' => 'Resposta inválida: ' . $res, '_http' => $code];
  if ($code < 200 || $code >= 300) {
    if (!isset($json['error'])) $json['error'] = 'HTTP ' . $code;
    $json['_http'] = $code;
  }
  return $json;
}

function find_db_row_by_tx(string $id): ?array
{
  $db = load_db(PIX_DB_PATH);
  for ($i = count($db) - 1; $i >= 0; $i--) {
    $row = $db[$i];
    if (!is_array($row)) continue;
    $txRow = (string)($row['transactionId'] ?? '');
    $txExt = (string)($row['external_id'] ?? '');
    $txResp = '';
    if (isset($row['resp']) && is_array($row['resp'])) {
      $txResp = (string)($row['resp']['id'] ?? ($row['resp']['transaction_id'] ?? ''));
    }
    if ($txRow === $id || $txExt === $id || $txResp === $id) return $row;
  }
  return null;
}

function maybe_dispatch_utm(string $txId, ?array $row, ?string $utmfy_token): void
{
  if (!$row || !$utmfy_token) return;
  if (!is_dir(UTM_SENT_DIR)) @mkdir(UTM_SENT_DIR, 0775, true);
  $flag = UTM_SENT_DIR . '/' . preg_replace('/[^A-Za-z0-9]/', '_', $txId) . '.ok';
  if (file_exists($flag)) return;

  $lead = $row['lead'] ?? [];
  $meta = $row['meta'] ?? [];

  $payload = [
    'orderId' => 'CH-' . $txId,
    'platform' => 'Pix',
    'paymentMethod' => 'pix',
    'status' => 'paid',
    'createdAt' => date('Y-m-d H:i:s'),
    'approvedDate' => date('Y-m-d H:i:s'),
    'customer' => [
      'name' => $lead['name'] ?? '',
      'email' => $lead['email'] ?? '',
      'phone' => preg_replace('/\D/', '', (string)($lead['phone'] ?? '')),
      'document' => preg_replace('/\D/', '', (string)($lead['document'] ?? '')),
      'country' => 'BR',
    ],
    'products' => [[
      'id' => 'prod-paid',
      'name' => 'Checkout Pago',
      'quantity' => 1,
      'priceInCents' => (int)($row['valor_centavos'] ?? 0),
    ]],
    'trackingParameters' => [
      'utm_source' => $meta['utm_source'] ?? null,
      'utm_campaign' => $meta['utm_campaign'] ?? null,
      'utm_medium' => $meta['utm_medium'] ?? null,
      'utm_content' => $meta['utm_content'] ?? null,
      'utm_term' => $meta['utm_term'] ?? null,
    ],
    'isTest' => false,
  ];

  $ch = curl_init('https://api.utmify.com.br/api-credentials/orders');
  curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'x-api-token: ' . $utmfy_token],
    CURLOPT_POSTFIELDS => json_encode($payload),
  ]);
  curl_exec($ch);
  curl_close($ch);
  @file_put_contents($flag, date('c'));
}

$id = isset($_GET['id']) ? trim((string)$_GET['id']) : (isset($_GET['transactionId']) ? trim((string)$_GET['transactionId']) : '');
if ($id === '') {
  http_response_code(400);
  echo json_encode(['success' => false, 'error' => 'Parâmetro id vazio']);
  exit;
}

$api = paradise_status($id, $paradise_secret);
if (isset($api['error'])) {
  $fallback = find_db_row_by_tx($id);
  if ($fallback) {
    $raw = (string)($fallback['status'] ?? ($fallback['resp']['status'] ?? 'PENDING'));
    $mapped = map_status_for_front($raw);
    echo json_encode([
      'success' => true,
      'status' => $mapped,
      'isPaid' => $mapped === 'APPROVED',
      'transaction_id' => $id,
      'paid_at' => null,
      'source' => 'cache',
    ]);
    exit;
  }
  echo json_encode(['success' => false, 'status' => 'UNKNOWN', 'isPaid' => false, 'error' => $api['error']]);
  exit;
}

$raw = (string)($api['status'] ?? '');
$mapped = map_status_for_front($raw);
$isPaid = ($mapped === 'APPROVED');

if ($isPaid) {
  $row = find_db_row_by_tx($id);
  if (isset($utmfy_token)) maybe_dispatch_utm($id, $row, $utmfy_token);
}

echo json_encode([
  'success' => true,
  'status' => $mapped,
  'isPaid' => $isPaid,
  'transaction_id' => $id,
  'paid_at' => $api['updated_at'] ?? null,
]);
