<div class="row mb-4">
    <div class="col-12">
        <h2><i class="bi bi-cash-coin"></i> Finanzas</h2>
        <p class="text-muted">Gestión de gastos y conceptos especiales</p>
    </div>
</div>

<ul class="nav nav-tabs mb-4" id="financeTabs">
    <li class="nav-item">
        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#concepts">
            <i class="bi bi-collection"></i> Conceptos Especiales
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#expenses">
            <i class="bi bi-receipt"></i> Gastos
        </button>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane fade show active" id="concepts">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Conceptos Especiales</h5>
                <?php if (Auth::isCapturist()): ?>
                    <button id="newConceptBtn" class="btn btn-primary btn-sm">
                        <i class="bi bi-plus"></i> Nuevo Concepto
                    </button>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php foreach ($concepts as $concept): 
                        $status = CollectionConcept::getCollectionStatus($concept['id']);
                    ?>
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                 <div class="card-body">
                                     <h6 class="card-title">[ID: <?= $concept['id'] ?>] <?= htmlspecialchars($concept['name']) ?></h6>
                                     <p class="card-text small text-muted"><?= htmlspecialchars($concept['description'] ?? '') ?></p>
                                    <div class="mb-2">
                                        <small>Monto Total:</small> <strong>$<?= number_format($concept['total_amount'], 2) ?></strong>
                                    </div>
                                    <div class="mb-2">
                                        <small>Monto por casa:</small> <strong>$<?= number_format($concept['amount_per_house'], 2) ?></strong>
                                    </div>
                                    <div class="progress mb-2" style="height: 20px;">
                                        <div class="progress-bar bg-success" style="width: <?= $status['percentage'] ?>%">
                                            <?= $status['percentage'] ?>%
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">Recaudado:</small> <strong>$<?= number_format($status['total_collected'], 2) ?></strong>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">Gastado:</small> <strong class="text-danger">$<?= number_format($status['total_expenses'], 2) ?></strong>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">Balance Neto:</small> <strong class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">$<?= number_format($status['balance'], 2) ?></strong>
                                    </div>
                                    <div class="mt-2">
                                        <a href="/dashboard.php?page=concept_view&id=<?= $concept['id'] ?>" class="btn btn-sm btn-outline-primary">
                                            Ver Detalles
                                         </a>
                                         <?php if (Auth::isCapturist()): ?>
                                        <button class="btn btn-sm btn-outline-secondary btn-edit-concept" data-concept-id="<?= $concept['id'] ?>">
                                            <i class="bi bi-pencil"></i> Editar
                                        </button>
                                        <?php endif; ?>
                                        <?php if (Auth::isAdmin()): ?>
                                        <button class="btn btn-sm btn-outline-danger btn-delete-concept" data-concept-id="<?= $concept['id'] ?>">
                                            <i class="bi bi-trash"></i> Eliminar
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="tab-pane fade" id="expenses">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Gastos Registrados</h5>
                <?php if (Auth::isCapturist()): ?>
                    <button id="newExpenseBtn" class="btn btn-primary btn-sm">
                        <i class="bi bi-plus"></i> Nuevo Gasto
                    </button>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                         <thead>
                            <tr>
                                <th>Fecha</th>
                                <th>Descripción</th>
                                <th>Conceptos</th>
                                <th>Categoría</th>
                                <th>Comprobante</th>
                                 <th>Monto</th>
                                 <th>Acciones</th>
                             </tr>
                         </thead>
                        <tbody>
                            <?php foreach ($expenses as $expense):
                                $expenseConcepts = Expense::getConcepts($expense['id']);
                            ?>
                                <tr>
                                    <td><?= date('d/m/Y', strtotime($expense['expense_date'])) ?></td>
                                    <td><?= htmlspecialchars($expense['description']) ?></td>
                                    <td>
                                        <?php if (!empty($expenseConcepts)): ?>
                                            <div>
                                                <?php foreach ($expenseConcepts as $ec): ?>
                                                    <span class="badge bg-info" title="Monto: $<?= number_format($ec['amount'], 2) ?>">
                                                        <?= htmlspecialchars($ec['concept_name']) ?>
                                                    </span>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted">Sin concepto</span>
                                        <?php endif; ?>
                                    </td>
                                     <td><?= htmlspecialchars($expense['category'] ?? '-') ?></td>
                                     <td>
                                         <?php if (!empty($expense['receipt_path'])): ?>
                                             <a href="<?= htmlspecialchars($expense['receipt_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info">
                                                 <i class="bi bi-eye"></i> Ver
                                             </a>
                                         <?php else: ?>
                                             <span class="text-muted">-</span>
                                         <?php endif; ?>
                                     </td>
                                     <td class="text-end">$<?= number_format($expense['amount'], 2) ?></td>
                                    <td>
                                        <?php if (Auth::isCapturist()): ?>
                                        <button class="btn btn-sm btn-outline-primary btn-edit-expense" data-expense-id="<?= $expense['id'] ?>">
                                            <i class="bi bi-pencil"></i> Editar
                                        </button>
                                        <?php endif; ?>
                                        <?php if (Auth::isAdmin()): ?>
                                        <button class="btn btn-sm btn-danger btn-delete-expense" data-expense-id="<?= $expense['id'] ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if (Auth::isCapturist()): ?>
