<?php
$bold = is_array($bold ?? null) ? $bold : [];
$credibanco = is_array($credibanco ?? null) ? $credibanco : [];

$boldEnabled = trim((string) old('bold_enabled', (bool) ($bold['enabled'] ?? false) ? '1' : '0')) === '1';
$boldMode = strtolower(trim((string) old('bold_mode', (string) ($bold['mode'] ?? 'dataphone'))));
$forcedOpenBoldMode = strtolower(trim((string) (flash('integraciones_bold_open_mode') ?? '')));
if (in_array($forcedOpenBoldMode, ['dataphone', 'button'], true)) {
    $boldMode = $forcedOpenBoldMode;
}
if (!in_array($boldMode, ['dataphone', 'button'], true)) {
    $boldMode = 'dataphone';
}
$boldModeLabel = $boldMode === 'button' ? 'Botón de pagos' : 'API datáfono';
$boldApiUrl = trim((string) old('bold_api_url', (string) ($bold['api_url'] ?? '')));
$boldApiKeyInput = trim((string) old('bold_api_key', ''));
$boldHasApiKey = (bool) ($bold['has_api_key'] ?? false);
$boldApiKeyPreview = trim((string) ($bold['api_key_preview'] ?? ''));
$boldButtonCheckoutUrl = trim((string) old('bold_button_checkout_url', (string) ($bold['button_checkout_url'] ?? 'https://checkout.bold.co')));
if ($boldButtonCheckoutUrl === '') {
    $boldButtonCheckoutUrl = 'https://checkout.bold.co';
}
$boldButtonPublicKeyInput = trim((string) old('bold_button_public_key', ''));
$boldButtonSecretKeyInput = trim((string) old('bold_button_secret_key', ''));
$boldHasButtonPublicKey = (bool) ($bold['has_button_public_key'] ?? false);
$boldHasButtonSecretKey = (bool) ($bold['has_button_secret_key'] ?? false);
$boldButtonPublicKeyPreview = trim((string) ($bold['button_public_key_preview'] ?? ''));
$boldButtonSecretKeyPreview = trim((string) ($bold['button_secret_key_preview'] ?? ''));
$boldConfigured = (bool) ($bold['is_configured'] ?? false);
$boldDataphoneConfigured = (bool) ($bold['is_dataphone_configured'] ?? false);
$boldButtonConfigured = (bool) ($bold['is_button_configured'] ?? false);
$boldMethodActive = (bool) ($bold['method_active'] ?? false);
$boldDataphoneMethodActive = (bool) ($bold['method_active_dataphone'] ?? false);
$boldButtonMethodActive = (bool) ($bold['method_active_button'] ?? false);
$boldDataphoneActive = $boldDataphoneMethodActive;
$boldButtonActive = $boldButtonMethodActive;
$boldDataphoneMethodAvailable = $boldDataphoneConfigured && $boldDataphoneMethodActive;
$boldButtonMethodAvailable = $boldButtonConfigured && $boldButtonMethodActive;

$buttonTestAmountType = strtolower(trim((string) old('bold_button_test_amount_type', 'close')));
if (!in_array($buttonTestAmountType, ['close', 'open'], true)) {
    $buttonTestAmountType = 'close';
}
$buttonTestAmount = trim((string) old('bold_button_test_amount', '10000'));
$buttonTestCurrency = strtoupper(trim((string) old('bold_button_test_currency', 'COP')));
if ($buttonTestCurrency === '') {
    $buttonTestCurrency = 'COP';
}
$buttonTestReference = trim((string) old('bold_button_test_reference', ''));
$buttonTestDescription = trim((string) old('bold_button_test_description', 'Pago de prueba Veltrix POS'));
$buttonGeneratedUrl = trim((string) old('bold_button_generated_url', ''));
$buttonGeneratedPaymentLink = trim((string) old('bold_button_generated_payment_link', ''));

