<?php

chdir(__DIR__);

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/src/PaymentIntentService.php';

use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
use App\PaymentIntentService;

// --- INITIALIZATION ---
$log = PluginLogManager::create();
$configManager = PluginConfigManager::create();
$config = $configManager->loadConfig();

$ipServer = $config['ipServer'] ?? '';
$baseUrl = 'https://' . $ipServer . '/crm'; 
$apiUcrmKey = $config['apiTokenUcrm'] ?? '';
$stripeApiKey = $config['apiTokenStripe'] ?? '';

$service = new PaymentIntentService($baseUrl, $apiUcrmKey, $stripeApiKey, $log);

// --- ROUTER ---
$action = $_GET['action'] ?? 'view';

// 1. Image Handler
if ($action === 'image') {
    $filename = basename($_GET['file'] ?? '');
    $path = __DIR__ . '/img/' . $filename;
    if ($filename && file_exists($path)) {
        $mime = mime_content_type($path);
        header("Content-Type: $mime");
        readfile($path);
    } else {
        http_response_code(404);
        echo "Image not found";
    }
    exit;
}

// 2. Search Handler (AJAX)
if ($action === 'search') {
    $query = $_GET['q'] ?? '';
    if (strlen($query) < 2) {
        echo json_encode([]);
        exit;
    }
    $results = $service->searchClients($query);
    header('Content-Type: application/json');
    echo json_encode($results);
    exit;
}

// 3. Get Details Handler (AJAX)
if ($action === 'details') {
    $clientId = $_GET['id'] ?? 0;
    if (!$clientId) {
        echo json_encode(['error' => 'No ID provided']);
        exit;
    }
    $details = $service->getClientDetails($clientId);
    header('Content-Type: application/json');
    echo json_encode($details);
    exit;
}

