<?php
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__ . '/..'); }
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/api/shared/ApiLoader.php';
header('Content-Type: application/json');
try {
    $pdo = Database::getInstance()->getConnection();
    $client = ApiLoader::getIntegrationClient('key2pay', $pdo);
    $payload = [
        'currency' => 'USD',
        'amount' => 50000,
        'language' => 'ES',
        'description' => 'Depósito CRM $500',
        'notificationUrl' => 'https://goldendragonexchange.com/api/key2pay/ipn',
        'returnUrl' => 'https://goldendragonexchange.com/portal/payment_success',
        'cancelUrl' => 'https://goldendragonexchange.com/portal/payment_cancel',
        'customer' => [ 'FirstName'=>'Carlos','LastName'=>'Mendoza','Email'=>'cliente.demo@example.com', 'Mobile'=>'+34666777888' ]
    ];
    $res = $client->createCheckoutPage($payload);
    $json = $res['json'] ?? [];
    $uid = $json['uid'] ?? null;
    $url = $json['checkoutUrl'] ?? $json['url'] ?? null;
    if (!$url && $uid) {
        $info = $client->getCheckoutPage($uid);
        $url = $info['json']['checkoutUrl'] ?? $info['json']['url'] ?? null;
        $res['info'] = $info;
    }
    echo json_encode([ 'success'=>$res['success'] ?? false, 'status'=>$res['http_code'] ?? null, 'uid'=>$uid, 'checkout_url'=>$url, 'json'=>$res['json'] ?? null ]);
} catch (Throwable $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
