<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';
require_once BASE_PATH . '/api/shared/ApiLoader.php'; // Incluir el autoloader de API
if (!isset($_SESSION['client_id'])) { header('Location: ' . module_url('client_portal/login.php')); exit(); }

$page_title = 'Depósito';
$module = 'transactions';
$action = 'deposit';

$clientId = (int)$_SESSION['client_id'];
$db = Database::getInstance();
$pdo = $db->getConnection();

// Usar la nueva clase API para verificar configuración de Big4pay
$big4payClient = ApiLoader::getBig4payClient($pdo);
$big4payEnabled = $big4payClient->isConfigured();

$stmtAcc = $pdo->prepare("SELECT id, account_number, currency, account_type, balance FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at ASC");
$stmtAcc->execute([$clientId]);
$accounts = $stmtAcc->fetchAll();

$message = null; $error = null;

$stmtCliInit = $pdo->prepare("SELECT first_name,last_name,email,phone FROM clients WHERE id=? LIMIT 1");
$stmtCliInit->execute([$clientId]);
$rowInit = $stmtCliInit->fetch();
$firstInit = $rowInit['first_name'] ?? '';
$lastInit = $rowInit['last_name'] ?? '';
$emailInit = $rowInit['email'] ?? '';
$phoneInit = $rowInit['phone'] ?? '';
$countryIsoInit = '';
try { $stpInit = $pdo->prepare('SELECT country FROM client_profiles WHERE client_id=? LIMIT 1'); $stpInit->execute([$clientId]); if ($rp=$stpInit->fetch()) { if (!$countryIsoInit && !empty($rp['country'])) { $countryIsoInit = strtoupper($rp['country']); } } } catch (Throwable $__){ }
if ($phoneInit) { $phoneInit = preg_replace('/\D+/', '', (string)$phoneInit); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $accountId = (int)($_POST['account_id'] ?? 0);
    $amount = (float)($_POST['amount'] ?? 0);
    $method = trim($_POST['method'] ?? '');

    if ($accountId <= 0 || $amount <= 0) {
        $error = 'Selecciona una cuenta y un monto válido.';
    } elseif ($method === '') {
        $error = 'Selecciona un método de pago.';
    } else {
        $methodKey = strtolower($method);
        $knownMethods = ['key2pay','big4pay'];
        if (!in_array($methodKey, $knownMethods, true)) {
            $error = 'Método de pago no válido.';
        } else {
        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN checkout_redirect_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
        try {
            $stmtRed = $pdo->prepare("SELECT checkout_redirect_url FROM payment_methods WHERE provider_key = ? LIMIT 1");
            $stmtRed->execute([$methodKey]);
                if ($pmRow = $stmtRed->fetch()) {
                $redir = trim($pmRow['checkout_redirect_url'] ?? '');
                if ($methodKey === 'key2pay') {
                    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                    $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
                    $rootPath = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/');
                    $redir = $origin . $rootPath . '/modules/checkout/' . $methodKey . '/index.php';
                }
                if ($redir === '') {
                    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                    $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
                    $rootPath = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/');
                    $redir = $origin . $rootPath . '/modules/checkout/' . $methodKey . '/index.php';
                }
                if ($redir !== '') {
                    $stmtOne = $pdo->prepare("SELECT account_number, currency FROM client_accounts WHERE id = ? AND client_id = ? LIMIT 1");
                    $stmtOne->execute([$accountId, $clientId]);
                    $accRow = $stmtOne->fetch();
                    $currencyRed = $accRow ? ($accRow['currency'] ?? 'USD') : 'USD';
                    $accNumRed = $accRow ? ($accRow['account_number'] ?? '') : '';
                    $sep = (strpos($redir, '?') !== false) ? '&' : '?';
                    $payload = $clientId . '|' . $accNumRed . '|' . (time()+600);
                    $sig = hash_hmac('sha256', $payload, APP_SECRET);
                    $sso = rtrim(strtr(base64_encode($payload.'|'.$sig), '+/', '-_'), '=');
                    $to = $redir . $sep . 'amount=' . urlencode((string)$amount) . '&currency=' . urlencode((string)$currencyRed) . '&client_id=' . urlencode((string)$clientId) . '&account_number=' . urlencode((string)$accNumRed) . '&provider=' . urlencode((string)$methodKey) . '&sso=' . urlencode($sso);
                    header('Location: ' . $to);
                    exit;
                }
            }
        } catch (Throwable $__) {}
        // Si no hay URL de checkout configurada y el método no es key2pay, no ejecutar APIs: mostrar diagnóstico
        if ($methodKey !== 'key2pay') {
            $diag = [ 'method'=>$methodKey, 'account_id'=>$accountId, 'amount'=>$amount, 'client_id'=>$clientId ];
            $error = 'Checkout no configurado para ' . strtoupper($methodKey) . '. Define Checkout URL en Payment Methods. ' . json_encode($diag);
        }
        $client = ApiLoader::getIntegrationClient($methodKey, $pdo);

        if (false) {
            if ($methodKey === 'big4pay' && !$big4payEnabled) {
                $error = 'Big4pay no está configurado. Configura usuario y contraseña en Integraciones.';
            } else {
                $stmtOne = $pdo->prepare("SELECT id, account_number, currency FROM client_accounts WHERE id = ? AND client_id = ? LIMIT 1");
                $stmtOne->execute([$accountId, $clientId]);
                $acc = $stmtOne->fetch();
                if (!$acc) {
                    $error = 'Cuenta no encontrada.';
                } else {
                    $currency = $acc['currency'] ?? 'USD';
                    $stmtCli = $pdo->prepare("SELECT first_name, last_name, email, phone FROM clients WHERE id = ? LIMIT 1");
                    $stmtCli->execute([$clientId]);
                    $clientRow = $stmtCli->fetch();
                    $firstName = $clientRow['first_name'] ?? 'Cliente';
                    $lastName = $clientRow['last_name'] ?? '';
                    $email = $clientRow['email'] ?? '';
                    $mobile = $clientRow['phone'] ?? '';

                        if ($methodKey === 'key2pay' || $methodKey === 'big4pay') {
                            $currency = $acc['currency'] ?? 'USD';
                            $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                            $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
                            $rootPath = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/');
                            $to = $origin . $rootPath . '/modules/checkout/' . $methodKey . '/index.php'
                                . '&amount=' . urlencode((string)$amount)
                                . '&currency=' . urlencode((string)$currency)
                                . '&client_id=' . urlencode((string)$clientId)
                                . '&account_number=' . urlencode((string)($acc['account_number'] ?? ''));
                            header('Location: ' . $to);
                            exit;
                        }
                        $raw = (method_exists($client, 'createAccessTokenRaw') ? $client->createAccessTokenRaw() : ['success' => true, 'authorization' => null, 'json' => []]);
                    if (!$raw['success']) {
                        $error = 'Error autenticando con ' . ucfirst($methodKey) . ': ' . ($raw['message'] ?? ('HTTP ' . ($raw['http_code'] ?? '')));
                    } else {
                        $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/' . $methodKey . '/ipn.php');
                            $successUrl = $successUrl ?: ($origin . $rootPath . '/modules/client_portal/big4pay_success.php');
                            $cancelUrl = $cancelUrl ?: ($origin . $rootPath . '/modules/client_portal/big4pay_cancel.php');
                        }

                        if ($methodKey === 'key2pay') {
                            $params = [
                                'currency' => $currency,
                                'amount' => (int)round($amount * 100),
                                'language' => 'ES',
                                'orderId' => $identifier,
                                'description' => 'Depósito de cliente',
                                'notificationUrl' => $ipnUrl,
                                'returnUrl' => $successUrl,
                                'cancelUrl' => $cancelUrl,
                                'customer' => [ 'FirstName'=>$firstName, 'LastName'=>$lastName, 'Email'=>$email, 'Mobile'=>$mobile ],
                                'client_id' => $clientId,
                                'account_number' => ($acc['account_number'] ?? null)
                            ];
                            $res = $client->createCheckoutPage($params);
                        } else {
                            $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' => 'http://yoursite.com/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) : null;
                        }

                        $_SESSION['pending_deposit'] = [
                            'account_id' => $accountId,
                            'amount' => $amount,
                            'identifier' => $identifier,
                            'access_token' => $token
                        ];

                    // Registrar intento en historial
                    $pdo->exec("CREATE TABLE IF NOT EXISTS payment_attempts (
                      id INT AUTO_INCREMENT PRIMARY KEY,
                      client_id INT NULL,
                      account_number VARCHAR(64) NULL,
                      method VARCHAR(64) NOT NULL,
                      identifier VARCHAR(64) NOT NULL,
                      amount DECIMAL(18,6) NOT NULL,
                      currency VARCHAR(8) NOT NULL,
                      status VARCHAR(32) NOT NULL,
                      external_transaction_id VARCHAR(128) NULL,
                      source VARCHAR(32) NOT NULL,
                      redirect_url VARCHAR(255) NULL,
                      checkout_url VARCHAR(255) NULL,
                      message TEXT NULL,
                      raw_json JSON NULL,
                      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                      updated_at DATETIME NULL,
                      UNIQUE KEY uniq_identifier (identifier)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                    $redirectUrl = null;
                    $checkoutUrl = ($res['json']['paymentPageUrl'] ?? $res['json']['paymentFormUrl'] ?? 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 $__) {}
                    $selPA = $pdo->prepare("SELECT id FROM payment_attempts WHERE identifier = ? LIMIT 1");
                    $selPA->execute([$identifier]);
                    $exist = $selPA->fetch(PDO::FETCH_ASSOC);
                    if ($exist) {
                        $updPA = $pdo->prepare("UPDATE payment_attempts SET client_id=?, account_number=?, method=?, amount=?, currency=?, status='initiated', source='client_portal', payment_method=?, channel=?, redirect_url=?, checkout_url=?, raw_json=?, updated_at=NOW() WHERE id=?");
                        $updPA->execute([$clientId, ($acc['account_number'] ?? ''), $methodKey, $amount, $currency, $pmLabel, $channel, $redirectUrl, $checkoutUrl, json_encode($res), (int)$exist['id']]);
                    } else {
                        $insPA = $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 (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                        $insPA->execute([$clientId, ($acc['account_number'] ?? ''), $methodKey, $identifier, $amount, $currency, 'initiated', 'client_portal', $pmLabel, $channel, $redirectUrl, $checkoutUrl, json_encode($res)]);
                    }

                        $redirectUrl = $redirectUrl;
                        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) {
                            header('Location: ' . $redirectUrl);
                            exit;
                        } else {
                            if ($methodKey === 'key2pay' && $checkoutUrl) { header('Location: ' . $checkoutUrl); exit; }
                            $error = 'No se recibió URL de checkout. ' . (isset($res['body']) ? (is_string($res['body']) ? $res['body'] : json_encode($res['body'])) : '');
                        }
                    }
                }
            }
        } else {
            $stmtOne = $pdo->prepare("SELECT id, account_number, currency, balance FROM client_accounts WHERE id = ? AND client_id = ? LIMIT 1");
            $stmtOne->execute([$accountId, $clientId]);
            $acc = $stmtOne->fetch();
            if (!$acc) { $error = 'Cuenta no encontrada.'; }
            else {
                $currency = $acc['currency'] ?? 'USD';
                // Registrar depósito local solo para métodos NO integrados (banco/cash)
                if (!in_array($methodKey, ['key2pay','big4pay'], true)) {
                    $pdo->beginTransaction();
                    try {
                        $stmtTx = $pdo->prepare("INSERT INTO client_transactions (client_id, type, amount, currency, reference, notes, created_at) VALUES (?,?,?,?,?, ?, NOW())");
                        $stmtTx->execute([$clientId, 'deposit', $amount, $currency, uniqid('DEP-'), $method]);
                        $stmtUp = $pdo->prepare("UPDATE client_accounts SET balance = balance + ? WHERE id = ?");
                        $stmtUp->execute([$amount, $accountId]);
                        if (!empty($acc['account_number'])) {
                            $stmtTa = $pdo->prepare("UPDATE trading_accounts SET balance = balance + ?, equity = equity + ?, free_margin = free_margin + ?, updated_at = NOW() WHERE client_id = ? AND account_number = ?");
                            $stmtTa->execute([$amount, $amount, $amount, $clientId, $acc['account_number']]);
                        }
                        $pdo->commit();
                        $message = 'Depósito registrado correctamente.';
                    } catch (Throwable $e) {
                        $pdo->rollBack();
                        $error = 'Error registrando el depósito.';
                    }
                }
            }
        }
        }
    }
}

