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

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $action = $_GET['action'] ?? $_POST['action'] ?? '';
    $client = ApiLoader::getIntegrationClient('key2pay', $pdo);
    if (!$client) { echo json_encode(['success'=>false,'message'=>'Key2Pay no disponible']); exit; }

    if ($action === 'list_key2pay_methods') {
        $params = [];
        foreach (['channel','country','currency'] as $k) {
            if (isset($_GET[$k]) && $_GET[$k] !== '') { $params[$k] = $_GET[$k]; continue; }
            if (isset($_POST[$k]) && $_POST[$k] !== '') { $params[$k] = $_POST[$k]; }
        }
        // Auto-configurar Key2Pay desde credenciales de Big4pay si no está configurado
        if (!$client->isConfigured()) {
            try {
                $u = '';$p='';
                $selB = $pdo->prepare("SELECT api_username, api_password FROM payment_methods WHERE provider_key='big4pay' AND is_active=1 AND (type='deposit' OR type='both') ORDER BY id DESC LIMIT 1");
                $selB->execute(); if ($pmB = $selB->fetch()) { $u = $pmB['api_username'] ?? ''; $p = $pmB['api_password'] ?? ''; }
                if (!$u || !$p) {
                    $stmtB = $pdo->prepare("SELECT setting_key, setting_value FROM integration_settings WHERE integration_name='big4pay'");
                    $stmtB->execute(); while ($row = $stmtB->fetch()) { if ($row['setting_key']==='username'&& !$u) $u=$row['setting_value']; if ($row['setting_key']==='password'&& !$p) $p=$row['setting_value']; }
                }
                if ($u && $p) { $client->saveConfiguration('https://sandbox-api.key2pay.io/v1', $u, $p, null, []); }
            } catch (Throwable $__) {}
        }
        $res = $client->getPaymentMethods($params);
        $items = [];
        if (!empty($res['json']) && is_array($res['json'])) {
            $raw = $res['json'];
            $list = [];
            foreach (['items','paymentMethods','methods','data','results'] as $k) {
                if (isset($raw[$k]) && is_array($raw[$k])) { $list = $raw[$k]; break; }
            }
            if (!$list && is_array($raw)) { $list = $raw; }
            $items = array_map(function($x){
                return [
                    'uid' => $x['uid'] ?? ($x['id'] ?? null),
                    'name' => $x['name'] ?? ($x['displayName'] ?? ''),
                    'country' => $x['country'] ?? '',
                    'channel' => $x['channel'] ?? '',
                    'currencies' => $x['currencies'] ?? [],
                    'currencyLimits' => $x['currencyLimits'] ?? [],
                    'imageUrl' => $x['imageUrl'] ?? ($x['logoUrl'] ?? ($x['image'] ?? ($x['icon'] ?? ''))),
                ];
            }, $list);
        }
        echo json_encode(['success'=>true,'items'=>$items, 'http_code'=>$res['http_code'] ?? null]);
        exit;
    }

    if ($action === 'create_key2pay_checkout') {
        $currency = $_POST['currency'] ?? 'USD';
        $amountMinor = (int)($_POST['amount_minor'] ?? 0);
        $orderId = $_POST['order_id'] ?? ('ORD_' . time());
        $desc = $_POST['description'] ?? 'Deposit';
        $lang = $_POST['language'] ?? 'EN';
        $clientId = isset($_POST['client_id']) ? (int)$_POST['client_id'] : null;
        $accountNumber = $_POST['account_number'] ?? null;
        $ipnUrl = ($_SERVER['HTTP_ORIGIN'] ?? ('http://' . $_SERVER['HTTP_HOST'])) . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/api/payment_method/key2pay/ipn.php';
        $returnUrl = ($_SERVER['HTTP_ORIGIN'] ?? ('http://' . $_SERVER['HTTP_HOST'])) . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/modules/client_portal/payment_success.php';
        $cancelUrl = ($_SERVER['HTTP_ORIGIN'] ?? ('http://' . $_SERVER['HTTP_HOST'])) . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/modules/client_portal/payment_cancel.php';
        $firstName = $_SESSION['first_name'] ?? null;
        $lastName = $_SESSION['last_name'] ?? null;
        $email = $_SESSION['email'] ?? null;
        $mobile = $_SESSION['mobile'] ?? null;
        if ((!$firstName || !$email) && $clientId) {
            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'] ?? ''); $mobile = $mobile ?: ($row['phone'] ?? ''); }
            } catch (Throwable $__) {}
        }
        $res = $client->createCheckoutPage([
            'currency' => $currency,
            'amount' => $amountMinor,
            'language' => $lang,
            'orderId' => $orderId,
            'description' => $desc,
            'notificationUrl' => $ipnUrl,
            'returnUrl' => $returnUrl,
            'cancelUrl' => $cancelUrl,
            'customer' => [ 'FirstName'=>$firstName ?: 'Cliente', 'LastName'=>$lastName ?: 'CRM', 'Email'=>$email ?: 'demo@example.com', 'Mobile'=>$mobile ?: '' ],
            'client_id' => $clientId,
            'account_number' => $accountNumber
        ]);
        echo json_encode($res);
        exit;
    }

    echo json_encode(['success'=>false,'message'=>'Acción inválida']);
} catch (Throwable $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
