{{-- resources/views/admin/expense/create.blade.php --}}
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                    <span>Registrar Gasto</span>
                    <a href="{{ route('admin_fit.expense.index') }}" class="btn btn-sm btn-secondary">
                        <i class="bi bi-chevron-left"></i> Volver
                    </a>
                </div>
                <div class="card-body bg-white">
                    @if ($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form method="POST" action="{{ route('admin_fit.expense.store') }}" enctype="multipart/form-data" id="expenseForm">
                        @csrf

                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Fecha del Gasto <span class="text-danger">*</span></label>
                                <input type="date" name="expense_date" class="form-control is-required" value="{{ old('expense_date', date('Y-m-d')) }}" required>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Categoría <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <select name="category_id" class="form-select is-required" required>
                                        <option value="">Seleccione una categoría</option>
                                        @foreach($categories as $category)
                                            <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                                {{ $category->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#newCategoryModal">
                                        <i class="bi bi-plus"></i>
                                    </button>
                                </div>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Descripción <span class="text-danger">*</span></label>
                                <input type="text" name="description" class="form-control is-required" value="{{ old('description') }}" required maxlength="255">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Monto <span class="text-danger">*</span></label>
                                <input type="text" name="amount" class="form-control mountFormat is-required" value="{{ old('amount') }}" required>
                                <small class="text-muted">Tasa activa: {{ number_format($activeRate, 4, ',', '.') }}</small>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Método de Pago <span class="text-danger">*</span></label>
                                <select name="payment_method" class="form-select is-required" required>
                                    <option value="">Seleccione</option>
                                    <option value="efectivo" {{ old('payment_method') == 'efectivo' ? 'selected' : '' }}>Efectivo</option>
                                    <option value="transferencia" {{ old('payment_method') == 'transferencia' ? 'selected' : '' }}>Transferencia</option>
                                    <option value="tarjeta" {{ old('payment_method') == 'tarjeta' ? 'selected' : '' }}>Tarjeta</option>
                                    <option value="cheque" {{ old('payment_method') == 'cheque' ? 'selected' : '' }}>Cheque</option>
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Referencia</label>
                                <input type="text" name="reference" class="form-control" value="{{ old('reference') }}" maxlength="100">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Proveedor</label>
                                <div class="input-group">
                                    <select name="supplier_id" id="supplier_id" class="form-select">
                                        <option value="">Sin proveedor</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                                {{ $supplier->supplier_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <button type="button" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#quickSupplierModal">
                                        <i class="bi bi-plus-circle"></i> Nuevo
                                    </button>
                                </div>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Notas</label>
                                <textarea name="notes" class="form-control" rows="3" maxlength="500">{{ old('notes') }}</textarea>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Comprobante</label>
                                <input type="file" name="receipt" class="form-control" accept="image/*">
                                <small class="text-muted">Opcional. Formatos: JPG, PNG (máx 5MB)</small>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Estado</label>
                                <select name="status" class="form-select">
                                    <option value="pagado" {{ old('status', 'pagado') == 'pagado' ? 'selected' : '' }}>Pagado</option>
                                    <option value="pendiente" {{ old('status') == 'pendiente' ? 'selected' : '' }}>Pendiente</option>
                                    <option value="cancelado" {{ old('status') == 'cancelado' ? 'selected' : '' }}>Cancelado</option>
                                </select>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="submit" class="btn btn-success">Guardar Gasto</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-info text-white">Ayuda</div>
                <div class="card-body small bg-white">
                    <p class="mb-2"><strong>Categoría:</strong> Clasifica el tipo de gasto (servicios, insumos, etc.)</p>
                    <p class="mb-2"><strong>Monto:</strong> Usa formato 1.234,56 o 1234.56</p>
                    <p class="mb-2"><strong>Método de Pago:</strong> Cómo se realizó el pago</p>
                    <p class="mb-2"><strong>Comprobante:</strong> Sube una foto o escaneo del comprobante</p>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Modal para crear categoría rápida --}}
<div class="modal fade" id="newCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Nueva Categoría</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="quickCategoryForm">
                    <div class="mb-3">
                        <label class="form-label">Nombre <span class="text-danger">*</span></label>
                        <input type="text" id="quickCategoryName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Color</label>
                        <input type="color" id="quickCategoryColor" class="form-control form-control-color" value="#6c757d">
                    </div>
                    <div id="quickCategoryError" class="text-danger small d-none"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" id="saveQuickCategory" class="btn btn-primary">Crear</button>
            </div>
        </div>
    </div>
</div>



{{-- Modal para crear proveedor rápido (fuera del form principal) --}}
<div class="modal fade" id="quickSupplierModal" tabindex="-1" aria-labelledby="quickSupplierModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="quickSupplierModalLabel"><i class="bi bi-person-plus"></i> Crear proveedor rápido</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <form id="quickSupplierForm">
                    <div class="mb-3">
                        <label for="quick_supplier_name" class="form-label">Nombre del proveedor <span class="text-danger">*</span></label>
                        <input type="text" id="quick_supplier_name" class="form-control border-primary" maxlength="80" required autofocus>
                    </div>
                    <div id="quickSupplierError" class="text-danger small d-none"></div>
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle"></i> Crear y seleccionar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
    const supplierSelect = document.getElementById('supplier_id');
    
    // ==================== CREAR PROVEEDOR RÁPIDO ====================
    const quickSupplierForm = document.getElementById('quickSupplierForm');
    const quickSupplierName = document.getElementById('quick_supplier_name');
    const quickSupplierError = document.getElementById('quickSupplierError');
    
    if (quickSupplierForm) {
        quickSupplierForm.addEventListener('submit', async function(event) {
            event.preventDefault();
            
            if (quickSupplierError) {
                quickSupplierError.classList.add('d-none');
                quickSupplierError.textContent = '';
            }
            
            const supplierName = quickSupplierName?.value.trim();
            if (!supplierName) {
                if (quickSupplierError) {
                    quickSupplierError.textContent = 'Debes ingresar el nombre del proveedor.';
                    quickSupplierError.classList.remove('d-none');
                }
                return;
            }
            
            try {
                const response = await fetch('{{ route("admin_fit.supplier.quick_store") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    },
                    body: JSON.stringify({ supplier_name: supplierName })
                });
                
                const data = await response.json();
                
                if (!response.ok || !data.id) {
                    throw new Error(data.message || 'No se pudo crear el proveedor');
                }
                
                // Agregar la nueva opción al select
                const option = document.createElement('option');
                option.value = data.id;
                option.textContent = data.supplier_name;
                option.selected = true;
                
                if (supplierSelect) {
                    supplierSelect.appendChild(option);
                    supplierSelect.value = data.id;
                }
                
                // Limpiar el campo y cerrar el modal
                if (quickSupplierName) quickSupplierName.value = '';
                
                const modalElement = document.getElementById('quickSupplierModal');
                if (modalElement && window.bootstrap?.Modal) {
                    const modal = bootstrap.Modal.getInstance(modalElement);
                    if (modal) modal.hide();
                }
                
                // Mostrar mensaje de éxito
                if (typeof Swal !== 'undefined' && Swal.fire) {
                    Swal.fire({
                        title: 'Proveedor creado',
                        text: 'Proveedor disponible para seleccionar.',
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    });
                }
                
            } catch (error) {
                if (quickSupplierError) {
                    quickSupplierError.textContent = error.message || 'Error creando proveedor';
                    quickSupplierError.classList.remove('d-none');
                }
            }
        });
    }
    
    // ==================== CREAR CATEGORÍA RÁPIDA ====================
    const saveCategoryBtn = document.getElementById('saveQuickCategory');
    const categorySelect = document.querySelector('select[name="category_id"]');
    
    if (saveCategoryBtn && categorySelect) {
        saveCategoryBtn.addEventListener('click', async function() {
            const name = document.getElementById('quickCategoryName')?.value.trim();
            const color = document.getElementById('quickCategoryColor')?.value || '#6c757d';
            const errorDiv = document.getElementById('quickCategoryError');
            
            if (!name) {
                if (errorDiv) {
                    errorDiv.textContent = 'El nombre de la categoría es obligatorio.';
                    errorDiv.classList.remove('d-none');
                }
                return;
            }
            
            if (errorDiv) {
                errorDiv.classList.add('d-none');
                errorDiv.textContent = '';
            }
            
            try {
                const response = await fetch('{{ route("admin_fit.expense.categories.store") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    },
                    body: JSON.stringify({
                        name: name,
                        color: color,
                        is_active: true
                    })
                });
                
                const data = await response.json();
                
                if (!response.ok || !data.success) {
                    throw new Error(data.message || 'Error al crear la categoría');
                }
                
                // Agregar la nueva categoría al select
                const option = document.createElement('option');
                option.value = data.data.id;
                option.textContent = data.data.name;
                option.setAttribute('data-color', data.data.color);
                categorySelect.appendChild(option);
                categorySelect.value = data.data.id;
                
                // Cerrar modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('newCategoryModal'));
                if (modal) modal.hide();
                
                // Limpiar formulario
                if (document.getElementById('quickCategoryName')) document.getElementById('quickCategoryName').value = '';
                
                Swal.fire('Creada', 'Categoría creada correctamente', 'success');
                
            } catch (error) {
                if (errorDiv) {
                    errorDiv.textContent = error.message;
                    errorDiv.classList.remove('d-none');
                }
            }
        });
    }
    
    // ==================== VALIDACIÓN DEL FORMULARIO ====================
    const form = document.getElementById('expenseForm');
    if (form) {
        form.addEventListener('submit', function(event) {
            const amount = document.querySelector('input[name="amount"]')?.value;
            const categoryId = document.querySelector('select[name="category_id"]')?.value;
            const description = document.querySelector('input[name="description"]')?.value;
            const expenseDate = document.querySelector('input[name="expense_date"]')?.value;
            
            let errors = [];
            
            if (!expenseDate) errors.push('La fecha del gasto es obligatoria');
            if (!categoryId) errors.push('La categoría es obligatoria');
            if (!description || description.trim() === '') errors.push('La descripción es obligatoria');
            if (!amount || parseFloat(amount.replace(/\./g, '').replace(',', '.')) <= 0) errors.push('El monto debe ser mayor a cero');
            
            if (errors.length > 0) {
                event.preventDefault();
                if (typeof Swal !== 'undefined' && Swal.fire) {
                    Swal.fire('Error', errors.join('<br>'), 'error');
                } else {
                    alert(errors.join('\n'));
                }
            }
        });
    }
    
    // ==================== PREVISUALIZACIÓN DE IMAGEN ====================
    const receiptInput = document.querySelector('input[name="receipt"]');
    if (receiptInput) {
        receiptInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    // Puedes agregar una previsualización si lo deseas
                    console.log('Imagen cargada:', file.name);
                };
                reader.readAsDataURL(file);
            }
        });
    }
});
</script>
@endpush