<?php
// Contenido del módulo Integraciones (Voiso configuración y estado)
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
$pdo = getDB()->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);

if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}

// Incluir el autoloader de API
require_once __DIR__ . '/../../api/shared/ApiLoader.php';

$canConfigureVoiso = userHasPermissionByName($pdo, 'voiso.configure', $current_user_id);
$canConfigurePayments = userHasPermissionByName($pdo, 'payments.configure', $current_user_id);
// Permiso específico para configurar Big4pay; permitir si tiene big4pay.configure o payments.configure
$canConfigureBig4pay = userHasPermissionByName($pdo, 'big4pay.configure', $current_user_id) || $canConfigurePayments;

// Usar las nuevas clases API para cargar configuraciones
$voisoClient = ApiLoader::getVoisoClient($pdo);
$big4payClient = ApiLoader::getBig4payClient($pdo);
$key2payClient = ApiLoader::getIntegrationClient('key2pay', $pdo);

$voisoConfig = $voisoClient->getConfiguration();
$big4payConfig = $big4payClient->getConfiguration();
$key2payConfig = $key2payClient ? $key2payClient->getConfiguration() : [];

$api_base_url = htmlspecialchars($voisoConfig['api_base_url'] ?? '');
$api_token = htmlspecialchars($voisoConfig['api_token'] ?? '');
$default_caller_id = htmlspecialchars($voisoConfig['default_caller_id'] ?? '');
$default_agent_id = htmlspecialchars($voisoConfig['default_agent_id'] ?? '');

$big4pay_username = htmlspecialchars($big4payConfig['username'] ?? '');
// Mantener el valor real oculto (se cargará vía JS si está configurado)
$big4pay_password = '';
// Moneda configurada
$big4pay_currency = htmlspecialchars($big4payConfig['currency'] ?? 'MXN');
// URLs configurables
$big4pay_ipn_url = htmlspecialchars($big4payConfig['ipn_url'] ?? '');
$big4pay_success_url = htmlspecialchars($big4payConfig['success_url'] ?? '');
$big4pay_cancel_url = htmlspecialchars($big4payConfig['cancel_url'] ?? '');

// Estado de configuración usando los métodos de las clases API
$isVoisoConfigured = $voisoClient->isConfigured();
$isBig4payConfigured = $big4payClient->isConfigured();
$isKey2PayConfigured = $key2payClient ? $key2payClient->isConfigured() : false;
?>

<div class="roles-header">
    <div class="header-left">
        <h1 class="page-title">
            <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M10 3a2 2 0 1 1 4 0v3h3a2 2 0 1 1 0 4h-3v4h3a2 2 0 1 1 0 4h-3v3a2 2 0 1 1-4 0v-3H7a2 2 0 1 1 0-4h3v-4H7a2 2 0 1 1 0-4h3V3z"/>
            </svg>
            Integraciones
        </h1>
        <p class="page-subtitle">Configura y gestiona integraciones externas: Voiso y Payment Methods.</p>
    </div>
    
</div>