$credibancoEnabled = trim((string) old('credibanco_enabled', (bool) ($credibanco['enabled'] ?? false) ? '1' : '0')) === '1';
$credibancoApiUrl = trim((string) old('credibanco_api_url', (string) ($credibanco['api_url'] ?? '')));
$credibancoTokenUrl = trim((string) old('credibanco_token_url', (string) ($credibanco['token_url'] ?? '')));
$credibancoClientIdInput = trim((string) old('credibanco_client_id', ''));
$credibancoClientSecretInput = trim((string) old('credibanco_client_secret', ''));
$credibancoHasClientId = (bool) ($credibanco['has_client_id'] ?? false);
$credibancoClientIdPreview = trim((string) ($credibanco['client_id_preview'] ?? ''));
$credibancoHasClientSecret = (bool) ($credibanco['has_client_secret'] ?? false);
$credibancoClientSecretPreview = trim((string) ($credibanco['client_secret_preview'] ?? ''));
$credibancoEventsSecretInput = trim((string) old('credibanco_events_secret', ''));
$credibancoHasEventsSecret = (bool) ($credibanco['has_events_secret'] ?? false);
$credibancoEventsSecretPreview = trim((string) ($credibanco['events_secret_preview'] ?? ''));
$credibancoConfigured = (bool) ($credibanco['is_configured'] ?? false);
$credibancoMethodActive = (bool) ($credibanco['method_active'] ?? false);
$credibancoWebhookUrl = trim((string) ($credibanco['webhook_url'] ?? url('webhooks/credibanco')));
$credibancoTestMerchantCode = trim((string) old('credibanco_test_merchant_code', '010601557'));
$credibancoTestStartAt = trim((string) old('credibanco_test_start_at', '2025-04-24 00:00:00'));
$credibancoTestEndAt = trim((string) old('credibanco_test_end_at', '2025-04-24 23:59:59'));
$credibancoTestRowsPerPage = trim((string) old('credibanco_test_rows_per_page', '10'));
$credibancoTestPage = trim((string) old('credibanco_test_page', '1'));
$credibancoTestTerminal = trim((string) old('credibanco_test_terminal', ''));
$credibancoTestAuthorizationCode = trim((string) old('credibanco_test_authorization_code', ''));
$credibancoTestReference = trim((string) old('credibanco_test_reference', ''));
$credibancoTestAccessToken = trim((string) old('credibanco_test_access_token', ''));

$integrationModalToOpen = trim((string) (flash('integraciones_modal') ?? ''));
$openBoldModal = $integrationModalToOpen === 'bold';
$openCredibancoModal = $integrationModalToOpen === 'credibanco';

$boldLogoUrl = asset('img/integrations/logo-bold.jpeg');
$credibancoLogoUrl = asset('img/integrations/logo-credibanco.png');
$comingSoonIntegrations = [
    [
        'name' => 'WordPress',
        'kind' => 'Botón de pago',
        'description' => 'Sincronización con ecommerce y catálogo online.',
        'logo' => asset('img/integrations/logo-wordpress.webp'),
    ],
];
?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
            <div>
                <h1 class="h5 mb-1">Marketplace de integraciones</h1>
                <p class="text-muted mb-0">Activa servicios externos desde una tarjeta visual y gestiona todo en modal.</p>
            </div>
            <span class="badge text-bg-light border"><?= e((string) (3 + count($comingSoonIntegrations))) ?> integraciones</span>
        </div>
    </div>
</div>