// 4. Create Intent Handler (AJAX)
if ($action === 'create_intent') {
    $input = json_decode(file_get_contents('php://input'), true);
    $clientId = $input['clientId'] ?? 0;
    $amount = filter_var($input['amount'], FILTER_VALIDATE_FLOAT);
    $stripeCustomerId = $input['stripeCustomerId'] ?? '';
    
    // Hardcoded admin ID as per user context in previous script (fallback)
    // In a real plugin, we might want to get this from a mapping or config, but for now specific ID or 1
    $adminId = 5472; 

    if (!$amount || $amount < 10) {
        echo json_encode(['success' => false, 'error' => 'El monto debe ser mayor a $10.00 MXN']);
        exit;
    }

    if (!$stripeCustomerId) {
        echo json_encode(['success' => false, 'error' => 'El cliente no tiene Stripe Customer ID']);
        exit;
    }

    $result = $service->createPaymentIntent($clientId, $amount, $stripeCustomerId, $adminId);
    
    // Logging for debug
    $log->appendLog("Create Intent Result: " . json_encode($result));

    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

// 5. Webhook Handler
if ($action === 'webhook') {
    $payload = @file_get_contents('php://input');
    $event = null;

    try {
        $event = \Stripe\Event::constructFrom(
            json_decode($payload, true)
        );
    } catch(\UnexpectedValueException $e) {
        http_response_code(400);
        exit();
    }

    $log->appendLog("Webhook Received: " . $event->type);
    $log->appendLog("Webhook Payload (Raw): " . $payload);

    try {
        if ($event->type == 'payment_intent.succeeded') {
            $paymentIntent = $event->data->object;
            $clientId = $paymentIntent->metadata->clientId ?? null;
            $amount = $paymentIntent->amount / 100;
            $currency = $paymentIntent->currency;
            
            if ($clientId) {
                $notes = "Pago procesado via Stripe PaymentIntent: " . $paymentIntent->id;
                $res = $service->registerPayment($clientId, $amount, $currency, $notes);
                $log->appendLog("Payment Register UCRM ($clientId) for PI {$paymentIntent->id}: " . ($res ? 'Success' : 'Fail'));
            } else {
                $log->appendLog("Warning: No clientId found in metadata for PI: " . $paymentIntent->id);
            }
        } 
        elseif ($event->type == 'customer_cash_balance_transaction.created') {
            $txn = $event->data->object;
            $log->appendLog("Processing Cash Balance Transaction: " . $txn->id);
            
            // Check if money was applied to a payment object
            if (isset($txn->applied_to_payment) && isset($txn->applied_to_payment->payment_intent)) {
                $piId = $txn->applied_to_payment->payment_intent;
                $log->appendLog("Transaction applied to PI: " . $piId);
                
                $paymentIntent = $service->getPaymentIntent($piId);
                
                if ($paymentIntent) {
                     $clientId = $paymentIntent->metadata->clientId ?? null;
                     // In cash balance txn, net_amount is what was received (negative for withdrawals, positive for deposits/applications)
                     // Usually it's negative when applied to a PI, so we take abs
                     $amount = abs($txn->net_amount) / 100;
                     $currency = $txn->currency;
                     
                     if ($clientId) {
                        $notes = "Pago via Transferencia (Cash Balance) aplicado a Intent: " . $piId . " (Txn: " . $txn->id . ")";
                        $res = $service->registerPayment($clientId, $amount, $currency, $notes);
                        $log->appendLog("Cash Balance Payment Register UCRM ($clientId) for PI $piId: " . ($res ? 'Success' : 'Fail'));
                     } else {
                        $log->appendLog("Error: No clientId found in metadata for PI: $piId");
                     }
                } else {
                    $log->appendLog("Error: Could not retrieve PaymentIntent $piId from Stripe");
                }
            } else {
                $log->appendLog("Info: Cash Balance Transaction " . $txn->id . " not directly applied to a PaymentIntent yet.");
            }
        }
    } catch (\Exception $e) {
        $log->appendLog("CRITICAL ERROR in Webhook Exception: " . $e->getMessage());
    }

    http_response_code(200);
    exit;
}

// --- VIEW (HTML) ---
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generar Payment Intent</title>
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            /* Light Mode Variables */
            --primary: #4f46e5; /* Indigo 600 */
            --primary-hover: #4338ca; /* Indigo 700 */
            --bg-body: #f3f4f6;
            --bg-card: #ffffff;
            --text-main: #111827;
            --text-muted: #6b7280;
            --border: #e5e7eb;
            --input-bg: #ffffff;
            --success-bg: #ecfdf5;
            --success-text: #065f46;
            --error-bg: #fef2f2;
            --error-text: #991b1b;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --radius: 16px;
            --transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        [data-theme="dark"] {
            /* Dark Mode Variables */
            --primary: #6366f1; /* Indigo 500 */
            --primary-hover: #818cf8; /* Indigo 400 */
            --bg-body: #111827; /* Gray 900 */
            --bg-card: #1f2937; /* Gray 800 */
            --text-main: #f9fafb; /* Gray 50 */
            --text-muted: #9ca3af; /* Gray 400 */
            --border: #374151; /* Gray 700 */
            --input-bg: #111827; /* Gray 900 */
            --success-bg: #064e3b;
            --success-text: #6ee7b7;
            --error-bg: #7f1d1d;
            --error-text: #fca5a5;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
            --shadow-md: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
        }

        * { box-sizing: border-box; outline: none; }
        
        body {
            font-family: 'Outfit', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-main);
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            transition: background-color var(--transition), color var(--transition);
        }

        .container {
            width: 100%;
            max-width: 550px;
            background: var(--bg-card);
            border-radius: var(--radius);
            box-shadow: var(--shadow-md);
            padding: 2.5rem;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
            position: relative;
            transition: background-color var(--transition), box-shadow var(--transition);
        }

        /* Dark Mode Toggle */
        .theme-toggle {
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 50%;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .theme-toggle:hover {
            color: var(--primary);
            background-color: rgba(99, 102, 241, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 0.5rem;
        }
        
        .header img {
            max-height: 70px;
            margin-bottom: 1.25rem;
            display: block;
            margin-left: auto;
            margin-right: auto;
            filter: drop-shadow(0 4px 6px rgba(0,0,0,0.1));
            border-radius: 16px;
        }

        .header h1 {
            font-size: 1.75rem;
            font-weight: 700;
            margin: 0;
            background: linear-gradient(135deg, var(--text-main) 0%, var(--text-muted) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .header p {
            color: var(--text-muted);
            margin: 0.75rem 0 0;
            font-size: 0.95rem;
            line-height: 1.5;
        }

        .form-group {
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 0.6rem;
        }

        label {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--text-main);
            letter-spacing: 0.02em;
        }

        .input-wrapper {
            position: relative;
        }

        input[type="text"], input[type="number"] {
            width: 100%;
            padding: 0.875rem 1rem;
            border: 1px solid var(--border);
            border-radius: 12px;
            font-size: 1rem;
            font-family: inherit;
            background-color: var(--input-bg);
            color: var(--text-main);
            transition: all 0.2s;
        }

        input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.15);
        }

        input::placeholder {
            color: var(--text-muted);
            opacity: 0.7;
        }

        .search-icon {
            position: absolute;
            right: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
            pointer-events: none;
            font-size: 1.1rem;
        }

        /* Predictions Dropdown */
        .predictions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            margin-top: 6px;
            max-height: 260px;
            overflow-y: auto;
            z-index: 20;
            display: none;
            box-shadow: var(--shadow-md);
            overflow: hidden;
        }

        .prediction-item {
            padding: 1rem;
            cursor: pointer;
            border-bottom: 1px solid var(--border);
            transition: background 0.15s;
        }

        .prediction-item:last-child {
            border-bottom: none;
        }

        .prediction-item:hover {
            background-color: rgba(99, 102, 241, 0.05);
        }

        .prediction-item .name {
            font-weight: 600;
            display: block;
            color: var(--text-main);
        }

        .prediction-item .address {
            font-size: 0.85rem;
            color: var(--text-muted);
            display: block;
            margin-top: 4px;
        }

        /* Client Details Section */
        #clientDetails {
            border-top: 1px solid var(--border);
            padding-top: 1.5rem;
            display: none;
            animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.25rem 1rem;
            margin-bottom: 2rem;
            font-size: 0.95rem;
            background: rgba(99, 102, 241, 0.03); 
            padding: 1.5rem;
            border-radius: 12px;
            border: 1px solid var(--border);
        }
        
        .info-item .label {
            color: var(--text-muted);
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 4px;
            font-weight: 600;
        }
        
        .info-item .value {
            font-weight: 600;
            color: var(--text-main);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 1rem;
            background-color: var(--primary);
            color: #ffffff;
            font-weight: 600;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 1rem;
            letter-spacing: 0.01em;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .btn:hover {
            background-color: var(--primary-hover);
            transform: translateY(-1px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.15);
        }
        
        .btn:active {
            transform: translateY(0);
        }

        .btn:disabled {
            background-color: var(--border);
            color: var(--text-muted);
            cursor: not-allowed;
            box-shadow: none;
            transform: none;
        }

        /* Modal */
        .modal-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.6);
            backdrop-filter: blur(4px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 50;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }

        .modal-overlay.active {
            opacity: 1;
            pointer-events: auto;
        }

        .modal {
            background: var(--bg-card);
            width: 90%;
            max-width: 420px;
            padding: 2.5rem;
            border-radius: 20px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.25);
            text-align: center;
            transform: scale(0.9);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }
        
        .modal-overlay.active .modal {
            transform: scale(1);
        }

        .modal h3 {
            margin-top: 0;
            color: var(--text-main);
            font-size: 1.5rem;
        }
        
        .modal p {
            color: var(--text-muted);
            margin-bottom: 2rem;
            line-height: 1.6;
        }
        
        .modal strong {
            color: var(--primary);
        }

        .modal-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-secondary {
            background: transparent;
            border: 1px solid var(--border);
            color: var(--text-main);
        }
        
        .btn-secondary:hover {
            background: rgba(0,0,0,0.05);
            border-color: var(--text-muted);
        }
        
        [data-theme="dark"] .btn-secondary:hover {
            background: rgba(255,255,255,0.05);
        }

        /* Alerts */
        .alert {
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            font-size: 0.95rem;
            display: none;
            border: 1px solid transparent;
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
        }
        
        .alert.success {
            background-color: var(--success-bg);
            color: var(--success-text);
            border-color: rgba(6, 95, 70, 0.1);
        }
        
        .alert.error {
            background-color: var(--error-bg);
            color: var(--error-text);
            border-color: rgba(153, 27, 27, 0.1);
        }
        
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

    </style>