<style>
.integration-card { display: flex; align-items: center; gap: 12px; cursor: pointer; padding: 12px; }
.integration-card:hover { background: #f7f7f8; }
.integration-logo { width: 48px; height: 48px; border-radius: 8px; background: #eef2ff; display: inline-flex; align-items: center; justify-content: center; }
.integration-title { font-size: 18px; font-weight: 600; }
.badge { background: #e9ecef; color: #555; padding: 4px 8px; border-radius: 8px; font-size: 12px; }
.status-pill { padding: 4px 8px; border-radius: 8px; font-size: 12px; border: 1px solid transparent; }
.status-ok { background: #e6fffa; color: #065f46; border-color: #a7f3d0; }
.status-missing { background: #fff7ed; color: #9a3412; border-color: #fed7aa; }
</style>

<div class="integrations-grid">
    <div class="card">
        <div class="integration-card" onclick="toggleVoisoConfig()">
            <span class="integration-logo">
                <img src="../../public/integrations/voiso.svg" alt="Voiso" style="width:32px;height:32px"/>
            </span>
            <div style="flex:1">
                <div class="integration-title">Voiso</div>
                <div class="muted">Click-to-call y configuración del Contact Center API.</div>
            </div>
            <span class="status-pill <?php echo $isVoisoConfigured ? 'status-ok' : 'status-missing'; ?>">
                <?php echo $isVoisoConfigured ? 'Configurado' : 'Falta configuración'; ?>
            </span>
            <?php if (!$canConfigureVoiso): ?>
                <span class="badge">Solo lectura</span>
            <?php endif; ?>
        </div>
        <div id="voisoConfigPanel" class="card-body" style="display:none">
            <p class="muted">Para Click-to-call, necesitamos el endpoint y token de Voiso, además del Caller ID y opcionalmente un Agent ID por defecto.</p>

            <form id="voisoConfigForm" class="form-grid">
                <div class="form-group">
                    <label class="form-label">API Base URL</label>
                    <input type="text" id="voiso_api_base_url" class="form-control" placeholder="https://api.voiso.com" value="<?php echo $api_base_url; ?>" <?php echo $canConfigureVoiso ? '' : 'disabled'; ?>>
                </div>
                <div class="form-group">
                    <label class="form-label">API Token</label>
                    <input type="password" id="voiso_api_token" class="form-control" placeholder="Bearer token" value="<?php echo $api_token; ?>" <?php echo $canConfigureVoiso ? '' : 'disabled'; ?>>
                </div>
                <div class="form-group">
                    <label class="form-label">Default Caller ID</label>
                    <input type="text" id="voiso_default_caller_id" class="form-control" placeholder="Ej. +34911111222" value="<?php echo $default_caller_id; ?>" <?php echo $canConfigureVoiso ? '' : 'disabled'; ?>>
                </div>
                <div class="form-group">
                    <label class="form-label">Default Agent ID (opcional)</label>
                    <input type="text" id="voiso_default_agent_id" class="form-control" placeholder="Ej. 12345" value="<?php echo $default_agent_id; ?>" <?php echo $canConfigureVoiso ? '' : 'disabled'; ?>>
                </div>
                <?php if ($canConfigureVoiso): ?>
                <div class="form-actions">
                    <button type="button" class="btn btn-primary" onclick="saveVoisoSettings()">Guardar configuración</button>
                    <button type="button" class="btn btn-secondary" onclick="testVoisoIntegration()">Probar integración</button>
                </div>
                <?php endif; ?>
            </form>

            <div class="alert alert-info" id="voisoConfigStatus" style="display:none"></div>
        </div>
    </div>

    <!-- Payment Methods Section -->
    <div class="card">
        <div class="integration-card" onclick="toggleBig4payConfig()">
            <span class="integration-logo">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#4f46e5" stroke-width="2">
                    <rect x="1" y="5" width="22" height="14" rx="2" ry="2"/>
                    <line x1="1" y1="10" x2="23" y2="10"/>
                </svg>
            </span>
            <div style="flex:1">
                <div class="integration-title">Big4pay</div>
                <div class="muted">Procesamiento de pagos para el portal del cliente.</div>
            </div>
            <span class="status-pill <?php echo $isBig4payConfigured ? 'status-ok' : 'status-missing'; ?>">
                <?php echo $isBig4payConfigured ? 'Configurado' : 'Falta configuración'; ?>
            </span>
            <?php if (!$canConfigureBig4pay): ?>
                <span class="badge">Solo lectura</span>
            <?php endif; ?>
        </div>
        <div id="big4payConfigPanel" class="card-body" style="display:none">
            <p class="muted">Configura las credenciales de Big4pay para procesar pagos desde el portal del cliente.</p>

            <form id="big4payConfigForm" class="form-grid">
                <div class="form-group">
                    <label class="form-label">Username</label>
                    <input type="text" id="big4pay_username" class="form-control" placeholder="@iatrade" value="<?php echo $big4pay_username; ?>" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?>>
                </div>
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <div style="display:flex; gap:8px; align-items:center;">
                        <input type="password" id="big4pay_password" class="form-control" placeholder="Password" value="<?php echo $big4pay_password; ?>" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?> data-loaded="false">
                        <?php if ($canConfigureBig4pay): ?>
                        <button type="button" class="btn btn-secondary" id="toggle_big4pay_password" onclick="toggleBig4payPassword()" title="Mostrar/Ocultar">
                            👁️
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Currency</label>
                    <select id="big4pay_currency" class="form-control" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?>>
                        <?php $curr = $big4pay_currency; ?>
                        <option value="MXN" <?php echo $curr === 'MXN' ? 'selected' : ''; ?>>MXN (Mexican Peso)</option>
                        <option value="USD" <?php echo $curr === 'USD' ? 'selected' : ''; ?>>USD (US Dollar)</option>
                        <option value="EUR" <?php echo $curr === 'EUR' ? 'selected' : ''; ?>>EUR (Euro)</option>
                        <option value="COP" <?php echo $curr === 'COP' ? 'selected' : ''; ?>>COP (Colombian Peso)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">IPN URL</label>
                    <input type="text" id="big4pay_ipn_url" class="form-control" placeholder="https://tu-dominio.com/api/payment_method/big4pay/ipn.php" value="<?php echo $big4pay_ipn_url; ?>" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?> />
                </div>
                <div class="form-group">
                    <label class="form-label">Success URL</label>
                    <input type="text" id="big4pay_success_url" class="form-control" placeholder="https://tu-dominio.com/portal/big4pay_success" value="<?php echo $big4pay_success_url; ?>" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?> />
                </div>
                <div class="form-group">
                    <label class="form-label">Cancel URL</label>
                    <input type="text" id="big4pay_cancel_url" class="form-control" placeholder="https://tu-dominio.com/portal/big4pay_cancel" value="<?php echo $big4pay_cancel_url; ?>" <?php echo $canConfigureBig4pay ? '' : 'disabled'; ?> />
                </div>
                <?php if ($canConfigureBig4pay): ?>
                <div class="form-actions">
                    <button type="button" class="btn btn-primary" onclick="saveBig4paySettings()">Guardar configuración</button>
                    <button type="button" class="btn btn-secondary" onclick="testBig4payIntegration()">Probar integración</button>
                    <button type="button" class="btn btn-success" onclick="testBig4payPayment()">Pago de prueba (200 <?php echo $big4pay_currency; ?>)</button>
                </div>
                <?php endif; ?>
            </form>

            <div class="alert alert-info" id="big4payConfigStatus" style="display:none"></div>
        </div>
    </div>
</div>

<script>
const BIG4PAY_IS_CONFIGURED = <?php echo $isBig4payConfigured ? 'true' : 'false'; ?>;
const CAN_CONFIGURE_BIG4PAY = <?php echo $canConfigureBig4pay ? 'true' : 'false'; ?>;
async function saveVoisoSettings() {
    const payload = {
        api_base_url: document.getElementById('voiso_api_base_url').value.trim(),
        api_token: document.getElementById('voiso_api_token').value.trim(),
        default_caller_id: document.getElementById('voiso_default_caller_id').value.trim(),
        default_agent_id: document.getElementById('voiso_default_agent_id').value.trim(),
    };
    const statusBox = document.getElementById('voisoConfigStatus');
    statusBox.style.display = 'none';
    try {
        const resp = await fetch('/modules/integrations/actions.php?action=save_settings', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ integration: 'voiso', settings: payload })
        });
        const data = await resp.json();
        statusBox.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
        statusBox.textContent = data.message || (data.success ? 'Configuración guardada.' : 'Error al guardar');
        statusBox.style.display = 'block';
    } catch (e) {
        statusBox.className = 'alert alert-error';
        statusBox.textContent = 'Error de red o JSON inválido al guardar configuración.';
        statusBox.style.display = 'block';
    }
}

function toggleVoisoConfig(forceOpen) {
    const panel = document.getElementById('voisoConfigPanel');
    if (!panel) return;
    if (forceOpen === true) {
        panel.style.display = 'block';
        return;
    }
    panel.style.display = (panel.style.display === 'none' || panel.style.display === '') ? 'block' : 'none';
}

async function testVoisoIntegration() {
    const statusBox = document.getElementById('voisoConfigStatus');
    statusBox.className = 'alert alert-info';
    statusBox.textContent = 'Probando conexión con Voiso…';
    statusBox.style.display = 'block';
    try {
        const resp = await fetch('/modules/integrations/actions.php?action=test_voiso');
        const data = await resp.json();
        statusBox.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
        statusBox.textContent = data.message ? `${data.message}${data.status ? ` (HTTP ${data.status})` : ''}` : (data.success ? 'Integración verificada.' : 'Error al probar integración');
        statusBox.style.display = 'block';
    } catch (e) {
        statusBox.className = 'alert alert-error';
        statusBox.textContent = 'Error de red o JSON inválido durante la prueba.';
        statusBox.style.display = 'block';
    }
}

async function saveBig4paySettings() {
    const payload = {
        username: document.getElementById('big4pay_username').value.trim(),
        password: document.getElementById('big4pay_password').value.trim(),
        currency: document.getElementById('big4pay_currency').value,
        ipn_url: document.getElementById('big4pay_ipn_url').value.trim(),
        success_url: document.getElementById('big4pay_success_url').value.trim(),
        cancel_url: document.getElementById('big4pay_cancel_url').value.trim(),
    };
    const statusBox = document.getElementById('big4payConfigStatus');
    statusBox.style.display = 'none';
    try {
        const resp = await fetch('/modules/integrations/actions.php?action=save_settings', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ integration: 'big4pay', settings: payload })
        });
        const data = await resp.json();
        statusBox.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
        statusBox.textContent = data.message || (data.success ? 'Configuración guardada.' : 'Error al guardar');
        statusBox.style.display = 'block';
    } catch (e) {
        statusBox.className = 'alert alert-error';
        statusBox.textContent = 'Error de red o JSON inválido al guardar configuración.';
        statusBox.style.display = 'block';
    }
}