<div class="vx-integrations-grid">
    <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
        <div class="card-body">
            <div class="d-flex align-items-start gap-3 mb-3">
                <div class="d-flex align-items-center gap-3">
                    <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-bold" aria-hidden="true">
                        <img src="<?= e($boldLogoUrl) ?>" alt="Bold">
                    </span>
                        <div>
                            <h2 class="h5 mb-1">Bold</h2>
                            <p class="text-muted mb-0 vx-integration-description">Validación de pagos presenciales desde API de datáfono.</p>
                    </div>
                </div>
            </div>
            <div class="mb-3 d-flex flex-wrap gap-2 vx-integration-badges">
                <span class="badge text-bg-light border">Datáfono API</span>
            </div>

            <div class="row g-2 mb-3">
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Credenciales</small>
                        <strong><?= $boldDataphoneConfigured ? 'Completas' : 'Pendientes' ?></strong>
                    </div>
                </div>
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Método POS</small>
                        <strong><?= $boldDataphoneMethodAvailable ? 'Disponible' : 'No disponible' ?></strong>
                    </div>
                </div>
            </div>

                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mt-auto">
                    <span class="badge vx-integration-state <?= e($boldDataphoneActive ? 'is-active' : 'is-inactive') ?>">
                        <?= $boldDataphoneActive ? 'Activa' : 'Inactiva' ?>
                    </span>
                    <button
                        class="btn btn-primary vx-integration-integrate-btn"
                        type="button"
                        data-bs-toggle="modal"
                        data-bs-target="#boldIntegrationModal"
                        data-bold-open-mode="dataphone"
                    >
                        <i class="bx bx-link-alt me-1"></i>Integrar
                    </button>
                </div>
        </div>
    </article>

    <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
        <div class="card-body">
            <div class="d-flex align-items-start gap-3 mb-3">
                <div class="d-flex align-items-center gap-3">
                    <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-bold" aria-hidden="true">
                        <img src="<?= e($boldLogoUrl) ?>" alt="Bold">
                    </span>
                    <div>
                        <h2 class="h5 mb-1">Bold</h2>
                        <p class="text-muted mb-0 vx-integration-description">Generación de links con Botón de pagos para checkout web.</p>
                    </div>
                </div>
            </div>
            <div class="mb-3 d-flex flex-wrap gap-2 vx-integration-badges">
                <span class="badge text-bg-light border">Botón de pagos</span>
            </div>

            <div class="row g-2 mb-3">
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Credenciales</small>
                        <strong><?= $boldButtonConfigured ? 'Completas' : 'Pendientes' ?></strong>
                    </div>
                </div>
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Método POS</small>
                        <strong><?= $boldButtonMethodAvailable ? 'Disponible' : 'No disponible' ?></strong>
                    </div>
                </div>
            </div>

            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mt-auto">
                <span class="badge vx-integration-state <?= e($boldButtonActive ? 'is-active' : 'is-inactive') ?>">
                    <?= $boldButtonActive ? 'Activa' : 'Inactiva' ?>
                </span>
                <button
                    class="btn btn-primary vx-integration-integrate-btn"
                    type="button"
                    data-bs-toggle="modal"
                    data-bs-target="#boldIntegrationModal"
                    data-bold-open-mode="button"
                >
                    <i class="bx bx-link-alt me-1"></i>Integrar
                </button>
            </div>
        </div>
    </article>

    <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
        <div class="card-body">
            <div class="d-flex align-items-start gap-3 mb-3">
                <div class="d-flex align-items-center gap-3">
                    <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-bold vx-integration-logo-credibanco-image" aria-hidden="true">
                        <img src="<?= e($credibancoLogoUrl) ?>" alt="Credibanco">
                    </span>
                    <div>
                        <h2 class="h5 mb-1">Credibanco</h2>
                        <p class="text-muted mb-0 vx-integration-description">Integración para cobros por datáfono y confirmación asíncrona por webhook.</p>
                    </div>
                </div>
            </div>
            <div class="mb-3 d-flex flex-wrap gap-2 vx-integration-badges">
                <span class="badge text-bg-light border">Datáfono API</span>
                <span class="badge text-bg-light border">developer.credibanco.com</span>
            </div>

            <div class="row g-2 mb-3">
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Credenciales</small>
                        <strong><?= $credibancoConfigured ? 'Completas' : 'Pendientes' ?></strong>
                    </div>
                </div>
                <div class="col-6">
                    <div class="vx-integration-metric">
                        <small>Método POS</small>
                        <strong><?= $credibancoMethodActive ? 'Disponible' : 'No disponible' ?></strong>
                    </div>
                </div>
            </div>

            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mt-auto">
                <span class="badge vx-integration-state <?= e($credibancoEnabled ? 'is-active' : 'is-inactive') ?>">
                    <?= $credibancoEnabled ? 'Activa' : 'Inactiva' ?>
                </span>
                <button
                    class="btn btn-primary vx-integration-integrate-btn"
                    type="button"
                    data-bs-toggle="modal"
                    data-bs-target="#credibancoIntegrationModal"
                >
                    <i class="bx bx-link-alt me-1"></i>Integrar
                </button>
            </div>
        </div>
    </article>

    <?php foreach ($comingSoonIntegrations as $integration): ?>
        <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-coming">
            <div class="card-body">
                <div class="d-flex align-items-start gap-3 mb-3">
                    <div class="d-flex align-items-center gap-3">
                        <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-muted" aria-hidden="true">
                            <img src="<?= e((string) ($integration['logo'] ?? '')) ?>" alt="<?= e((string) ($integration['name'] ?? 'Integración')) ?>">
                        </span>
                        <div>
                            <h2 class="h5 mb-1"><?= e((string) ($integration['name'] ?? 'Integración')) ?></h2>
                            <p class="text-muted mb-0 vx-integration-description"><?= e((string) ($integration['description'] ?? 'Disponible pronto.')) ?></p>
                        </div>
                    </div>
                </div>
                <div class="mb-3 d-flex flex-wrap gap-2 vx-integration-badges">
                    <span class="badge text-bg-light border"><?= e((string) ($integration['kind'] ?? 'Integración')) ?></span>
                </div>

                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <div class="vx-integration-metric">
                            <small>Estado</small>
                            <strong>Disponible pronto</strong>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="vx-integration-metric">
                            <small>Configuración</small>
                            <strong>Pendiente</strong>
                        </div>
                    </div>
                </div>

                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mt-auto">
                    <span class="badge vx-integration-state is-soon">Próximamente</span>
                    <button class="btn vx-integration-integrate-btn vx-integration-integrate-btn-disabled" type="button" disabled>
                        <i class="bx bx-time-five me-1"></i>Integrar
                    </button>
                </div>
            </div>
        </article>
    <?php endforeach; ?>
