<?php
session_start();
header('Content-Type: application/json');
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/api/shared/ApiLoader.php';

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $method = strtolower(trim($_POST['method'] ?? ''));
  $amount = (float)($_POST['amount'] ?? 0);
  $currency = strtoupper(trim($_POST['currency'] ?? 'USD'));
  $accountNumber = trim($_POST['account_number'] ?? '');
  $countrySel = strtoupper(trim($_POST['country'] ?? ''));
  $allowedCountries = ['US','MX','AR','BR','CL','CO','PE','EC','BO','UY'];
  if (!in_array($countrySel, $allowedCountries, true)) { $countrySel = ($currency === 'MXN') ? 'MX' : 'US'; }
  if ($amount <= 0) { throw new Exception('Monto inválido'); }
  // Redirección directa al checkout configurado si existe
  $redirConf = null;
  try {
    $st = $pdo->prepare("SELECT checkout_redirect_url FROM payment_methods WHERE provider_key = ? AND is_active = 1 AND (type='deposit' OR type='both') ORDER BY id DESC LIMIT 1");
    $st->execute([$method]);
    if ($row = $st->fetch()) { $redirConf = trim($row['checkout_redirect_url'] ?? ''); }
  } catch (Throwable $__) {}
  $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
  $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
  $rootBase = $origin . rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/');
  if ($redirConf === '' && in_array($method, ['key2pay','big4pay'], true)) { $redirConf = $rootBase . '/modules/checkout/' . $method . '/index.php'; }
  if ($redirConf !== '') {
    $sep = (strpos($redirConf, '?') !== false) ? '&' : '?';
    $to = $redirConf . $sep . 'amount=' . urlencode((string)$amount) . '&currency=' . urlencode((string)$currency) . '&client_id=' . urlencode((string)$clientId) . '&account_number=' . urlencode((string)$accountNumber) . '&provider=' . urlencode((string)$method);
    echo json_encode(['success' => true, 'redirect_url' => $to]);
    return;
  }

  $client = ApiLoader::getIntegrationClient($method, $pdo);
  if (!$client) { throw new Exception('Método no soportado'); }

  // Obtener datos del cliente si están en sesión (client portal)
  $clientId = isset($_SESSION['client_id']) ? (int)$_SESSION['client_id'] : 0;
  $firstName = 'Cliente'; $lastName = ''; $email = ''; $mobile = '';
  if ($clientId > 0) {
    $stmtCli = $pdo->prepare("SELECT first_name, last_name, email, phone FROM clients WHERE id = ? LIMIT 1");
    $stmtCli->execute([$clientId]);
    if ($row = $stmtCli->fetch()) {
      $firstName = $row['first_name'] ?? $firstName;
      $lastName = $row['last_name'] ?? $lastName;
      $email = $row['email'] ?? $email;
      $mobile = $row['phone'] ?? $mobile;
    }
  }

  $raw = method_exists($client, 'createAccessTokenRaw') ? $client->createAccessTokenRaw() : ['success' => true, 'authorization' => null, 'json' => []];
  if (!$raw['success']) { throw new Exception($raw['message'] ?? ('HTTP ' . ($raw['http_code'] ?? ''))); }
  $token = $raw['authorization'] ?? ($raw['json']['access_token'] ?? null);
  if ($token && method_exists($client, 'saveAccessToken')) { $client->saveAccessToken($token); }

  $identifier = method_exists($client, 'generateIdentifier') ? $client->generateIdentifier() : uniqid('TRX_');
  $config = method_exists($client, 'getConfiguration') ? $client->getConfiguration() : [];
  $ipnUrl = $config['ipn_url'] ?? null;
  $successUrl = $config['success_url'] ?? null;
  $cancelUrl = $config['cancel_url'] ?? null;
  if (!$ipnUrl || !$successUrl || !$cancelUrl) {
    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $rootPath = rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/');
    $ipnUrl = $ipnUrl ?: ($origin . $rootPath . '/api/payment_method/' . $method . '/ipn.php');
    $successUrl = $successUrl ?: ($origin . $rootPath . '/modules/client_portal/big4pay_success.php');
    $cancelUrl = $cancelUrl ?: ($origin . $rootPath . '/modules/client_portal/big4pay_cancel.php');
  }

  $params = [
    'access_token' => $token,
    'identifier' => $identifier,
    'currency' => $currency,
    'amount' => $amount,
    'language' => 'ES',
    'description' => 'Depósito WebTrader',
    'details' => 'deposit transactions',
    'ipn_url' => $ipnUrl,
    'success_url' => $successUrl,
    'cancel_url' => $cancelUrl,
    'site_name' => 'IAttrade',
    'site_logo' => 'http://yoursite.com/logo.png',
    'checkout_theme' => 'light',
    'customer' => [
      'first_name' => $firstName,
      'last_name' => $lastName,
      'country' => ($countrySel ?: (($currency === 'MXN') ? 'MX' : 'US')),
      'email' => $email,
      'mobile' => $mobile
    ]
  ];
  $res = method_exists($client, 'initiatePayment') ? $client->initiatePayment($params) : null;

  // Guardar intento con estado initiated
  $redirectUrlTmp = null; $checkoutTmp = null;
  if (is_array($res)) {
    $jsonTmp = $res['json'] ?? null;
    if (is_array($jsonTmp)) { $redirectUrlTmp = $jsonTmp['redirect_url'] ?? $jsonTmp['payment_link'] ?? null; $checkoutTmp = $jsonTmp['checkout_url'] ?? null; }
  }
  // Detectar payment_method y channel desde la respuesta
  $pmLabel = null; $channel = null;
  if (is_array($res)) {
    $j = $res['json'] ?? [];
    if (!is_array($j) && isset($res['body']) && is_string($res['body'])) { $j = json_decode($res['body'], true) ?: []; }
    if (is_array($j)) {
      $pmLabel = $j['payment_method'] ?? ($j['paymentMethod'] ?? null);
      if (is_array($j['paymentMethod'] ?? null)) { $pmLabel = ($j['paymentMethod']['name'] ?? ($j['paymentMethod']['label'] ?? $pmLabel)); }
      if (is_array($j['payment'] ?? null)) {
        $pmLabel = $pmLabel ?: ($j['payment']['method_label'] ?? ($j['payment']['method'] ?? null));
        $channel = $j['payment']['channel'] ?? $channel;
      }
      if (is_array($j['paymentMethod'] ?? null)) { $channel = $channel ?: ($j['paymentMethod']['channel'] ?? null); }
      $channel = $channel ?: ($j['channel'] ?? ($j['category'] ?? null));
      if ($channel && !in_array(strtolower($channel), ['online','cash'])) { $channel = strtolower($channel)==='cash'?'cash':'online'; }
    }
  }
  // Asegurar columnas opcionales
  try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN payment_method VARCHAR(64) NULL"); } catch (Throwable $__) {}
  try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN channel VARCHAR(32) NULL"); } catch (Throwable $__) {}
  $ins = $pdo->prepare("INSERT INTO payment_attempts (client_id, account_number, method, identifier, amount, currency, status, source, payment_method, channel, redirect_url, checkout_url, raw_json) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
  $ins->execute([$clientId, $accountNumber, $method, $identifier, $amount, $currency, 'initiated', 'webtrader', $pmLabel, $channel, $redirectUrlTmp, $checkoutTmp, json_encode($res)]);

  $redirectUrl = null;
  if (is_array($res)) {
    $json = $res['json'] ?? null;
    if (is_array($json)) { $redirectUrl = $json['redirect_url'] ?? $json['checkout_url'] ?? $json['payment_link'] ?? null; }
    if (!$redirectUrl && isset($res['body']) && is_string($res['body'])) {
      $decoded = json_decode($res['body'], true);
      if (is_array($decoded)) { $redirectUrl = $decoded['redirect_url'] ?? $decoded['checkout_url'] ?? $decoded['payment_link'] ?? null; }
    }
  }
  if ($redirectUrl) { echo json_encode(['success' => true, 'redirect_url' => $redirectUrl]); }
  else { echo json_encode(['success' => false, 'message' => 'No se recibió URL de checkout', 'raw' => $res]); }
} catch (Throwable $e) {
  http_response_code(400);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