function toggleBig4payConfig(forceOpen) {
    const panel = document.getElementById('big4payConfigPanel');
    if (!panel) return;
    if (forceOpen === true) {
        panel.style.display = 'block';
        return;
    }
    panel.style.display = (panel.style.display === 'none' || panel.style.display === '') ? 'block' : 'none';
}

async function testBig4payIntegration() {
    const statusBox = document.getElementById('big4payConfigStatus');
    statusBox.className = 'alert alert-info';
    statusBox.textContent = 'Probando conexión con Big4pay…';
    statusBox.style.display = 'block';
    try {
        const resp = await fetch('/modules/integrations/actions.php?action=test_big4pay');
        const data = await resp.json();
        statusBox.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
        const httpPart = data.status ? ` (HTTP ${data.status})` : '';
        statusBox.textContent = data.message ? `${data.message}${httpPart}` : (data.success ? 'Integración verificada.' : 'Error al probar integración');
        statusBox.style.display = 'block';
    } catch (e) {
        statusBox.className = 'alert alert-error';
        statusBox.textContent = 'Error de red o JSON inválido durante la prueba.';
        statusBox.style.display = 'block';
    }
}

async function toggleBig4payPassword() {
    const input = document.getElementById('big4pay_password');
    const btn = document.getElementById('toggle_big4pay_password');
    if (!input || !btn) return;
    if (input.type === 'password') {
        // Mostrar en texto plano; cargar si aún no está cargado
        if (input.dataset.loaded !== 'true') {
            try {
                const resp = await fetch('/modules/integrations/actions.php?action=get_big4pay_password');
                const data = await resp.json();
                if (data.success && typeof data.password === 'string') {
                    input.value = data.password;
                    input.dataset.loaded = 'true';
                }
            } catch (e) {
                // Mantener oculto si falla la carga
            }
        }
        input.type = 'text';
        btn.textContent = '🙈';
        btn.title = 'Ocultar';
    } else {
        // Ocultar, manteniendo el valor real en el input
        input.type = 'password';
        btn.textContent = '👁️';
        btn.title = 'Mostrar';
    }
}

