<div class="row mb-4">
    <div class="col-12">
        <a href="/dashboard.php?page=finanzas" class="btn btn-outline-secondary mb-2">
            <i class="bi bi-arrow-left"></i> Volver a Finanzas
        </a>
        <h2><i class="bi bi-collection"></i> <?= htmlspecialchars($concept['name']) ?></h2>
        <p class="text-muted"><?= htmlspecialchars($concept['description'] ?? '') ?></p>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="card border-primary">
            <div class="card-body text-center">
                <h6 class="text-muted">Monto por Casa</h6>
                <h4 class="text-primary">$<?= number_format($concept['amount_per_house'], 2) ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-success">
            <div class="card-body text-center">
                <h6 class="text-muted">Recaudado</h6>
                <h4 class="text-success">$<?= number_format($status['total_collected'], 2) ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-danger">
            <div class="card-body text-center">
                <h6 class="text-muted">Gastado</h6>
                <h4 class="text-danger">$<?= number_format($status['total_expenses'], 2) ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card <?= $status['balance'] >= 0 ? 'border-success' : 'border-danger' ?>">
            <div class="card-body text-center">
                <h6 class="text-muted">Balance Neto</h6>
                <h4 class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">$<?= number_format($status['balance'], 2) ?></h4>
                <small class="text-muted">(Recaudado - Gastado)</small>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">Pagos por Casa</h5>
    </div>
    <div class="card-body">
        <?php if (empty($payments)): ?>
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i>
                No hay pagos inicializados para este concepto.
                <br><br>
                <?php if (Auth::isCapturist()): ?>
                    <button class="btn btn-primary" onclick="initializeConceptPayments()">
                        <i class="bi bi-plus-circle"></i> Inicializar Pagos
                    </button>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-sm table-hover">
                    <thead>
                        <tr>
                            <th>Casa</th>
                            <th>Propietario</th>
                            <th>Monto</th>
                            <th>Fecha de Pago</th>
                            <?php if (Auth::isCapturist()): ?>
                                <th>Acciones</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payments as $payment):
                            $cellClass = $payment['amount'] > 0 ? 'paid' : 'pending';
                        ?>
                            <tr data-payment-id="<?= $payment['id'] ?>" data-house-id="<?= $payment['house_id'] ?>">
                                <td><strong><?= $payment['house_number'] ?></strong></td>
                                <td><?= htmlspecialchars($payment['owner_name'] ?? '-') ?></td>
                                <td class="payment-cell <?= $cellClass ?>"
                                    data-amount="<?= $payment['amount'] ?>"
                                    <?= Auth::isCapturist() ? 'contenteditable="true"' : '' ?>>
                                    <?= $payment['amount'] > 0 ? '$' . number_format($payment['amount'], 2) : '-' ?>
                                </td>
                                <td><?= $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-' ?></td>
                                <?php if (Auth::isCapturist()): ?>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="saveConceptPayment(this)">
                                            <i class="bi bi-check"></i>
                                        </button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php
require_once __DIR__ . '/../../models/Expense.php';
$conceptExpenses = $db->fetchAll(
    "SELECT e.*, ec.amount as allocated_amount
     FROM expense_concept_collections ec
     JOIN expenses e ON ec.expense_id = e.id
     WHERE ec.concept_id = ?
     ORDER BY e.expense_date DESC",
    [$concept['id']]
);
?>

<div class="card mt-4">
    <div class="card-header">
        <h5 class="card-title mb-0">Gastos Asociados</h5>
    </div>
    <div class="card-body">
        <?php if (!empty($conceptExpenses)): ?>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Descripción</th>
                            <th>Categoría</th>
                            <th>Asignado</th>
                            <th>Total Gasto</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($conceptExpenses as $exp): ?>
                            <tr>
                                <td><?= date('d/m/Y', strtotime($exp['expense_date'])) ?></td>
                                <td><?= htmlspecialchars($exp['description']) ?></td>
                                <td><?= htmlspecialchars($exp['category'] ?? '-') ?></td>
                                <td class="text-end text-info">$<?= number_format($exp['allocated_amount'], 2) ?></td>
                                <td class="text-end">$<?= number_format($exp['amount'], 2) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-secondary">
                            <th colspan="3" class="text-end">Total:</th>
                            <th class="text-end text-danger">$<?= number_format($status['total_expenses'], 2) ?></th>
                            <th>-</th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php else: ?>
            <p class="text-muted mb-0">No hay gastos asociados a este concepto.</p>
        <?php endif; ?>
    </div>
</div>

<script>
const conceptId = '<?= $concept['id'] ?>';

function initializeConceptPayments() {
    console.log('Inicializando pagos...');
    console.log('Concept ID:', conceptId);

    if (typeof Swal === 'undefined') {
        alert('Error: SweetAlert no está cargado');
        return;
    }

    Swal.fire({
        title: '¿Inicializar pagos?',
        text: 'Esto creará registros de pago para todas las casas activas con monto $0.00. ¿Continuar?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Sí, inicializar',
        confirmButtonColor: '#3085d6',
        cancelButtonText: 'Cancelar'
    }).then(function(result) {
        console.log('Resultado del sweetalert:', result);

        if (result.isConfirmed) {
            console.log('Iniciando fetch...');
            console.log('URL:', '/api/initialize_concept_payments.php?concept_id=' + conceptId);

            fetch('/api/initialize_concept_payments.php?concept_id=' + conceptId)
                .then(function(r) {
                    console.log('Respuesta del servidor:', r);
                    return r.json();
                })
                .then(function(data) {
                    console.log('Datos recibidos:', data);
                    if (data.success) {
                        Swal.fire('Éxito', data.message, 'success').then(function() {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error', data.message, 'error');
                    }
                })
                .catch(function(error) {
                    console.error('Error:', error);
                    Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
                });
        }
    });
}

<?php if (Auth::isCapturist()): ?>
document.querySelectorAll('.payment-cell[contenteditable="true"]').forEach(function(cell) {
    cell.addEventListener('focus', function() {
        this.classList.add('editing');
    });

    cell.addEventListener('blur', function() {
        this.classList.remove('editing');
    });

    cell.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
        }
    });
});

function saveConceptPayment(btn) {
    const row = btn.closest('tr');
    const cell = row.querySelector('.payment-cell');
    const houseId = row.dataset.houseId;
    const value = cell.textContent.trim();
    const amount = parseFloat(value.replace(/[^0-9.-]+/g, '')) || 0;

    cell.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

    fetch('/api/save_concept_payment.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            concept_id: '<?= $concept['id'] ?>',
            house_id: houseId,
            amount: amount
        })
    })
    .then(function(r) {
        return r.json();
    })
    .then(function(data) {
        if (data.success) {
            location.reload();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    });
}
<?php endif; ?>
</script>