</div>

<div class="modal fade vx-integration-modal" id="boldIntegrationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h5 class="modal-title d-flex align-items-center gap-2 mb-0">
                    <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-bold vx-integration-logo-sm" aria-hidden="true">
                        <img src="<?= e($boldLogoUrl) ?>" alt="Bold">
                    </span>
                    Integrar Bold
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-lg-8">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body">
                                <h3 class="h6 mb-3">Configuración de API</h3>
                                <form action="<?= e(url('integraciones/bold')) ?>" method="post" class="row g-3">
                                    <?= csrf_field() ?>

                                    <div class="col-md-4">
                                        <label class="form-label">Estado integración</label>
                                        <select class="form-select" name="bold_enabled">
                                            <option value="1" <?= $boldEnabled ? 'selected' : '' ?>>Activa</option>
                                            <option value="0" <?= !$boldEnabled ? 'selected' : '' ?>>Inactiva</option>
                                        </select>
                                    </div>

                                    <div class="col-md-8">
                                        <label class="form-label">Tipo de integración</label>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="badge text-bg-light border" id="boldModeContextLabel">
                                                <?= $boldMode === 'button' ? 'Botón de pagos' : 'API datáfono' ?>
                                            </span>
                                            <small class="text-muted">Este modal ya viene configurado desde la tarjeta seleccionada.</small>
                                        </div>
                                        <input type="hidden" name="bold_mode" id="boldModeInput" value="<?= e($boldMode) ?>">
                                    </div>

                                    <div class="col-12 vx-bold-pane <?= $boldMode === 'dataphone' ? '' : 'd-none' ?>" data-bold-pane="dataphone">
                                        <div class="border rounded-3 p-3">
                                            <div class="fw-semibold mb-2">Llaves API datáfono</div>
                                            <div class="row g-3">
                                                <div class="col-md-7">
                                                    <label class="form-label">URL API Bold</label>
                                                    <input
                                                        type="url"
                                                        class="form-control"
                                                        name="bold_api_url"
                                                        value="<?= e($boldApiUrl) ?>"
                                                        maxlength="255"
                                                        placeholder="https://api.bold.co"
                                                    >
                                                    <small class="text-muted">Debe iniciar con `https://` o `http://`.</small>
                                                </div>
                                                <div class="col-md-5">
                                                    <label class="form-label">API Key</label>
                                                    <input
                                                        type="password"
                                                        class="form-control"
                                                        name="bold_api_key"
                                                        value="<?= e($boldApiKeyInput) ?>"
                                                        autocomplete="new-password"
                                                        placeholder="<?= e($boldHasApiKey ? ($boldApiKeyPreview !== '' ? $boldApiKeyPreview : 'Configurada (oculta). Déjala vacía para conservarla.') : 'Pega aquí tu API Key de Bold') ?>"
                                                    >
                                                    <?php if ($boldHasApiKey && $boldApiKeyInput === '' && $boldApiKeyPreview !== ''): ?>
                                                        <small class="text-muted d-block mt-1">
                                                            Actual: <code><?= e($boldApiKeyPreview) ?></code>
                                                        </small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12 vx-bold-pane <?= $boldMode === 'button' ? '' : 'd-none' ?>" data-bold-pane="button">
                                        <div class="border rounded-3 p-3">
                                            <div class="fw-semibold mb-2">Llaves Botón de pagos</div>
                                            <div class="row g-3">
                                                <div class="col-md-12">
                                                    <label class="form-label">URL Checkout Bold (opcional)</label>
                                                    <input
                                                        type="url"
                                                        class="form-control"
                                                        name="bold_button_checkout_url"
                                                        value="<?= e($boldButtonCheckoutUrl) ?>"
                                                        maxlength="255"
                                                        placeholder="https://checkout.bold.co"
                                                    >
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Llave pública</label>
                                                    <input
                                                        type="password"
                                                        class="form-control"
                                                        name="bold_button_public_key"
                                                        value="<?= e($boldButtonPublicKeyInput) ?>"
                                                        autocomplete="new-password"
                                                        placeholder="<?= e($boldHasButtonPublicKey ? ($boldButtonPublicKeyPreview !== '' ? $boldButtonPublicKeyPreview : 'Configurada (oculta). Déjala vacía para conservarla.') : 'Pega aquí tu llave pública') ?>"
                                                    >
                                                    <?php if ($boldHasButtonPublicKey && $boldButtonPublicKeyInput === '' && $boldButtonPublicKeyPreview !== ''): ?>
                                                        <small class="text-muted d-block mt-1">
                                                            Actual: <code><?= e($boldButtonPublicKeyPreview) ?></code>
                                                        </small>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Llave secreta</label>
                                                    <input
                                                        type="password"
                                                        class="form-control"
                                                        name="bold_button_secret_key"
                                                        value="<?= e($boldButtonSecretKeyInput) ?>"
                                                        autocomplete="new-password"
                                                        placeholder="<?= e($boldHasButtonSecretKey ? ($boldButtonSecretKeyPreview !== '' ? $boldButtonSecretKeyPreview : 'Configurada (oculta). Déjala vacía para conservarla.') : 'Pega aquí tu llave secreta') ?>"
                                                    >
                                                    <?php if ($boldHasButtonSecretKey && $boldButtonSecretKeyInput === '' && $boldButtonSecretKeyPreview !== ''): ?>
                                                        <small class="text-muted d-block mt-1">
                                                            Actual: <code><?= e($boldButtonSecretKeyPreview) ?></code>
                                                        </small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12 d-flex justify-content-end">
                                        <button class="btn btn-primary" type="submit">
                                            <i class="bx bx-save me-1"></i>Guardar integración
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body">
                                <h3 class="h6 mb-3" id="boldTestCardTitle">Probar API datáfono</h3>

                                <div class="vx-bold-test-pane <?= $boldMode === 'dataphone' ? '' : 'd-none' ?>" data-bold-test-pane="dataphone">
                                    <form action="<?= e(url('integraciones/bold/probar')) ?>" method="post" class="row g-2">
                                        <?= csrf_field() ?>

                                        <div class="col-12">
                                            <div class="alert alert-light border mb-0">
                                                <strong>Validación de conectividad:</strong>
                                                esta prueba consulta métodos y terminales en API Datáfono Bold
                                                para verificar llaves, endpoint y permisos.
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="alert alert-warning border mb-0 py-2">
                                                <strong>Nota:</strong>
                                                solo funciona con <strong>Smart Pro</strong> y <strong>Smart</strong>
                                                (a partir de versión de S.O
                                                <code>D20_Bold_release_20250414</code>;
                                                se recomienda actualizar antes de realizar la integración).
                                            </div>
                                        </div>

                                        <div class="col-12 d-flex justify-content-end mt-2">
                                            <button class="btn btn-outline-primary" type="submit">
                                                <i class="bx bx-check-shield me-1"></i>Probar conexión
                                            </button>
                                        </div>
                                        <div class="col-12">
                                            <small class="text-muted d-block text-end">Si responde OK, la integración Datáfono quedó conectada.</small>
                                        </div>
                                    </form>
                                </div>

                                <div class="vx-bold-test-pane <?= $boldMode === 'button' ? '' : 'd-none' ?>" data-bold-test-pane="button">
                                    <form action="<?= e(url('integraciones/bold/probar-boton')) ?>" method="post" class="row g-2">
                                        <?= csrf_field() ?>

                                        <div class="col-6">
                                            <label class="form-label">Tipo de monto</label>
                                            <select class="form-select" name="bold_button_test_amount_type">
                                                <option value="close" <?= $buttonTestAmountType === 'close' ? 'selected' : '' ?>>Cerrado</option>
                                                <option value="open" <?= $buttonTestAmountType === 'open' ? 'selected' : '' ?>>Abierto</option>
                                            </select>
                                        </div>

                                        <div class="col-6">
                                            <label class="form-label">Moneda</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                name="bold_button_test_currency"
                                                value="<?= e($buttonTestCurrency) ?>"
                                                maxlength="3"
                                                placeholder="COP"
                                            >
                                        </div>

                                        <div class="col-12">
                                            <label class="form-label">Monto de prueba</label>
                                            <input
                                                type="number"
                                                class="form-control"
                                                name="bold_button_test_amount"
                                                value="<?= e($buttonTestAmount) ?>"
                                                step="1"
                                                min="0"
                                                placeholder="Ej: 10000"
                                            >
                                        </div>

                                        <div class="col-12">
                                            <label class="form-label">Referencia (opcional)</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                name="bold_button_test_reference"
                                                value="<?= e($buttonTestReference) ?>"
                                                maxlength="120"
                                                placeholder="Se genera automática si va vacía"
                                            >
                                        </div>

                                        <div class="col-12">
                                            <label class="form-label">Descripción</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                name="bold_button_test_description"
                                                value="<?= e($buttonTestDescription) ?>"
                                                maxlength="140"
                                                placeholder="Pago de prueba Veltrix POS"
                                            >
                                        </div>

                                        <div class="col-12 d-flex justify-content-end mt-2">
                                            <button class="btn btn-outline-primary" type="submit">
                                                <i class="bx bx-link-external me-1"></i>Crear checkout de prueba
                                            </button>
                                        </div>
                                        <div class="col-12">
                                            <small class="text-muted d-block text-end">Crea un link real de checkout usando la API de Botón de pagos.</small>
                                        </div>
                                    </form>

                                    <?php if ($buttonGeneratedUrl !== ''): ?>
                                        <div class="mt-3 p-2 border rounded-3 bg-light-subtle">
                                            <small class="text-muted d-block mb-1">Último checkout generado</small>
                                            <?php if ($buttonGeneratedPaymentLink !== ''): ?>
                                                <small class="d-block mb-1">ID: <strong><?= e($buttonGeneratedPaymentLink) ?></strong></small>
                                            <?php endif; ?>
                                            <?php if ($buttonTestReference !== ''): ?>
                                                <small class="d-block mb-2">Referencia: <strong><?= e($buttonTestReference) ?></strong></small>
                                            <?php endif; ?>
                                            <div class="input-group input-group-sm">
                                                <input type="text" class="form-control" value="<?= e($buttonGeneratedUrl) ?>" readonly>
                                                <a class="btn btn-primary" href="<?= e($buttonGeneratedUrl) ?>" target="_blank" rel="noopener">
                                                    Abrir
                                                </a>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <hr class="my-3">

                                <div class="d-grid gap-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Integración</small>
                                        <span class="badge <?= e($boldEnabled ? 'text-bg-success' : 'text-bg-secondary') ?>">
                                            <?= $boldEnabled ? 'Activa' : 'Inactiva' ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Método</small>
                                        <span class="badge text-bg-light border"><?= e($boldModeLabel) ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Credenciales (método)</small>
                                        <span class="badge <?= e($boldConfigured ? 'text-bg-success' : 'text-bg-warning text-dark') ?>">
                                            <?= $boldConfigured ? 'Completas' : 'Pendientes' ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Método de pago Bold</small>
                                        <span class="badge <?= e($boldMethodActive ? 'text-bg-primary' : 'text-bg-secondary') ?>">
                                            <?= $boldMethodActive ? 'Activo en POS' : 'Inactivo en POS' ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade vx-integration-modal" id="credibancoIntegrationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h5 class="modal-title d-flex align-items-center gap-2 mb-0">
                    <span class="vx-integration-logo vx-integration-logo-image vx-integration-logo-bold vx-integration-logo-credibanco-image vx-integration-logo-sm" aria-hidden="true">
                        <img src="<?= e($credibancoLogoUrl) ?>" alt="Credibanco">
                    </span>
                    Integrar Credibanco
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-lg-8">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body">
                                <h3 class="h6 mb-3">Configuración API Credibanco</h3>
                                <form action="<?= e(url('integraciones/credibanco')) ?>" method="post" class="row g-3">
                                    <?= csrf_field() ?>

                                    <div class="col-md-4">
                                        <label class="form-label">Estado integración</label>
                                        <select class="form-select" name="credibanco_enabled">
                                            <option value="1" <?= $credibancoEnabled ? 'selected' : '' ?>>Activa</option>
                                            <option value="0" <?= !$credibancoEnabled ? 'selected' : '' ?>>Inactiva</option>
                                        </select>
                                    </div>

                                    <div class="col-md-8">
                                        <label class="form-label">URL API base</label>
                                        <input
                                            type="url"
                                            class="form-control"
                                            name="credibanco_api_url"
                                            value="<?= e($credibancoApiUrl) ?>"
                                            maxlength="255"
                                            placeholder="https://api.developer.credibanco.com"
                                        >
                                        <small class="text-muted">Debe iniciar con `https://` o `http://`.</small>
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">URL SSO token (opcional)</label>
                                        <input
                                            type="url"
                                            class="form-control"
                                            name="credibanco_token_url"
                                            value="<?= e($credibancoTokenUrl) ?>"
                                            maxlength="255"
                                            placeholder="Ejemplo: https://sso-.../auth/realms/3Scale/protocol/openid-connect/token"
                                        >
                                        <small class="text-muted">Credibanco indica que este endpoint por ambiente se solicita al comercial asignado.</small>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Client ID</label>
                                        <input
                                            type="password"
                                            class="form-control"
                                            name="credibanco_client_id"
                                            value="<?= e($credibancoClientIdInput) ?>"
                                            autocomplete="new-password"
                                            placeholder="<?= e($credibancoHasClientId ? ($credibancoClientIdPreview !== '' ? $credibancoClientIdPreview : 'Configurado (oculto). Déjalo vacío para conservarlo.') : 'Ejemplo: 116d58b9') ?>"
                                        >
                                        <?php if ($credibancoHasClientId && $credibancoClientIdInput === '' && $credibancoClientIdPreview !== ''): ?>
                                            <small class="text-muted d-block mt-1">Actual: <code><?= e($credibancoClientIdPreview) ?></code></small>
                                        <?php endif; ?>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Client Secret</label>
                                        <input
                                            type="password"
                                            class="form-control"
                                            name="credibanco_client_secret"
                                            value="<?= e($credibancoClientSecretInput) ?>"
                                            autocomplete="new-password"
                                            placeholder="<?= e($credibancoHasClientSecret ? ($credibancoClientSecretPreview !== '' ? $credibancoClientSecretPreview : 'Configurado (oculto). Déjalo vacío para conservarlo.') : 'Pega aquí tu Client Secret') ?>"
                                        >
                                        <?php if ($credibancoHasClientSecret && $credibancoClientSecretInput === '' && $credibancoClientSecretPreview !== ''): ?>
                                            <small class="text-muted d-block mt-1">Actual: <code><?= e($credibancoClientSecretPreview) ?></code></small>
                                        <?php endif; ?>
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Webhook secret (opcional)</label>
                                        <input
                                            type="password"
                                            class="form-control"
                                            name="credibanco_events_secret"
                                            value="<?= e($credibancoEventsSecretInput) ?>"
                                            autocomplete="new-password"
                                            placeholder="<?= e($credibancoHasEventsSecret ? ($credibancoEventsSecretPreview !== '' ? $credibancoEventsSecretPreview : 'Configurada (oculta). Déjala vacía para conservarla.') : 'Secret de firma de eventos') ?>"
                                        >
                                        <?php if ($credibancoHasEventsSecret && $credibancoEventsSecretInput === '' && $credibancoEventsSecretPreview !== ''): ?>
                                            <small class="text-muted d-block mt-1">Actual: <code><?= e($credibancoEventsSecretPreview) ?></code></small>
                                        <?php endif; ?>
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">URL webhook en Credibanco</label>
                                        <input type="text" class="form-control" value="<?= e($credibancoWebhookUrl) ?>" readonly>
                                        <small class="text-muted">Configura esta URL en tu panel de desarrolladores de Credibanco.</small>
                                    </div>

                                    <div class="col-12 d-flex justify-content-end">
                                        <button class="btn btn-primary" type="submit">
                                            <i class="bx bx-save me-1"></i>Guardar integración
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body">
                                <h3 class="h6 mb-3">Probar token + consulta</h3>
                                <form action="<?= e(url('integraciones/credibanco/probar')) ?>" method="post" class="row g-2">
                                    <?= csrf_field() ?>

                                    <div class="col-12">
                                        <label class="form-label">Código comercio (CU)</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_merchant_code"
                                            value="<?= e($credibancoTestMerchantCode) ?>"
                                            maxlength="80"
                                            placeholder="Ejemplo: 010601557"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Fecha inicio</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_start_at"
                                            value="<?= e($credibancoTestStartAt) ?>"
                                            maxlength="40"
                                            placeholder="YYYY-MM-DD HH:MM:SS"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Fecha fin</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_end_at"
                                            value="<?= e($credibancoTestEndAt) ?>"
                                            maxlength="40"
                                            placeholder="YYYY-MM-DD HH:MM:SS"
                                        >
                                    </div>

                                    <div class="col-6">
                                        <label class="form-label">Filas</label>
                                        <input
                                            type="number"
                                            class="form-control"
                                            name="credibanco_test_rows_per_page"
                                            value="<?= e($credibancoTestRowsPerPage) ?>"
                                            min="1"
                                            max="500"
                                            step="1"
                                        >
                                    </div>

                                    <div class="col-6">
                                        <label class="form-label">Página</label>
                                        <input
                                            type="number"
                                            class="form-control"
                                            name="credibanco_test_page"
                                            value="<?= e($credibancoTestPage) ?>"
                                            min="1"
                                            step="1"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Terminal (opcional)</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_terminal"
                                            value="<?= e($credibancoTestTerminal) ?>"
                                            maxlength="40"
                                            placeholder="Ejemplo: 000BB2TC"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Código autorización (opcional)</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_authorization_code"
                                            value="<?= e($credibancoTestAuthorizationCode) ?>"
                                            maxlength="40"
                                            placeholder="Ejemplo: 603801"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Referencia (opcional)</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            name="credibanco_test_reference"
                                            value="<?= e($credibancoTestReference) ?>"
                                            maxlength="80"
                                            placeholder="Ejemplo: 001482622"
                                        >
                                    </div>

                                    <div class="col-12">
                                        <label class="form-label">Access token manual (opcional)</label>
                                        <textarea
                                            class="form-control"
                                            name="credibanco_test_access_token"
                                            rows="2"
                                            placeholder="Pega aquí el token generado en el portal de Credibanco para saltar la generación SSO"
                                        ><?= e($credibancoTestAccessToken) ?></textarea>
                                    </div>

                                    <div class="col-12 d-flex justify-content-end mt-2">
                                        <button class="btn btn-outline-primary" type="submit">
                                            <i class="bx bx-check-shield me-1"></i>Probar token/consulta
                                        </button>
                                    </div>
                                </form>

                                <small class="text-muted d-block mt-2">
                                    Sandbox Credibanco: CU de prueba sugeridos <code>010601557</code>, <code>014270680</code>, <code>014589824</code>.
                                </small>
                                <small class="text-muted d-block">
                                    Fechas de prueba sugeridas: <code>2025-04-24</code> o <code>2025-07-07</code>/<code>2025-07-08</code>.
                                </small>
                                <small class="text-muted d-block">
                                    Si no tienes URL SSO, genera token en el portal y pégalo en “Access token manual”.
                                </small>

                                <hr class="my-3">
                                <h3 class="h6 mb-3">Estado rápido</h3>
                                <div class="d-grid gap-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Integración</small>
                                        <span class="badge <?= e($credibancoEnabled ? 'text-bg-success' : 'text-bg-secondary') ?>">
                                            <?= $credibancoEnabled ? 'Activa' : 'Inactiva' ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Credenciales</small>
                                        <span class="badge <?= e($credibancoConfigured ? 'text-bg-success' : 'text-bg-warning text-dark') ?>">
                                            <?= $credibancoConfigured ? 'Completas' : 'Pendientes' ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">Método de pago</small>
                                        <span class="badge <?= e($credibancoMethodActive ? 'text-bg-primary' : 'text-bg-secondary') ?>">
                                            <?= $credibancoMethodActive ? 'Activo en POS' : 'Inactivo en POS' ?>
                                        </span>
                                    </div>
                                </div>

                                <hr class="my-3">
                                <small class="text-muted d-block">
                                    Flujo: la venta se crea <strong>pendiente</strong> y pasa a <strong>pagada</strong>
                                    cuando llega webhook aprobado en <code>/webhooks/credibanco</code>.
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<?php if ($openBoldModal): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof bootstrap === 'undefined') {
                return;
            }
            const modalEl = document.getElementById('boldIntegrationModal');
            if (!modalEl) {
                return;
            }
            const instance = bootstrap.Modal.getOrCreateInstance(modalEl);
            instance.show();
        });
    </script>
