<?php
// LOG DEBUG
$debug_trace = [];
function debug_log($msg)
{
  global $debug_trace;
  $logFile = __DIR__ . '/debug_pix.log';
  $time = date('Y-m-d H:i:s');
  if (!is_string($msg)) {
    $msg = json_encode($msg, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  }
  $line = "[$time] $msg";
  $debug_trace[] = $line;
  @file_put_contents($logFile, $line . PHP_EOL, FILE_APPEND);
}

debug_log("Script checkout-process.php (Paradise) iniciado.");

require '../config.php';
debug_log("Config.php incluido com sucesso.");

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

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
date_default_timezone_set('America/Sao_Paulo');

$metaKeys = [
  'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term',
  'campaign_id', 'adset_id', 'ad_id', 'placement', 'fbclid', 'gclid', 'msclkid', 'ttclid'
];

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

$PIX_DB_PATH = __DIR__ . '/dutty.json';

function db_append(array $row, ?string $path = null): bool
{
  global $PIX_DB_PATH;
  $path = $path ?: ($PIX_DB_PATH ?? (__DIR__ . '/dutty.json'));
  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)) {
    clearstatcache(true, $path);
    $size = filesize($path);
    rewind($fp);
    $json = $size > 0 ? fread($fp, $size) : '[]';
    $data = json_decode($json, true);
    if (!is_array($data)) $data = [];
    $data[] = $row;

    $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;
}

$meta = [];
foreach ($metaKeys as $k) {
  if (!empty($_SESSION[$k])) {
    $val = preg_replace('/[\x00-\x1F\x7F]/u', '', trim((string)$_SESSION[$k]));
    $meta[$k] = mb_substr($val, 0, 512);
  }
}
$meta['_meta_source'] = 'SESSION';

$input = json_decode(file_get_contents('php://input'), true);
$plate = trim((string)($input['plate'] ?? ''));
$total = (float)($input['total'] ?? 0);
$customerData = is_array($input['customerData'] ?? null) ? $input['customerData'] : [];

if ($total <= 0) {
  debug_log(["erro" => "Valor total inválido", "input" => $input]);
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Valor total inválido']);
  exit;
}

$priceCents = (int)round($total * 100);
if ($priceCents < 100) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'price_cents mínimo é 100 (R$ 1,00)']);
  exit;
}

$name = trim((string)($customerData['name'] ?? 'Cliente'));
$email = trim((string)($customerData['email'] ?? 'cliente@email.com'));
$cpf = preg_replace('/\D/', '', (string)($customerData['cpf'] ?? ''));
$phone = preg_replace('/\D/', '', (string)($customerData['phone'] ?? ''));

if ($name === '') $name = 'Cliente';
if ($email === '') $email = 'cliente@email.com';
if ($cpf === '') $cpf = str_pad((string)random_int(0, 99999999999), 11, '0', STR_PAD_LEFT);
if ($phone === '') $phone = '11999999999';

$lead = [
  'name' => $name,
  'email' => $email,
  'document' => $cpf,
  'phone' => $phone,
];

$data = [
  'method' => 'pix',
  'lead' => $lead,
  'items' => [[
    'title' => 'Pagamento PIX - Placa ' . ($plate !== '' ? $plate : 'SEM-PLACA'),
    'price_cents' => $priceCents,
    'qty' => 1,
    'externalRef' => (string)random_int(1000, 999999),
  ]],
  'amounts' => ['total_cents' => $priceCents],
];

