<?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; 
$apiUcrmKey = $config['apiTokenUcrm'] ?? '';
$stripeApiKey = $config['apiTokenStripe'] ?? '';

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

// --- 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;
}

// --- 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=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #006aff;
            --primary-dark: #0056cc;
            --bg-body: #f4f6f8;
            --bg-card: #ffffff;
            --text-main: #1f2937;
            --text-muted: #6b7280;
            --border: #e5e7eb;
            --success: #10b981;
            --danger: #ef4444;
            --radius: 12px;
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

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

        .container {
            width: 100%;
            max-width: 600px;
            background: var(--bg-card);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            padding: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .header {
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .header img {
            max-height: 60px;
            margin-bottom: 1rem;
            display: block;
            margin-left: auto;
            margin-right: auto;
        }

        .header h1 {
            font-size: 1.5rem;
            font-weight: 700;
            margin: 0;
            color: var(--text-main);
        }
        
        .header p {
            color: var(--text-muted);
            margin: 0.5rem 0 0;
        }

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

        label {
            font-weight: 500;
            font-size: 0.9rem;
            color: var(--text-main);
        }

        .input-wrapper {
            position: relative;
        }

        input[type="text"], input[type="number"] {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 1rem;
            font-family: inherit;
            transition: border-color 0.2s, box-shadow 0.2s;
        }

        input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(0, 106, 255, 0.1);
        }

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

        /* Predictions Dropdown */
        .predictions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid var(--border);
            border-radius: 8px;
            margin-top: 4px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 10;
            display: none;
            box-shadow: var(--shadow);
        }

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

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

        .prediction-item:hover {
            background-color: #f9fafb;
        }

        .prediction-item .name {
            font-weight: 600;
            display: block;
        }

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

        /* Client Details Section */
        #clientDetails {
            border-top: 1px solid var(--border);
            padding-top: 1.5rem;
            display: none;
            animation: fadeIn 0.3s ease-out;
        }

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

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 1.5rem;
            font-size: 0.9rem;
        }
        
        .info-item .label {
            color: var(--text-muted);
            font-size: 0.8rem;
            margin-bottom: 2px;
        }
        
        .info-item .value {
            font-weight: 500;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 0.875rem;
            background-color: var(--primary);
            color: white;
            font-weight: 600;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s, transform 0.1s;
            font-size: 1rem;
        }

        .btn:hover {
            background-color: var(--primary-dark);
        }
        
        .btn:active {
            transform: scale(0.99);
        }

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

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

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

        .modal {
            background: white;
            width: 90%;
            max-width: 400px;
            padding: 2rem;
            border-radius: var(--radius);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
            text-align: center;
            transform: scale(0.95);
            transition: transform 0.2s;
        }
        
        .modal-overlay.active .modal {
            transform: scale(1);
        }

        .modal h3 {
            margin-top: 0;
        }

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

        .btn-secondary {
            background: white;
            border: 1px solid var(--border);
            color: var(--text-main);
        }
        
        .btn-secondary:hover {
            background: #f9fafb;
        }

        /* Alerts */
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-size: 0.9rem;
            display: none;
        }
        
        .alert.success {
            background-color: #ecfdf5;
            color: #065f46;
            border: 1px solid #d1fae5;
        }
        
        .alert.error {
            background-color: #fef2f2;
            color: #991b1b;
            border: 1px solid #fee2e2;
        }
        
        .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: 8px;
        }

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

    </style>
</head>
<body>

<div class="container">
    <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"></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">🔍</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>

<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');
    
    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 = ''; // Or keep name? "Se limpia el formulario" usually refers to after success, but search box usually clears or shows selected. User said: "se seleccione el cliente deseado... se deben cargar sus datos... y ahí estará el formulario".

        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) {
                showAlert('success', 'Intención de pago creada correctamente. ID: ' + data.id);
                // 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 = 'block';
    }

    // 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>