</head>
<body>

<div class="container">
    <button class="theme-toggle" id="themeToggle" title="Cambiar tema">
        <!-- Sun Icon -->
        <svg id="sunIcon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>
        <!-- Moon Icon -->
        <svg id="moonIcon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
    </button>

    <div class="header">
        <img src="?action=image&file=logo.png" alt="Logo">
        <h1>Generar Intención de Pago</h1>
        <p>Busca un cliente para generar un cobro vía Stripe</p>
    </div>

    <!-- Alert Box -->
    <div id="alertBox" class="alert" style="display: none;"></div>

    <!-- Search Section -->
    <div class="form-group">
        <label for="clientSearch">Buscar Cliente</label>
        <div class="input-wrapper">
            <input type="text" id="clientSearch" placeholder="Nombre, ID, Dirección..." autocomplete="off">
            <span class="search-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
            </span>
            <div id="predictions" class="predictions"></div>
        </div>
    </div>

    <!-- Result & Form Section -->
    <div id="clientDetails">
        <div class="info-grid">
            <div class="info-item">
                <div class="label">Nombre</div>
                <div class="value" id="resName">--</div>
            </div>
            <div class="info-item">
                <div class="label">ID Cliente</div>
                <div class="value" id="resId">--</div>
            </div>
            <div class="info-item">
                <div class="label">Stripe Customer ID</div>
                <div class="value" id="resStripeId">--</div>
            </div>
            <div class="info-item">
                <div class="label">Email</div>
                <div class="value" id="resEmail">--</div>
            </div>
             <div class="info-item">
                <div class="label">Saldo Pendiente</div>
                <div class="value" id="resOutstanding">--</div>
            </div>
        </div>

        <div class="form-group">
            <label for="amount">Monto a cobrar (MXN)</label>
            <input type="number" id="amount" placeholder="0.00" min="10" step="0.01">
            <small style="color: var(--text-muted); font-size: 0.8rem;">Mínimo $10.00 MXN</small>
        </div>

        <button id="btnGenerate" class="btn" disabled>
            Generar Intención de Pago
        </button>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmModal" class="modal-overlay">
    <div class="modal">
        <h3>Confirmar Cobro</h3>
        <p>¿Estás seguro de generar una intención de pago por <strong id="modalAmount"></strong> al cliente <strong id="modalClient"></strong>?</p>
        <div class="modal-actions">
            <button id="btnCancel" class="btn btn-secondary">Cancelar</button>
            <button id="btnConfirm" class="btn">Confirmar</button>
        </div>
    </div>