ob_start();
?>
    <div class="section-header">
        <h2 class="section-title"><i class="fas fa-arrow-down"></i> Nuevo Depósito</h2>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
    <?php elseif ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <section class="support-card">
        <form method="post" class="ticket-form" id="cpDepositForm">
            <div class="form-grid" style="grid-template-columns: 1fr 1fr;">
                <div class="form-group">
                    <label for="account_id">Cuenta</label>
                    <select id="account_id" name="account_id" required>
                        <option value="">Selecciona una cuenta</option>
                        <?php foreach ($accounts as $a): ?>
                            <option value="<?php echo (int)$a['id']; ?>" <?php echo ((int)($_GET['account_id'] ?? 0) === (int)$a['id']) ? 'selected' : ''; ?>>
                                <?php echo strtoupper($a['currency']) . ' · #' . htmlspecialchars($a['account_number']) . ' · ' . ucfirst($a['account_type']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="amount">Monto</label>
                    <input type="number" id="amount" name="amount" step="0.01" min="0.01" required />
                    <small id="depositInlineMsg" class="inline-error" style="display:none"></small>
                </div>
                
                <div class="form-group" id="methodGroup" style="display:none; grid-column: 1 / -1;">
                    <label>Método</label>
                    <div class="method-tiles" id="cpDepositMethods">
                        <?php
                        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN checkout_redirect_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
                        $pmStmt = $pdo->prepare("SELECT provider_key, display_name, logo_path, supported_currencies, checkout_redirect_url FROM payment_methods WHERE is_active = 1 AND (type='deposit' OR type='both') ORDER BY id ASC");
                        $pmStmt->execute();
                        $pmRows = $pmStmt->fetchAll(PDO::FETCH_ASSOC);
                        if (!$pmRows) {
                            echo '<div class="alert alert-info">No hay métodos de pago activos.</div>';
                        } else {
                            foreach ($pmRows as $m) {
                                $val = strtolower($m['provider_key'] ?: $m['display_name']);
                                $title = htmlspecialchars($m['display_name'] ?: $m['provider_key']);
                                $logo = $m['logo_path'] ? ((substr($m['logo_path'],0,1)==='/') ? (asset(ltrim($m['logo_path'],'/'))) : asset($m['logo_path'])) : null;
                                $currs = htmlspecialchars($m['supported_currencies'] ?? '');
                                $redirect = $m['checkout_redirect_url'] ?? null;
                                if (!$redirect && in_array($val, ['key2pay','big4pay'], true)) {
                                    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                                    $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
                                    $rootPath = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/');
                                    $redirect = $origin . $rootPath . '/modules/checkout/' . $val . '/index.php';
                                }
                                echo '<label class="method-tile" data-value="'.htmlspecialchars($val).'" data-currencies="'.$currs.'"'.($redirect?(' data-redirect="'.htmlspecialchars($redirect).'"'):'').'>'; 
                                echo '<input class="method-input" type="radio" name="method" value="'.htmlspecialchars($val).'">';
                                if ($logo) {
                                    echo '<img class="method-logo" src="'.htmlspecialchars($logo).'" alt="'. $title .'"/>';
                                } else {
                                    echo '<i class="fas fa-credit-card"></i>';
                                }
                                echo '<span>'. $title .'</span>';
                                echo '</label>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
            <div class="form-actions">
                <button class="client-action-btn deposit" id="depositSubmitBtn" type="submit"><i class="fas fa-arrow-down"></i> Depositar</button>
                <a class="client-action-btn secondary" href="<?php echo module_url('client_portal/dashboard.php'); ?>">Cancelar</a>
            </div>
        </form>
    </section>
    <script>
    (function(){
      const sel = document.getElementById('account_id');
      const methodGroup = document.getElementById('methodGroup');
      const tiles = document.querySelectorAll('#cpDepositMethods .method-tile');
      const inputs = document.querySelectorAll('#cpDepositMethods .method-input');
      const form = document.getElementById('cpDepositForm');
      function updateSteps(){
        const hasAcc = !!sel.value;
        methodGroup.style.display = hasAcc ? '' : 'none';
        if (hasAcc) {
          const opt = sel.options[sel.selectedIndex];
          const text = opt ? opt.text : '';
          const cur = (text.match(/^[A-Z]{3}/) || ['USD'])[0];
          const amt = document.getElementById('amount');
          if (amt) { amt.placeholder = '0.00 ' + cur; }
          // Filtrar métodos por moneda
          tiles.forEach(t => {
            const cs = (t.getAttribute('data-currencies') || '').toUpperCase();
            const supportsAll = cs === '';
            const ok = supportsAll || cs.indexOf(cur) !== -1;
            t.style.display = ok ? '' : 'none';
            const inp = t.querySelector('.method-input');
            if (!ok && inp) inp.checked = false;
            if (!ok) t.classList.remove('selected');
            let chip = t.querySelector('.method-chip');
            if (!chip) {
              chip = document.createElement('span');
              chip.className = 'method-chip';
              t.appendChild(chip);
            }
            chip.textContent = cur;
          });
        }
        updateDepositBtnState();
      }
      sel.addEventListener('change', updateSteps);
      updateSteps();
      tiles.forEach(t=>{
        t.addEventListener('click', ()=>{
          tiles.forEach(x=>x.classList.remove('selected'));
          t.classList.add('selected');
          const inp = t.querySelector('.method-input');
          if (inp) inp.checked = true;
          // no abrir checkout en selección; requiere click en "Depositar"
          updateDepositBtnState();
        });
      });
      inputs.forEach(inp=>{
        inp.addEventListener('change', ()=>{
          tiles.forEach(x=>x.classList.remove('selected'));
          const lab = inp.closest('.method-tile');
          if (lab) lab.classList.add('selected');
          // no abrir en change; esperar al submit explícito
          updateDepositBtnState();
        });
      });
      const amtElListen = document.getElementById('amount');
      if (amtElListen) amtElListen.addEventListener('input', updateDepositBtnState);
      if (form) {
        form.addEventListener('submit', (e)=>{
          const checked = document.querySelector('#cpDepositMethods .method-input:checked');
          const val = (checked ? checked.value : '').toLowerCase();
          const lab = checked ? checked.closest('.method-tile') : null;
          const redirect = lab ? (lab.getAttribute('data-redirect')||'') : '';
            e.preventDefault();
            const amtEl = document.getElementById('amount');
            const amt = parseFloat(amtEl ? amtEl.value || '0' : '0');
            const opt = sel.options[sel.selectedIndex];
            const text = opt ? opt.text : '';
            const cur = (text.match(/^[A-Z]{3}/) || ['USD'])[0];
            const accNum = text.replace(/^\w{3}\s·\s#([^\s]+).*/, '$1');
            if (Number.isFinite(amt) && amt > 0) {
              const base = redirect || (location.origin + (location.pathname.indexOf('/simple_crm/')!==-1?'/simple_crm':'') + '/modules/checkout/' + val + '/index.php');
              const url = base + (base.indexOf('?')!==-1?'&':'?') + 'amount=' + encodeURIComponent(String(amt)) + '&currency=' + encodeURIComponent(cur) + '&client_id=' + encodeURIComponent('<?php echo (int)$clientId; ?>') + '&account_number=' + encodeURIComponent(accNum) + '&provider=' + encodeURIComponent(val) + '&first_name=' + encodeURIComponent('<?php echo htmlspecialchars($firstInit, ENT_QUOTES); ?>') + '&last_name=' + encodeURIComponent('<?php echo htmlspecialchars($lastInit, ENT_QUOTES); ?>') + '&email=' + encodeURIComponent('<?php echo htmlspecialchars($emailInit, ENT_QUOTES); ?>') + '&phone=' + encodeURIComponent('<?php echo htmlspecialchars($phoneInit, ENT_QUOTES); ?>') + '&mobile=' + encodeURIComponent('<?php echo htmlspecialchars($phoneInit, ENT_QUOTES); ?>') + '&country=' + encodeURIComponent('<?php echo htmlspecialchars($countryIsoInit, ENT_QUOTES); ?>');
              window.open(url, '_blank', 'noopener');
            }
        })
      }
      function updateDepositBtnState(){
        const btn = document.getElementById('depositSubmitBtn');
        if (!btn) return;
        const checked = document.querySelector('#cpDepositMethods .method-input:checked');
        const amtEl = document.getElementById('amount');
        const amt = parseFloat(amtEl ? (amtEl.value||'0') : '0');
        const ok = !!checked && Number.isFinite(amt) && amt > 0;
        btn.disabled = !ok;
        const msgEl = document.getElementById('depositInlineMsg');
        if (msgEl) {
          if (!ok) {
            let msg = '';
            if (!checked) msg = 'Selecciona un método.';
            else if (!Number.isFinite(amt) || amt<=0) msg = 'Monto inválido.';
            msgEl.textContent = msg;
            msgEl.style.display = 'block';
          } else { msgEl.textContent = ''; msgEl.style.display = 'none'; }
        }
      }
    })();
    </script>
    <style>
      .method-tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:12px}
      .method-tile{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;background:linear-gradient(180deg,#ffffff,#f6f8fb);border:1px solid #e2e8f0;border-radius:16px;padding:10px;height:100px;cursor:pointer;user-select:none;transition:transform .12s ease, box-shadow .18s ease, border-color .18s ease}
      .method-tile:hover{transform:translateY(-1px);box-shadow:0 10px 22px rgba(0,0,0,.08)}
      .method-input{display:none}
      .method-tile.selected{border-color:#2ea6ff;box-shadow:0 0 0 2px rgba(46,166,255,.30);background:linear-gradient(180deg,#ffffff,#eef4ff)}
      .method-logo{max-width:100px;max-height:40px;object-fit:contain}
      .method-tile>span{display:none}
      .method-chip{align-self:flex-end;background:#e0f2fe;color:#0369a1;border:1px solid #93c5fd;border-radius:999px;padding:2px 8px;font-size:11px;font-weight:700}
      @media (max-width: 1024px){ .method-tiles{grid-template-columns:repeat(auto-fill, minmax(140px,1fr));} }
      @media (max-width: 640px){ .method-tiles{grid-template-columns:repeat(2, minmax(120px,1fr));} .method-card{height:90px} }
      .inline-error{font-size:12px;color:#d93025;margin-top:6px}
    </style>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