async function testBig4payPayment() {
    const statusBox = document.getElementById('big4payConfigStatus');
    statusBox.style.display = 'none';
    
    try {
        const resp = await fetch('actions.php?action=test_big4pay_payment', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ amount: 200, currency: 'MXN' })
        });
        const data = await resp.json();
        statusBox.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
        const raw = typeof data.body === 'string' ? data.body : JSON.stringify(data.json ?? data);
        const prefix = data.http_code ? `(HTTP ${data.http_code}) ` : '';
        statusBox.textContent = `${prefix}${raw}`;
        statusBox.style.display = 'block';

        // Intentar abrir redirect_url / checkout_url / payment_link en nueva pestaña
        let redirectUrl = null;
        if (data) {
            redirectUrl = data.redirect_url || data.checkout_url || data.payment_link || null;
            if (!redirectUrl && data.json) {
                redirectUrl = data.json.redirect_url || data.json.checkout_url || data.json.payment_link || null;
            }
            if (!redirectUrl && typeof data.body === 'string') {
                try {
                    const parsed = JSON.parse(data.body);
                    redirectUrl = parsed.redirect_url || parsed.checkout_url || parsed.payment_link || null;
                } catch (_) {}
            }
        }
        if (redirectUrl && typeof redirectUrl === 'string') {
            try {
                const w = window.open(redirectUrl, '_blank', 'noopener');
                if (!w) {
                    // Fallback si el navegador bloquea popups: mostrar enlace clicable
                    const a = document.createElement('a');
                    a.href = redirectUrl;
                    a.target = '_blank';
                    a.rel = 'noopener';
                    a.textContent = 'Abrir checkout';
                    statusBox.appendChild(document.createElement('br'));
                    statusBox.appendChild(a);
                }
            } catch (err) {
                const a = document.createElement('a');
                a.href = redirectUrl;
                a.target = '_blank';
                a.rel = 'noopener';
                a.textContent = 'Abrir checkout';
                statusBox.appendChild(document.createElement('br'));
                statusBox.appendChild(a);
            }
        }
    } catch (e) {
        statusBox.className = 'alert alert-error';
        statusBox.textContent = 'Error de red al procesar pago de prueba.';
        statusBox.style.display = 'block';
    }
}