try {
  $tracking = [
    'utm_source' => $meta['utm_source'] ?? 'api',
    'utm_medium' => $meta['utm_medium'] ?? '',
    'utm_campaign' => $meta['utm_campaign'] ?? '',
    'utm_content' => $meta['utm_content'] ?? '',
    'utm_term' => $meta['utm_term'] ?? '',
  ];

  debug_log("Enviando para Paradise. Data: " . json_encode($data));
  $resp = paradise_create_transaction($paradise_secret, $data, $tracking);
  debug_log("Resposta Paradise: " . json_encode($resp));

  if (!is_array($resp)) {
    throw new Exception('Resposta inválida da Paradise');
  }
  if (isset($resp['status']) && strtolower((string)$resp['status']) === 'error') {
    throw new Exception($resp['message'] ?? 'Erro desconhecido na Paradise');
  }

  $transactionId = $resp['transaction_id'] ?? null;
  $externalId = $resp['id'] ?? null;
  $emv = $resp['qr_code'] ?? null;
  $qrImg = $resp['qr_code_base64'] ?? null;
  if (is_string($qrImg) && strpos($qrImg, 'base64,') !== false) {
    $qrImg = trim(substr($qrImg, strpos($qrImg, 'base64,') + 7));
  }
  $expiresAt = $resp['expires_at'] ?? ($resp['expirationDate'] ?? null);
  $status = strtoupper((string)($resp['status'] ?? 'PENDING'));

  if (!$transactionId || !$emv) {
    throw new Exception('Resposta sem qr_code ou transaction_id: ' . json_encode($resp, JSON_UNESCAPED_UNICODE));
  }

  if (function_exists('add_utm') && isset($utmfy_token)) {
    try {
      add_utm($name, $cpf, $email, $phone, $priceCents,
        $tracking['utm_source'], $tracking['utm_campaign'], $tracking['utm_medium'],
        $tracking['utm_content'], $tracking['utm_term'], $transactionId, $utmfy_token);
    } catch (\Throwable $e) {
      @file_put_contents(__DIR__ . '/utmify_dispatch.log', '[' . date('Y-m-d H:i:s') . "] TX=$transactionId ERROR=" . $e->getMessage() . PHP_EOL, FILE_APPEND);
    }
  }

  db_append([
    'ts' => date('Y-m-d H:i:s'),
    'type' => 'success',
    'transactionId' => (string)$transactionId,
    'external_id' => $externalId,
    'valor_centavos' => $priceCents,
    'plate' => $plate,
    'lead' => $lead,
    'meta' => $meta,
    'resp' => $resp,
  ]);

  echo json_encode([
    'pixCode' => $emv,
    'transactionId' => (string)$transactionId,
    'transactionHash' => $externalId,
    'qrCodeBase64' => $qrImg,
    'amount' => $total,
    'status' => $status,
    'expiresAt' => $expiresAt,
  ]);
  exit;
} catch (Exception $e) {
  $errMsg = $e->getMessage();
  debug_log("EXCEPTION CATCH: $errMsg");
  db_append([
    'ts' => date('Y-m-d H:i:s'),
    'type' => 'error',
    'msg' => $errMsg,
    'price_cents' => $priceCents,
    'meta' => $meta,
    'payload_try' => $data ?? null,
  ]);

  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => $errMsg]);
  exit;
}

function paradise_create_transaction(string $secret_key, array $data, array $tracking = []): array
{
  if (!$secret_key) return ['error' => 'Chave da Paradise ausente'];

  $doc = isset($data['lead']['document']) ? preg_replace('/\D+/', '', (string)$data['lead']['document']) : '';
  $phone = isset($data['lead']['phone']) ? preg_replace('/\D+/', '', (string)$data['lead']['phone']) : '';

  $amount = (int)($data['amounts']['total_cents'] ?? ($data['items'][0]['price_cents'] ?? 0));
  $description = (string)($data['items'][0]['title'] ?? 'Compra');
  $reference = 'REF-' . uniqid();

  $payload = [
    'amount' => $amount,
    'description' => $description,
    'reference' => $reference,
    'productHash' => 'prod_11b85d7562452228',
    'customer' => [
      'name' => (string)($data['lead']['name'] ?? 'Cliente'),
      'email' => (string)($data['lead']['email'] ?? 'cliente@email.com'),
      'document' => $doc,
      'phone' => $phone,
    ],
    'tracking' => $tracking,
  ];

  $url = 'https://multi.paradisepags.com/api/v1/transaction.php';

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
    CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      'X-API-Key: ' . $secret_key,
    ],
    CURLOPT_TIMEOUT => 30,
    CURLOPT_CONNECTTIMEOUT => 10,
  ]);

  $response = curl_exec($ch);
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $err = curl_error($ch);
  curl_close($ch);

  if ($err) return ['error' => 'Erro de rede: ' . $err];

  $resp = json_decode((string)$response, true);
  if (!is_array($resp)) {
    return ['error' => 'Resposta inválida da Paradise (HTTP ' . $status . '): ' . $response];
  }

  if ($status < 200 || $status >= 300) {
    $msg = $resp['message'] ?? ($resp['error'] ?? ('Erro desconhecido HTTP ' . $status));
    return ['error' => is_string($msg) ? $msg : json_encode($msg, JSON_UNESCAPED_UNICODE)];
  }

  return $resp;
}