</div>

<!-- Bank Transfer Instructions Modal -->
<div id="bankParamsModal" class="modal-overlay">
    <div class="modal" style="max-width: 500px; text-align: left;">
        <h3 style="text-align: center; margin-bottom: 0.5rem;">Instrucciones de Pago</h3>
        <p style="text-align: center; margin-bottom: 1.5rem;">Realiza la transferencia con los siguientes datos:</p>
        
        <div style="background: var(--bg-body); padding: 1.5rem; border-radius: 12px; margin-bottom: 2rem; border: 1px solid var(--border);">
            <div style="margin-bottom: 0.75rem; display: flex; justify-content: space-between;">
                <span style="color: var(--text-muted);">Monto:</span>
                <strong id="btAmount" style="color: var(--text-main);"></strong>
            </div>
            <div style="margin-bottom: 0.75rem; display: flex; justify-content: space-between;">
                <span style="color: var(--text-muted);">Banco:</span>
                <strong id="btBank" style="color: var(--text-main);"></strong>
            </div>
            <div style="margin-bottom: 0.75rem;">
                <span style="color: var(--text-muted); display: block; margin-bottom: 4px;">CLABE:</span>
                <div style="display: flex; gap: 8px;">
                    <strong id="btClabe" style="font-family: monospace; font-size: 1.2rem; color: var(--text-main); letter-spacing: 1px;"></strong>
                </div>
            </div>
            <!-- Not always present but good to have
            <div>
                <span style="color: var(--text-muted);">Referencia:</span>
                <strong id="btRef"></strong>
            </div> 
            -->
        </div>

        <div class="modal-actions" style="justify-content: center;">
            <button id="btnCloseBank" class="btn">Cerrar</button>
        </div>
    </div>