<?php endif; ?>

<?php if ($openCredibancoModal): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof bootstrap === 'undefined') {
                return;
            }
            const modalEl = document.getElementById('credibancoIntegrationModal');
            if (!modalEl) {
                return;
            }
            const instance = bootstrap.Modal.getOrCreateInstance(modalEl);
            instance.show();
        });
    </script>
<?php endif; ?>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const modalEl = document.getElementById('boldIntegrationModal');
        if (!modalEl) {
            return;
        }

        const modeInput = modalEl.querySelector('#boldModeInput');
        const openModeButtons = document.querySelectorAll('[data-bold-open-mode]');
        const panes = modalEl.querySelectorAll('[data-bold-pane]');
        const testPanes = modalEl.querySelectorAll('[data-bold-test-pane]');
        const testCardTitle = modalEl.querySelector('#boldTestCardTitle');
        const modeContextLabel = modalEl.querySelector('#boldModeContextLabel');

        const setMode = function (nextMode) {
            const mode = (nextMode === 'button') ? 'button' : 'dataphone';
            if (modeInput) {
                modeInput.value = mode;
            }

            panes.forEach(function (pane) {
                const paneMode = pane.getAttribute('data-bold-pane') || '';
                pane.classList.toggle('d-none', paneMode !== mode);
            });

            testPanes.forEach(function (pane) {
                const paneMode = pane.getAttribute('data-bold-test-pane') || '';
                pane.classList.toggle('d-none', paneMode !== mode);
            });

            if (testCardTitle) {
                testCardTitle.textContent = mode === 'dataphone'
                    ? 'Probar API datáfono'
                    : 'Probar Botón de pagos';
            }

            if (modeContextLabel) {
                modeContextLabel.textContent = mode === 'dataphone'
                    ? 'API datáfono'
                    : 'Botón de pagos';
            }
        };

        openModeButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                setMode(button.getAttribute('data-bold-open-mode') || 'dataphone');
            });
        });

        setMode(modeInput && modeInput.value ? modeInput.value : 'dataphone');
    });
</script>