<div class="modal fade" id="conceptModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="conceptModalTitle">Nuevo Concepto Especial</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="conceptForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="conceptIdInput">
                    <div class="mb-3">
                        <label class="form-label">Nombre del Concepto</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Descripción</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Monto Total a Recaudar ($)</label>
                        <input type="number" step="0.01" class="form-control" name="total_amount" id="totalAmountInput" placeholder="Ej: 20000.00">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Monto por Casa ($)</label>
                        <input type="number" step="0.01" class="form-control" name="amount_per_house" id="perHouseAmountInput" placeholder="Ej: 200.00">
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Fecha del Concepto</label>
                            <input type="date" class="form-control" name="concept_date" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Fecha de Vencimiento (opcional)</label>
                            <input type="date" class="form-control" name="due_date">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Categoría</label>
                        <input type="text" class="form-control" name="category" placeholder="Ej: Mantenimiento, Mejora">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary" id="conceptFormSubmitBtn">Guardar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="expenseModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="expenseModalTitle">Registrar Gasto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="expenseForm">
                <input type="hidden" name="id" id="expenseIdInput">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Descripción</label>
                        <input type="text" class="form-control" name="description" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Monto del Gasto</label>
                            <input type="number" step="0.01" class="form-control" name="amount" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Fecha</label>
                            <input type="date" class="form-control" name="expense_date" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Comprobante (Imagen o PDF)</label>
                        <input type="file" class="form-control" name="receipt" accept=".jpg,.jpeg,.png,.pdf" id="expenseReceiptInput">
                        <small class="text-muted" id="existingReceiptHint"></small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Asignar Gasto a Conceptos</label>
                        <div id="expense-concept-allocations" class="p-2 border rounded" style="max-height: 250px; overflow-y: auto;">
                            <?php if (empty($concepts)): ?>
                                <p class="text-muted">No hay conceptos especiales para asignar.</p>
                            <?php else: ?>
                                <?php foreach ($concepts as $c): 
                                    $status = CollectionConcept::getCollectionStatus($c['id']);
                                ?>
                                    <div class="allocation-row mb-2">
                                        <div class="form-check">
                                            <input class="form-check-input concept-checkbox" type="checkbox" value="<?= $c['id'] ?>" id="alloc_concept_<?= $c['id'] ?>">
                                            <label class="form-check-label" for="alloc_concept_<?= $c['id'] ?>">
                                                <?= htmlspecialchars($c['name']) ?>
                                                <small class="text-success">(Balance: $<?= number_format($status['balance'], 2) ?>)</small>
                                            </label>
                                        </div>
                                        <div class="input-group input-group-sm mt-1">
                                            <span class="input-group-text">$</span>
                                            <input type="number" step="0.01" class="form-control allocation-amount" name="allocations[<?= $c['id'] ?>]" placeholder="0.00" disabled>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="alert alert-secondary mt-2">
                        <div class="d-flex justify-content-between"><span>Monto del Gasto:</span> <strong id="summary-expense-amount">$0.00</strong></div>
                        <div class="d-flex justify-content-between"><span>Total Asignado:</span> <strong id="summary-allocated-amount">$0.00</strong></div>
                        <hr class="my-1">
                        <div class="d-flex justify-content-between fw-bold"><span>Restante:</span> <strong id="summary-remaining-amount">$0.00</strong></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Categoría</label>
                        <input type="text" class="form-control" name="category" placeholder="Ej: Mantenimiento, Limpieza">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar Gasto</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (!<?= Auth::isCapturist() ? 'true' : 'false' ?>) return;

    const expenseModalEl = document.getElementById('expenseModal');
    if (!expenseModalEl) return;

    // --- Concept Modal ---
    const conceptModalEl = document.getElementById('conceptModal');
    const conceptModal = conceptModalEl ? new bootstrap.Modal(conceptModalEl) : null;
    const conceptForm = document.getElementById('conceptForm');
    
    const openConceptModal = (id = null) => {
        conceptForm.reset();
        conceptForm.elements['id'].value = '';
        if (id) {
            conceptModalEl.querySelector('#conceptModalTitle').textContent = 'Editar Concepto Especial';
            conceptModalEl.querySelector('#conceptFormSubmitBtn').textContent = 'Guardar Cambios';
            fetch(`/dashboard.php?page=finanzas&action=get_concept&id=${id}`).then(r => r.json()).then(res => {
                if (res.success && res.data) {
                    const c = res.data;
                    conceptForm.elements['id'].value = c.id;
                    conceptForm.elements['name'].value = c.name || '';
                    conceptForm.elements['description'].value = c.description || '';
                    conceptForm.elements['total_amount'].value = c.total_amount || '';
                    conceptForm.elements['amount_per_house'].value = c.amount_per_house || '';
                    conceptForm.elements['concept_date'].value = c.concept_date || '';
                    conceptForm.elements['due_date'].value = c.due_date || '';
                    conceptForm.elements['category'].value = c.category || '';
                    conceptModal.show();
                } else {
                    Swal.fire('Error', res.message || 'No se pudo cargar el concepto.', 'error');
                }
            });
        } else {
            conceptModalEl.querySelector('#conceptModalTitle').textContent = 'Nuevo Concepto Especial';
            conceptModalEl.querySelector('#conceptFormSubmitBtn').textContent = 'Crear Concepto';
            conceptModal.show();
        }
    };

    const deleteConcept = (id) => {
        if (!<?= Auth::isAdmin() ? 'true' : 'false' ?>) {
            Swal.fire('Acceso Denegado', 'No tienes permisos para eliminar conceptos', 'error');
            return;
        }

        Swal.fire({
            title: '¿Eliminar Concepto?',
            text: 'Esta acción eliminará el concepto, sus pagos y asignaciones de gastos.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar'
        }).then(res => {
            if (res.isConfirmed) {
                fetch(`/dashboard.php?page=finanzas&action=delete_concept&id=${id}`, { method: 'GET' }).then(r => r.json()).then(data => {
                    if (data.success) {
                        Swal.fire('Eliminado', data.message, 'success').then(() => location.reload());
                    } else {
                        Swal.fire('Error', data.message, 'error');
                    }
                });
            }
        });
    };

    document.getElementById('newConceptBtn')?.addEventListener('click', () => openConceptModal());
    document.getElementById('concepts').addEventListener('click', e => {
        const editBtn = e.target.closest('.btn-edit-concept');
        if (editBtn) openConceptModal(editBtn.dataset.conceptId);
        const deleteBtn = e.target.closest('.btn-delete-concept');
        if (deleteBtn) deleteConcept(deleteBtn.dataset.conceptId);
    });

    conceptForm.addEventListener('submit', e => {
        e.preventDefault();
        const data = Object.fromEntries(new FormData(e.target).entries());
        data.total_amount = data.total_amount ? parseFloat(data.total_amount) : null;
        data.amount_per_house = data.amount_per_house ? parseFloat(data.amount_per_house) : null;
        fetch('/dashboard.php?page=finanzas&action=save_concept', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).then(r => r.json()).then(res => {
            if (res.success) {
                conceptModal.hide();
                Swal.fire('Éxito', res.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error', res.message || 'Error desconocido.', 'error');
            }
        });
    });

    // --- Expense Modal ---
    const expenseModal = new bootstrap.Modal(expenseModalEl);
    const expenseForm = document.getElementById('expenseForm');
    const expenseAmountInput = expenseForm.querySelector('input[name="amount"]');
    const allocationContainer = document.getElementById('expense-concept-allocations');

    const updateAllocationSummary = () => {
        const expenseAmount = parseFloat(expenseAmountInput.value) || 0;
        let allocatedAmount = 0;
        allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
            const amountInput = row.querySelector('.allocation-amount');
            if (!amountInput.disabled) {
                allocatedAmount += parseFloat(amountInput.value) || 0;
            }
        });
        const remainingAmount = expenseAmount - allocatedAmount;
        document.getElementById('summary-expense-amount').textContent = `$${expenseAmount.toFixed(2)}`;
        document.getElementById('summary-allocated-amount').textContent = `$${allocatedAmount.toFixed(2)}`;
        const remainingEl = document.getElementById('summary-remaining-amount');
        remainingEl.textContent = `$${remainingAmount.toFixed(2)}`;
        remainingEl.classList.toggle('text-danger', remainingAmount < 0 || (remainingAmount > 0 && allocatedAmount > 0));
    };

    document.getElementById('newExpenseBtn')?.addEventListener('click', () => {
        openExpenseModal();
    });

    const openExpenseModal = (id = null) => {
        expenseForm.reset();
        expenseForm.elements['id'].value = '';
        document.getElementById('existingReceiptHint').textContent = '';
        allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
            row.querySelector('.concept-checkbox').checked = false;
            const amountInput = row.querySelector('.allocation-amount');
            amountInput.value = '';
            amountInput.disabled = true;
        });
        updateAllocationSummary();

        if (id) {
            expenseModalEl.querySelector('#expenseModalTitle').textContent = 'Editar Gasto';
            fetch(`/dashboard.php?page=finanzas&action=get_expense&id=${id}`).then(r => r.json()).then(res => {
                if (res.success && res.data) {
                    const e = res.data;
                    expenseForm.elements['id'].value = e.id;
                    expenseForm.elements['description'].value = e.description || '';
                    expenseForm.elements['amount'].value = e.amount || '';
                    expenseForm.elements['expense_date'].value = e.expense_date || '';
                    expenseForm.elements['category'].value = e.category || '';

                    if (e.receipt_path) {
                        document.getElementById('existingReceiptHint').textContent = 'Comprobante existente: ' + e.receipt_path.split('/').pop();
                    }

                    // Load allocations
                    if (e.allocations && e.allocations.length > 0) {
                        allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
                            const checkbox = row.querySelector('.concept-checkbox');
                            const amountInput = row.querySelector('.allocation-amount');
                            const alloc = e.allocations.find(a => a.concept_id == checkbox.value);
                            if (alloc) {
                                checkbox.checked = true;
                                amountInput.value = alloc.amount;
                                amountInput.disabled = false;
                            }
                        });
                        updateAllocationSummary();
                    }

                    expenseModal.show();
                } else {
                    Swal.fire('Error', res.message || 'No se pudo cargar el gasto.', 'error');
                }
            });
        } else {
            expenseModalEl.querySelector('#expenseModalTitle').textContent = 'Registrar Gasto';
            expenseModal.show();
        }
    };

    expenseAmountInput.addEventListener('input', updateAllocationSummary);
    allocationContainer.addEventListener('change', e => {
        if (e.target.classList.contains('concept-checkbox')) {
            e.target.closest('.allocation-row').querySelector('.allocation-amount').disabled = !e.target.checked;
            if (!e.target.checked) e.target.closest('.allocation-row').querySelector('.allocation-amount').value = '';
        }
        updateAllocationSummary();
    });
     allocationContainer.addEventListener('input', e => {
        if (e.target.classList.contains('allocation-amount')) updateAllocationSummary();
    });

    expenseForm.addEventListener('submit', e => {
        e.preventDefault();

        const formData = new FormData(expenseForm);
        formData.append('id', expenseForm.elements['id'].value);
        formData.append('description', expenseForm.elements['description'].value);
        formData.append('amount', expenseForm.elements['amount'].value);
        formData.append('expense_date', expenseForm.elements['expense_date'].value);
        formData.append('category', expenseForm.elements['category'].value);

        const allocations = [];
        allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
            const checkbox = row.querySelector('.concept-checkbox');
            const amountInput = row.querySelector('.allocation-amount');
            if (checkbox.checked) {
                const amount = parseFloat(amountInput.value) || 0;
                if (amount > 0) {
                    allocations.push({ concept_id: checkbox.value, amount: amount });
                }
            }
        });

        formData.append('allocations', JSON.stringify(allocations));

        const allocatedTotal = allocations.reduce((sum, a) => sum + a.amount, 0);
        const expenseAmount = parseFloat(expenseForm.elements['amount'].value);

        if (allocations.length > 0 && Math.abs(expenseAmount - allocatedTotal) > 0.01) {
            Swal.fire('Error', 'El total asignado a los conceptos no coincide con el monto del gasto.', 'error');
            return;
        }

        Swal.fire({
            title: 'Guardando...',
            text: 'Procesando gasto y comprobante',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });

        fetch('/dashboard.php?page=finanzas&action=save_expense', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                expenseModal.hide();
                Swal.fire('Éxito', res.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error', res.message || 'Error desconocido.', 'error');
            }
        })
        .catch(error => {
            Swal.fire('Error', 'Error de conexión', 'error');
        });
    });
    
    // Delegate deleteExpense and editExpense events from main table
    document.getElementById('expenses')?.addEventListener('click', e => {
        const deleteBtn = e.target.closest('.btn-delete-expense');
        if(deleteBtn) deleteExpense(deleteBtn.dataset.expenseId);
        const editBtn = e.target.closest('.btn-edit-expense');
        if(editBtn) openExpenseModal(editBtn.dataset.expenseId);
    });

    const deleteExpense = (id) => {
        if (!<?= Auth::isAdmin() ? 'true' : 'false' ?>) {
            Swal.fire('Acceso Denegado', 'No tienes permisos para eliminar gastos', 'error');
            return;
        }

        Swal.fire({
            title: '¿Eliminar Gasto?',
            text: 'Esta acción no se puede deshacer.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar'
        }).then(res => {
            if (res.isConfirmed) {
                fetch(`/dashboard.php?page=finanzas&action=delete_expense&id=${id}`, { method: 'GET' }).then(r => r.json()).then(data => {
                    if (data.success) location.reload();
                });
            }
        });
    }
});
</script>
<?php endif; ?>