</div>

<script>
    const searchInput = document.getElementById('clientSearch');
    const predictionsDiv = document.getElementById('predictions');
    const detailsDiv = document.getElementById('clientDetails');
    const amountInput = document.getElementById('amount');
    const btnGenerate = document.getElementById('btnGenerate');
    const alertBox = document.getElementById('alertBox');
    const confirmModal = document.getElementById('confirmModal');
    
    // Theme Toggle Logic
    const themeToggle = document.getElementById('themeToggle');
    const sunIcon = document.getElementById('sunIcon');
    const moonIcon = document.getElementById('moonIcon');
    const htmlEl = document.documentElement;

    // Check saved theme or pref
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        htmlEl.setAttribute('data-theme', 'dark');
        sunIcon.style.display = 'block';
        moonIcon.style.display = 'none';
    } else {
        htmlEl.removeAttribute('data-theme');
        sunIcon.style.display = 'none';
        moonIcon.style.display = 'block';
    }

    themeToggle.addEventListener('click', () => {
        if (htmlEl.hasAttribute('data-theme')) {
            htmlEl.removeAttribute('data-theme');
            localStorage.setItem('theme', 'light');
            sunIcon.style.display = 'none';
            moonIcon.style.display = 'block';
        } else {
            htmlEl.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
            sunIcon.style.display = 'block';
            moonIcon.style.display = 'none';
        }
    });

    let debounceTimer;
    let selectedClient = null;

    // --- Search Logic ---
    searchInput.addEventListener('input', (e) => {
        const query = e.target.value;
        if (query.length < 2) {
            predictionsDiv.style.display = 'none';
            return;
        }
        
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            fetch(`?action=search&q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    renderPredictions(data);
                });
        }, 300);
    });

    const renderPredictions = (data) => {
        predictionsDiv.innerHTML = '';
        if (data.length === 0) {
            predictionsDiv.style.display = 'none';
            return;
        }

        data.forEach(client => {
            const div = document.createElement('div');
            div.className = 'prediction-item';
            div.innerHTML = `
                <span class="name">${client.clientType == 2 ? client.companyName : client.firstName + ' ' + client.lastName} (ID: ${client.id})</span>
                <span class="address">${client.fullAddress || 'Sin dirección'}</span>
            `;
            div.onclick = () => selectClient(client.id);
            predictionsDiv.appendChild(div);
        });

        predictionsDiv.style.display = 'block';
    };

    const selectClient = (id) => {
        predictionsDiv.style.display = 'none';
        searchInput.value = '';

        fetch(`?action=details&id=${id}`)
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    showAlert('error', data.error);
                    return;
                }
                selectedClient = data;
                document.getElementById('resName').textContent = data.fullName;
                document.getElementById('resId').textContent = data.id;
                document.getElementById('resStripeId').textContent = data.stripeCustomerId || 'No disponible';
                document.getElementById('resEmail').textContent = data.email;
                document.getElementById('resOutstanding').textContent = '$' + Number(data.accountOutstanding).toFixed(2);
                
                // Show details
                detailsDiv.style.display = 'block';
                
                // Validate Stripe ID for button
                if (!data.stripeCustomerId) {
                     showAlert('error', 'El cliente no tiene vinculado un Clave Stripe Customer ID. No se puede generar el pago.');
                     amountInput.disabled = true;
                     btnGenerate.disabled = true;
                } else {
                    amountInput.disabled = false;
                    checkAmount();
                    alertBox.style.display = 'none';
                }
            });
    };

    // --- Validation Logic ---
    amountInput.addEventListener('input', checkAmount);

    function checkAmount() {
        const val = parseFloat(amountInput.value);
        if (selectedClient && selectedClient.stripeCustomerId && val >= 10) {
            btnGenerate.disabled = false;
        } else {
            btnGenerate.disabled = true;
        }
    }

    // --- Generation Flow ---
    btnGenerate.addEventListener('click', () => {
        const amount = parseFloat(amountInput.value);
        document.getElementById('modalAmount').textContent = '$' + amount.toFixed(2) + ' MXN';
        document.getElementById('modalClient').textContent = selectedClient.fullName;
        confirmModal.classList.add('active');
    });

    document.getElementById('btnCancel').onclick = () => {
        confirmModal.classList.remove('active');
    };

    document.getElementById('btnConfirm').onclick = () => {
        confirmModal.classList.remove('active');
        const amount = parseFloat(amountInput.value);
        
        // Show loading state
        const originalText = btnGenerate.innerHTML;
        btnGenerate.disabled = true;
        btnGenerate.innerHTML = '<span class="spinner"></span> Procesando...';

        fetch(`?action=create_intent`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                clientId: selectedClient.id,
                amount: amount,
                stripeCustomerId: selectedClient.stripeCustomerId
            })
        })
        .then(res => res.json())
        .then(data => {
            btnGenerate.innerHTML = originalText;
            btnGenerate.disabled = false;

            if (data.success) {
                // Check if requires_action (Bank Transfer needed)
                if (data.status === 'requires_action' && data.next_action) {
                    const instructions = data.next_action.display_bank_transfer_instructions;
                    if (instructions) {
                        document.getElementById('btAmount').textContent = '$' + data.amount.toFixed(2) + ' ' + data.currency.toUpperCase();
                        
                        const financialAddress = instructions.financial_addresses && instructions.financial_addresses[0];
                        
                        let clabe = 'N/A';
                        let bankName = 'STP (Sistema de Transferencias y Pagos)';

                        // Priority: Custom Attribute from UCRM > Stripe Response
                        if (selectedClient && selectedClient.clabeInterbancaria) {
                            clabe = selectedClient.clabeInterbancaria;
                        } else if (financialAddress) {
                             if (financialAddress.spei) {
                                clabe = financialAddress.spei.clabe;
                                bankName = financialAddress.spei.bank_name || bankName;
                            } else if (financialAddress.bank_transfer) {
                                clabe = financialAddress.bank_transfer.clabe || financialAddress.bank_transfer.iban || 'N/A';
                                bankName = financialAddress.bank_transfer.bank_name || bankName;
                            }
                        }
                        
                        document.getElementById('btBank').textContent = bankName; 
                        document.getElementById('btClabe').textContent = clabe;
                        
                        const bankModal = document.getElementById('bankParamsModal');
                        bankModal.classList.add('active');
                        
                        // Close Handler
                        document.getElementById('btnCloseBank').onclick = () => {
                            bankModal.classList.remove('active');
                            // Now reset form
                            detailsDiv.style.display = 'none';
                            searchInput.value = '';
                            amountInput.value = '';
                            selectedClient = null;
                        };
                    } else {
                         // Fallback if no instructions found but requires action
                         showAlert('success', 'Intención creada (requires_action). ID: ' + data.id);
                    }
                } else {
                    // Succeeded immediatley or other status
                    showAlert('success', 'Intención de pago creada correctamente. ID: ' + data.id + ' (Estado: ' + data.status + ')');
                    // Reset form
                    detailsDiv.style.display = 'none';
                    searchInput.value = '';
                    amountInput.value = '';
                    selectedClient = null;
                }
            } else {
                showAlert('error', 'Error al crear intención: ' + (data.error || 'Desconocido'));
            }
        })
        .catch(err => {
            btnGenerate.innerHTML = originalText;
            btnGenerate.disabled = false;
            showAlert('error', 'Error de conexión: ' + err.message);
        });
    };

    function showAlert(type, msg) {
        alertBox.className = `alert ${type}`;
        alertBox.textContent = msg;
        alertBox.style.display = 'flex';
    }

    // Close predictions on click outside
    document.addEventListener('click', (e) => {
        if (!searchInput.contains(e.target) && !predictionsDiv.contains(e.target)) {
            predictionsDiv.style.display = 'none';
        }
    });

</script>
</body>
</html>
