<?php
session_start();
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';

$db = Database::getInstance();
$pdo = $db->getConnection();
$client = ApiLoader::getIntegrationClient('big4pay', $pdo);
$action = $_GET['action'] ?? $_POST['action'] ?? '';
header('Content-Type: application/json');

if (!$client) { echo json_encode(['success'=>false,'message'=>'Big4pay no configurado']); exit; }

try {
  if ($action === 'initiate_big4pay_checkout') {
    $currency = $_POST['currency'] ?? 'USD';
    $amount = (float)($_POST['amount'] ?? 0);
    $clientId = isset($_POST['client_id']) ? (int)$_POST['client_id'] : null;
    $accountNumber = $_POST['account_number'] ?? null;

    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $rootPath = rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/');
    $ipnUrl = $origin . $rootPath . '/api/payment_method/big4pay/ipn.php';
    $successUrl = $origin . $rootPath . '/modules/client_portal/big4pay_success.php';
    $cancelUrl = $origin . $rootPath . '/modules/client_portal/big4pay_cancel.php';

    $raw = method_exists($client, 'createAccessTokenRaw') ? $client->createAccessTokenRaw() : ['success'=>false,'message'=>'Método createAccessTokenRaw no disponible'];
    if (!$raw['success']) { echo json_encode(['success'=>false,'message'=>$raw['message'] ?? 'No se pudo autenticar']); exit; }
    $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_');
    $firstName = $_SESSION['first_name'] ?? 'Cliente';
    $lastName = $_SESSION['last_name'] ?? '';
    $email = $_SESSION['email'] ?? 'demo@example.com';
    $mobile = $_SESSION['mobile'] ?? '';
    if ($clientId && (!$email || !$firstName)) {
      try { $st=$pdo->prepare("SELECT first_name,last_name,email,phone FROM clients WHERE id=? LIMIT 1"); $st->execute([$clientId]); if ($row=$st->fetch()) { $firstName=$firstName?:($row['first_name']??'Cliente'); $lastName=$lastName?:($row['last_name']??''); $email=$email?:($row['email']??'demo@example.com'); $mobile=$mobile?:($row['phone']??''); } } catch(Throwable $__){ }
    }

    $params = [
      'access_token' => $token,
      'identifier' => $identifier,
      'currency' => $currency,
      'amount' => $amount,
      'language' => 'ES',
      'description' => 'Depósito de cliente',
      'details' => 'deposit transactions',
      'ipn_url' => $ipnUrl,
      'success_url' => $successUrl,
      'cancel_url' => $cancelUrl,
      'site_name' => 'IAttrade',
      'site_logo' => $origin . '/logo.png',
      'checkout_theme' => 'light',
      'customer' => [ 'first_name'=>$firstName, 'last_name'=>$lastName, 'country'=>($currency==='MXN'?'MX':'US'), 'email'=>$email, 'mobile'=>$mobile ]
    ];
    $res = method_exists($client, 'initiatePayment') ? $client->initiatePayment($params) : ['success'=>false,'message'=>'Método initiatePayment no disponible'];
    echo json_encode($res);
    exit;
  }
  echo json_encode(['success'=>false,'message'=>'Acción inválida']);
} catch (Throwable $e) {
  echo json_encode(['success'=>false,'message'=>'Error: '.$e->getMessage()]);
}
