<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 id="init-payments-btn" class="btn btn-primary">
                        <i class="bi bi-plus-circle"></i> Inicializar Pagos
                    </button>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <?php if (Auth::isCapturist()): ?>
                <div class="alert alert-warning text-center mb-3">
                    <i class="bi bi-arrow-clockwise"></i>
                    <button id="reinit-payments-btn" class="btn btn-warning me-2">
                        <i class="bi bi-arrow-clockwise"></i> Reinicializar Pagos
                    </button>
                    <small>Esto actualizará todos los pagos a $0.00</small>
                </div>
            <?php endif; ?>
            <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'] ?>"
                                    data-payment-date="<?= $payment['payment_date'] ?: '' ?>"
                                    <?= Auth::isCapturist() ? 'contenteditable="true"' : '' ?>>
                                    <?= $payment['amount'] > 0 ? '$' . number_format($payment['amount'], 2) : '-' ?>
                                </td>
                                <td>
                                    <?php if (Auth::isCapturist()): ?>
                                        <input type="date" class="form-control form-control-sm payment-date-input"
                                               value="<?= $payment['payment_date'] ? date('Y-m-d', strtotime($payment['payment_date'])) : '' ?>">
                                    <?php else: ?>
                                        <?= $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-' ?>
                                    <?php endif; ?>
                                </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';
$db = Database::getInstance();
 $conceptExpenses = $db->fetchAll(
     "SELECT e.*, ec.amount as allocated_amount
      FROM expense_concept_allocations 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"] ?>';

window.initializeConceptPayments = function() {
    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 ===');
            var url = '/dashboard.php?page=concept_view_actions&action=initialize_concept_payments&concept_id=' + conceptId;
            console.log('URL:', url);
            
            fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(function(response) {
                console.log('=== Respuesta del servidor ===', response);
                console.log('Status:', response.status);
                console.log('OK:', response.ok);
                
                if (!response.ok) {
                    return response.text().then(function(text) {
                        console.log('Error response text:', text);
                        throw new Error('HTTP ' + response.status + ': ' + text);
                    });
                }
                
                return response.text().then(function(text) {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('JSON parse error:', e);
                        console.error('Response text:', text);
                        throw new Error('Error al parsear JSON: ' + e.message);
                    }
                });
            })
            .then(function(data) {
                console.log('=== Datos recibidos ===', data);
                
                if (data.success) {
                    Swal.fire('Éxito', data.message, 'success').then(function() {
                        console.log('Recargando página...');
                        location.reload();
                    });
                } else {
                    Swal.fire('Error', data.message || 'Error desconocido', 'error');
                }
            })
            .catch(function(error) {
                console.error('=== Error en fetch ===', error);
                console.error('Error message:', error.message);
                Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
            });
        }
    });
};

<?php if (Auth::isCapturist()): ?>
document.querySelectorAll('.payment-cell[contenteditable="true"]').forEach(function(cell) {
    let originalValue = '';

    cell.addEventListener('focus', function() {
        originalValue = this.textContent.trim();
        this.classList.add('editing');

        const currentValue = this.textContent.trim();

        if (currentValue === '-' || currentValue === '') {
            this.textContent = '';
        } else if (currentValue.includes('$')) {
            this.textContent = currentValue.replace(/[^0-9.]/g, '');
        } else {
            this.textContent = currentValue;
        }

        setTimeout(() => {
            const selection = window.getSelection();
            const range = document.createRange();
            range.selectNodeContents(this);
            selection.removeAllRanges();
            selection.addRange(range);
        }, 0);
    });

    cell.addEventListener('blur', function() {
        this.classList.remove('editing');
        const newValue = this.textContent.trim();

        if (newValue === '') {
            this.textContent = originalValue;
        } else {
            let value = parseFloat(newValue.replace(/[^0-9.-]+/g, '')) || 0;

            if (value < 0 || isNaN(value)) {
                this.textContent = originalValue;
            } else if (value === 0) {
                this.textContent = '$0.00';
            } else {
                this.textContent = '$' + value.toFixed(2);
            }
        }
    });

    cell.addEventListener('keydown', function(e) {
        if (!((e.key >= '0' && e.key <= '9') ||
            e.key === '.' ||
            e.key === 'Backspace' ||
            e.key === 'Delete' ||
            e.key === 'Tab' ||
            e.key === 'Enter' ||
            e.key === 'ArrowLeft' ||
            e.key === 'ArrowRight')) {
            e.preventDefault();
        }
        if (e.key === 'Enter') {
            e.preventDefault();
            const btn = this.parentElement.querySelector('.btn-primary');
            if (btn) {
                btn.click();
            }
        }
    });
    
    cell.addEventListener('blur', function() {
        this.classList.remove('editing');
        const newValue = this.textContent.trim();

        if (newValue === '') {
            // If cell is empty on blur, restore the original value (cancel edit)
            this.textContent = originalValue;
        } else {
            let value = parseFloat(newValue.replace(/[^0-g.-]+/g, '')) || 0;
            if (value <= 0) {
                this.textContent = '-';
            } else {
                this.textContent = '$' + value.toFixed(2);
            }
        }
    });
    
    cell.addEventListener('keydown', function(e) {
        if (!((e.key >= '0' && e.key <= '9') ||
            e.key === '.' ||
            e.key === 'Backspace' ||
            e.key === 'Delete' ||
            e.key === 'Tab' ||
            e.key === 'Enter' ||
            e.key === 'ArrowLeft' ||
            e.key === 'ArrowRight')) {
            e.preventDefault();
        }
        if (e.key === 'Enter') {
            e.preventDefault();
            this.blur();
        }
    });
});

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

    console.log('=== Guardando pago ===');
    console.log('House ID:', houseId);
    console.log('Amount:', amount);
    console.log('Payment Date:', paymentDate);

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

    fetch('/dashboard.php?page=concept_view_actions&action=save_concept_payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            concept_id: '<?= $concept["id"] ?>',
            house_id: houseId,
            amount: amount,
            payment_date: paymentDate
        })
    })
    .then(function(r) {
        console.log('Response status:', r.status);
        return r.json();
    })
    .then(function(data) {
        console.log('Save payment data:', data);
        if (data.success) {
            location.reload();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    })
    .catch(function(error) {
        console.error('Save payment error:', error);
        Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
    });
};

// Attach event listener to button
const initButton = document.getElementById('init-payments-btn');
if (initButton) {
    initButton.addEventListener('click', window.initializeConceptPayments);
}

// Attach event listener to reinitialize button
const reinitButton = document.getElementById('reinit-payments-btn');
if (reinitButton) {
    reinitButton.addEventListener('click', window.initializeConceptPayments);
}
<?php endif; ?>
</script>