async function initBig4payPassword() {
    const input = document.getElementById('big4pay_password');
    if (!input) return;
    if (!CAN_CONFIGURE_BIG4PAY) return;
    if (!BIG4PAY_IS_CONFIGURED) return;
    try {
        const resp = await fetch('/modules/integrations/actions.php?action=get_big4pay_password');
        const data = await resp.json();
        if (data.success && typeof data.password === 'string') {
            input.value = data.password;
            input.dataset.loaded = 'true';
            input.type = 'password';
        }
    } catch (e) {
        // Silencioso: si falla, el usuario aún puede escribir una nueva
    }
}

document.addEventListener('DOMContentLoaded', initBig4payPassword);

function toggleKey2PayConfig(forceOpen){ const panel=document.getElementById('key2payConfigPanel'); if(!panel) return; panel.style.display=(forceOpen===true)?'block':((panel.style.display==='none'||panel.style.display==='')?'block':'none'); }
async function testKey2PayPayment(){ const box=document.getElementById('key2payConfigStatus'); box.style.display='none'; try{ const resp=await fetch('/modules/integrations/actions.php?action=test_key2pay_payment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({amount:200,currency:'USD'})}); const data=await resp.json(); box.className='alert '+(data.success?'alert-success':'alert-error'); const raw=typeof data.body==='string'?data.body:JSON.stringify(data.json??data); const prefix=data.http_code?`(HTTP ${data.http_code}) `:''; box.textContent=`${prefix}${raw}`; box.style.display='block'; let redirectUrl=null; redirectUrl=data?.json?.checkout_url || data?.json?.payment_link || null; if(!redirectUrl && typeof data.body==='string'){ try{ const parsed=JSON.parse(data.body); redirectUrl=parsed.checkout_url || parsed.payment_link || null; }catch(_){} } if(redirectUrl){ const a=document.createElement('a'); a.href=redirectUrl; a.target='_blank'; a.rel='noopener'; a.textContent='Abrir checkout'; box.appendChild(document.createElement('br')); box.appendChild(a); } }catch(e){ box.className='alert alert-error'; box.textContent='Error de red al procesar pago de prueba.'; box.style.display='block'; } }
</script>
