<div class="row mb-4">
    <div class="col-12">
        <h2><i class="bi bi-file-earmark-bar-graph"></i> Reportes</h2>
        <p class="text-muted">Balance general y reportes financieros</p>
    </div>
</div>

<div class="mb-4">
    <div class="btn-group" role="group">
        <a href="/dashboard.php?page=reportes" class="btn btn-outline-primary <?= ($_GET['type'] ?? 'general') == 'general' ? 'active' : '' ?>">
            <i class="bi bi-bar-chart"></i> Balance General
        </a>
        <a href="/dashboard.php?page=reportes&type=water-debtors" class="btn btn-outline-danger <?= ($_GET['type'] ?? '') == 'water-debtors' ? 'active' : '' ?>">
            <i class="bi bi-droplet-fill"></i> Deudores de Agua
        </a>
        <a href="/dashboard.php?page=reportes&type=concept-debtors" class="btn btn-outline-warning <?= ($_GET['type'] ?? '') == 'concept-debtors' ? 'active' : '' ?>">
            <i class="bi bi-cash-coin"></i> Deudores de Conceptos
        </a>
        <a href="/dashboard.php?page=reportes&type=concepts" class="btn btn-outline-info <?= ($_GET['type'] ?? '') == 'concepts' ? 'active' : '' ?>">
            <i class="bi bi-collection"></i> Conceptos Especiales
        </a>
        <a href="/dashboard.php?page=reportes&type=electricity-debtors" class="btn btn-outline-warning <?= ($_GET['type'] ?? '') == 'electricity-debtors' ? 'active' : '' ?>">
            <i class="bi bi-lightbulb-fill"></i> Deudores Luz
        </a>
    </div>
</div>

<?php $reportType = $_GET['type'] ?? 'general'; ?>

<?php if ($reportType == 'water-debtors' && isset($waterDebtors)): ?>
<?php
$hasFilters = !empty($waterDebtors['filters']['year']) || !empty($waterDebtors['filters']['months']) || !empty($waterDebtors['filters']['house_id']);
$filterText = [];
if (!empty($waterDebtors['filters']['year'])) {
    $filterText[] = "Año: " . $waterDebtors['filters']['year'];
}
if (!empty($waterDebtors['filters']['months'])) {
    $filterText[] = "Meses: " . implode(', ', $waterDebtors['filters']['months']);
}
if (!empty($waterDebtors['filters']['house_id'])) {
    require_once __DIR__ . '/../../models/House.php';
    $house = House::findById($waterDebtors['filters']['house_id']);
    $filterText[] = "Casa: " . ($house['number'] ?? 'N/A');
}
?>
<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="bi bi-funnel"></i> Filtros de Deudores de Agua
            <?php if ($hasFilters): ?>
                <span class="badge bg-info ms-2"><?= implode(' | ', $filterText) ?></span>
            <?php endif; ?>
        </h5>
        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#filtersCollapse">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    <div class="collapse <?php echo $hasFilters ? '' : 'show'; ?>" id="filtersCollapse">
        <div class="card-body">
            <form id="waterDebtorsFilter">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Año</label>
                        <select name="filter_year" class="form-select">
                            <option value="">Todos los años</option>
                            <?php for ($y = 2024; $y <= 2025; $y++): ?>
                                <option value="<?= $y ?>" <?= ($_GET['filter_year'] ?? '') == $y ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Casa</label>
                        <select name="filter_house" class="form-select">
                            <option value="">Todas las casas</option>
                            <?php
                            require_once __DIR__ . '/../../models/House.php';
                            $allHouses = House::getAccessible();
                            foreach ($allHouses as $h): ?>
                                <option value="<?= $h['id'] ?>" <?= ($_GET['filter_house'] ?? '') == $h['id'] ? 'selected' : '' ?>><?= $h['number'] ?> - <?= htmlspecialchars($h['owner_name'] ?? '') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Meses</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php
                            $allMonths = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                                         'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
                            $selectedMonths = explode(',', $_GET['filter_months'] ?? '');
                            foreach ($allMonths as $m): ?>
                                <div class="form-check">
                                    <input type="checkbox" name="filter_months[]" value="<?= $m ?>"
                                           class="form-check-input month-checkbox"
                                           id="month_<?= $m ?>"
                                           <?= in_array($m, $selectedMonths) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="month_<?= $m ?>"><?= substr($m,0,3) ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search"></i> Aplicar Filtros
                        </button>
                        <a href="/dashboard.php?page=reportes&type=water-debtors" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> Limpiar Filtros
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('waterDebtorsFilter').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const params = new URLSearchParams();

    if (formData.get('filter_year')) {
        params.append('filter_year', formData.get('filter_year'));
    }
    if (formData.get('filter_house')) {
        params.append('filter_house', formData.get('filter_house'));
    }

    const selectedMonths = formData.getAll('filter_months[]');
    if (selectedMonths.length > 0) {
        params.append('filter_months', selectedMonths.join(','));
    }

    window.location.href = '/dashboard.php?page=reportes&type=water-debtors&' + params.toString();
});
</script>

<?php if ($reportType == 'water-debtors' && isset($waterDebtors)): ?>
<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="card border-danger">
            <div class="card-body">
                <h6 class="text-muted">Total Adeudado (Agua - <?= $year ?>)</h6>
                <h3 class="text-danger">$<?= number_format($waterDebtors['total_due'], 2) ?></h3>
                <small class="text-muted">Total general de deudas</small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-info">
            <div class="card-body">
                <h6 class="text-muted">Total Esperado</h6>
                <h3 class="text-info">$<?= number_format($waterDebtors['total_expected'], 2) ?></h3>
                <small class="text-muted">Total de cuotas mensuales</small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-success">
            <div class="card-body">
                <h6 class="text-muted">Total Pagado</h6>
                <h3 class="text-success">$<?= number_format($waterDebtors['total_paid'], 2) ?></h3>
                <small class="text-muted">Total de pagos realizados</small>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0"><i class="bi bi-exclamation-triangle"></i> Deudores de Pago de Agua</h5>
        <button onclick="exportWaterDebtorsPDF()" class="btn btn-outline-danger btn-sm">
            <i class="bi bi-file-earmark-pdf"></i> Exportar PDF
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($waterDebtors['debtors'])): ?>
            <p class="text-muted">No hay deudores registrados</p>
        <?php else: ?>
            <table class="table table-sm table-bordered">
                <thead class="table-danger">
                    <tr>
                        <th>Casa</th>
                        <th>Propietario</th>
                        <th>Meses Adeudados</th>
                        <th>Total Debe</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($waterDebtors['debtors'] as $debtor): ?>
                        <tr>
                            <td><strong><?= $debtor['house_number'] ?></strong></td>
                            <td><?= htmlspecialchars($debtor['owner_name'] ?? '-') ?></td>
                            <td>
                                <table class="table table-sm mb-0">
                                    <?php foreach ($debtor['months_due'] as $month): ?>
                                        <tr>
                                            <td><?= $month['year'] ?> - <?= $month['month'] ?></td>
                                            <td class="text-end">$<?= number_format($month['due'], 2) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </table>
                            </td>
                            <td class="text-end fw-bold text-danger">$<?= number_format($debtor['total_due'], 2) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot class="table-dark">
                    <tr>
                        <th colspan="3" class="text-end">TOTAL GENERAL:</th>
                        <th class="text-end">$<?= number_format($waterDebtors['total_due'], 2) ?></th>
                    </tr>
                </tfoot>
            </table>
        <?php endif; ?>
    </div>
</div>

<script>
function exportWaterDebtorsPDF() {
    const params = new URLSearchParams();
    <?php if (!empty($waterDebtors['filters']['year'])): ?>
    params.append('filter_year', <?= $waterDebtors['filters']['year'] ?>);
    <?php endif; ?>
    <?php if (!empty($waterDebtors['filters']['months'])): ?>
    params.append('filter_months', '<?= implode(',', $waterDebtors['filters']['months']) ?>');
    <?php endif; ?>
    <?php if (!empty($waterDebtors['filters']['house_id'])): ?>
    params.append('filter_house', <?= $waterDebtors['filters']['house_id'] ?>);
    <?php endif; ?>
    window.open('/dashboard.php?page=reportes_actions&action=export_pdf_report&type=water-debtors&' + params.toString(), '_blank');
}
</script>
<?php endif; ?>

<?php elseif ($reportType == 'concept-debtors' && isset($conceptDebtors)): ?>
<div class="row g-4 mb-4">
    <div class="col-md-12">
        <div class="card border-warning">
            <div class="card-body">
                <h6 class="text-muted">Total Adeudado (Conceptos)</h6>
                <h3 class="text-warning">$<?= number_format($conceptDebtors['total_due'], 2) ?></h3>
                <small class="text-muted">Total general de deudas de conceptos especiales</small>
            </div>
        </div>
    </div>
</div>

<!-- Filtros para deudores de conceptos -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="bi bi-funnel"></i> Filtros</h5>
            </div>
            <div class="card-body">
                        <form method="GET" class="row g-3" id="conceptFiltersForm">
                            <input type="hidden" name="page" value="reportes">
                            <input type="hidden" name="type" value="concept-debtors">

                            <div class="col-md-5">
                                <label class="form-label">Casas</label>
                                <div class="border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                                    <div class="form-check">
                                        <input type="checkbox" name="filter_houses[]" value="all" class="form-check-input house-checkbox" id="house-all" checked>
                                        <label class="form-check-label fw-bold" for="house-all">Todas las casas</label>
                                    </div>
                                    <hr class="my-2">
                                    <?php
                                    $houses = House::getAccessible();
                                    foreach ($houses as $house):
                                        $checked = (!isset($_GET['filter_houses']) || in_array('all', $_GET['filter_houses'] ?? []) || in_array($house['id'], $_GET['filter_houses'] ?? [])) ? 'checked' : '';
                                    ?>
                                        <div class="form-check">
                                            <input type="checkbox" name="filter_houses[]" value="<?= $house['id'] ?>" class="form-check-input house-checkbox house-individual" id="house-<?= $house['id'] ?>" <?= $checked ?>>
                                            <label class="form-check-label" for="house-<?= $house['id'] ?>">
                                                <?= htmlspecialchars($house['number']) ?> - <?= htmlspecialchars($house['owner_name'] ?? 'Sin propietario') ?>
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="col-md-5">
                                <label class="form-label">Conceptos</label>
                                <div class="border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                                    <div class="form-check">
                                        <input type="checkbox" name="filter_concepts[]" value="all" class="form-check-input concept-checkbox" id="concept-all" checked>
                                        <label class="form-check-label fw-bold" for="concept-all">Todos los conceptos</label>
                                    </div>
                                    <hr class="my-2">
                                    <?php
                                    require_once __DIR__ . '/../../models/CollectionConcept.php';
                                    $concepts = CollectionConcept::all(true);
                                    foreach ($concepts as $concept):
                                        $checked = (!isset($_GET['filter_concepts']) || in_array('all', $_GET['filter_concepts'] ?? []) || in_array($concept['id'], $_GET['filter_concepts'] ?? [])) ? 'checked' : '';
                                    ?>
                                        <div class="form-check">
                                            <input type="checkbox" name="filter_concepts[]" value="<?= $concept['id'] ?>" class="form-check-input concept-checkbox concept-individual" id="concept-<?= $concept['id'] ?>" <?= $checked ?>>
                                            <label class="form-check-label" for="concept-<?= $concept['id'] ?>">
                                                <?= htmlspecialchars($concept['name']) ?> ($<?= number_format($concept['amount_per_house'], 2) ?>)
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="col-md-2 d-flex align-items-end">
                                <div class="d-grid gap-2 w-100">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-search"></i> Aplicar Filtros
                                    </button>
                                    <a href="?page=reportes&type=concept-debtors" class="btn btn-outline-secondary">
                                        <i class="bi bi-x-circle"></i> Limpiar
                                    </a>
                                </div>
                            </div>
                        </form>
            </div>
        </div>
    </div>
</div>

<?php foreach ($conceptDebtors['debtors'] as $concept): ?>
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
            <i class="bi bi-collection"></i> <?= htmlspecialchars($concept['concept_name']) ?>
            <span class="badge bg-warning ms-2">$<?= number_format($concept['total_due'], 2) ?> adeudado</span>
        </h5>
        <small class="text-muted">
            Esperado: $<?= number_format($concept['total_expected'], 2) ?> |
            Recaudado: $<?= number_format($concept['total_collected'], 2) ?> |
            Pendiente: $<?= number_format($concept['total_due'], 2) ?>
        </small>
    </div>
    <div class="card-body">
        <table class="table table-sm table-bordered">
            <thead class="table-warning">
                <tr>
                    <th>Casa</th>
                    <th>Propietario</th>
                    <th>Monto Esperado</th>
                    <th>Pagado</th>
                    <th>Adeuda</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($concept['house_debtors'] as $house): ?>
                    <tr>
                        <td><strong><?= $house['house_number'] ?></strong></td>
                        <td><?= htmlspecialchars($house['owner_name'] ?? '-') ?></td>
                        <td class="text-end">$<?= number_format($house['expected'], 2) ?></td>
                        <td class="text-end">$<?= number_format($house['paid'], 2) ?></td>
                        <td class="text-end fw-bold text-warning">$<?= number_format($house['due'], 2) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="4" class="text-end">Total:</th>
                    <th class="text-end">$<?= number_format($concept['total_due'], 2) ?></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<?php endforeach; ?>

<div class="card border-warning">
    <div class="card-body">
        <div class="row">
            <div class="col-md-12 text-center">
                <h5>Total General Adeudado en Todos los Conceptos</h5>
                <h3 class="text-warning">$<?= number_format($conceptDebtors['total_due'], 2) ?></h3>
                <button onclick="exportConceptDebtorsPDF()" class="btn btn-outline-warning">
                    <i class="bi bi-file-earmark-pdf"></i> Exportar PDF
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function exportConceptDebtorsPDF() {
    const houseCheckboxes = document.querySelectorAll('input[name="filter_houses[]"]:checked');
    const conceptCheckboxes = document.querySelectorAll('input[name="filter_concepts[]"]:checked');

    // Filtrar: excluir 'all' si hay opciones específicas seleccionadas
    let selectedHouses = Array.from(houseCheckboxes)
        .map(cb => cb.value)
        .filter(value => {
            if (value === 'all') {
                // Solo incluir 'all' si no hay otras opciones seleccionadas
                return houseCheckboxes.length === 1;
            }
            return true;
        });

    let selectedConcepts = Array.from(conceptCheckboxes)
        .map(cb => cb.value)
        .filter(value => {
            if (value === 'all') {
                // Solo incluir 'all' si no hay otras opciones seleccionadas
                return conceptCheckboxes.length === 1;
            }
            return true;
        });



    let url = '/dashboard.php?page=reportes_actions&action=export_pdf_report&type=concept-debtors';

    // Agregar casas seleccionadas
    if (selectedHouses.length > 0) {
        selectedHouses.forEach(house => {
            url += '&filter_houses[]=' + encodeURIComponent(house);
        });
    }

    // Agregar conceptos seleccionados
    if (selectedConcepts.length > 0) {
        selectedConcepts.forEach(concept => {
            url += '&filter_concepts[]=' + encodeURIComponent(concept);
        });
    }


    window.open(url, '_blank');
}

// Procesar formulario de filtros antes de enviar
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('conceptFiltersForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            // Filtrar los valores antes de enviar
            const houseCheckboxes = form.querySelectorAll('input[name="filter_houses[]"]:checked');
            const conceptCheckboxes = form.querySelectorAll('input[name="filter_concepts[]"]:checked');

            // Limpiar valores existentes
            const existingHouses = form.querySelectorAll('input[name="filter_houses[]"]');
            const existingConcepts = form.querySelectorAll('input[name="filter_concepts[]"]');

            existingHouses.forEach(input => input.remove());
            existingConcepts.forEach(input => input.remove());

            // Agregar solo los valores filtrados
            let selectedHouses = Array.from(houseCheckboxes)
                .map(cb => cb.value)
                .filter(value => {
                    if (value === 'all') {
                        return houseCheckboxes.length === 1;
                    }
                    return true;
                });

            let selectedConcepts = Array.from(conceptCheckboxes)
                .map(cb => cb.value)
                .filter(value => {
                    if (value === 'all') {
                        return conceptCheckboxes.length === 1;
                    }
                    return true;
                });

            // Crear inputs hidden con los valores filtrados
            selectedHouses.forEach(house => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'filter_houses[]';
                input.value = house;
                form.appendChild(input);
            });

            selectedConcepts.forEach(concept => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'filter_concepts[]';
                input.value = concept;
                form.appendChild(input);
            });
        });
    }
});

// Lógica para checkboxes de casas
document.addEventListener('DOMContentLoaded', function() {
    const houseAllCheckbox = document.getElementById('house-all');
    const houseIndividualCheckboxes = document.querySelectorAll('.house-individual');

    if (houseAllCheckbox) {
        houseAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            houseIndividualCheckboxes.forEach(cb => {
                cb.checked = isChecked;
            });
            // Limpiar estado intermedio cuando se marca/desmarca manualmente
            houseAllCheckbox.indeterminate = false;
        });

        houseIndividualCheckboxes.forEach(cb => {
            cb.addEventListener('change', function() {
                const allChecked = Array.from(houseIndividualCheckboxes).every(cb => cb.checked);
                const someChecked = Array.from(houseIndividualCheckboxes).some(cb => cb.checked);

                houseAllCheckbox.checked = allChecked;
                houseAllCheckbox.indeterminate = someChecked && !allChecked;
            });
        });
    }

    // Lógica para checkboxes de conceptos
    const conceptAllCheckbox = document.getElementById('concept-all');
    const conceptIndividualCheckboxes = document.querySelectorAll('.concept-individual');

    if (conceptAllCheckbox) {
        conceptAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            conceptIndividualCheckboxes.forEach(cb => {
                cb.checked = isChecked;
            });
            // Limpiar estado intermedio cuando se marca/desmarca manualmente
            conceptAllCheckbox.indeterminate = false;
        });

        conceptIndividualCheckboxes.forEach(cb => {
            cb.addEventListener('change', function() {
                const allChecked = Array.from(conceptIndividualCheckboxes).every(cb => cb.checked);
                const someChecked = Array.from(conceptIndividualCheckboxes).some(cb => cb.checked);

                conceptAllCheckbox.checked = allChecked;
                conceptAllCheckbox.indeterminate = someChecked && !allChecked;
            });
        });
    }
});
</script>

<?php elseif ($reportType == 'concepts'): ?>
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <h5 class="card-title mb-0">
                <i class="bi bi-funnel"></i> Filtros de Conceptos Especiales
            </h5>
            <button type="button" class="btn btn-sm btn-outline-secondary ms-3" data-bs-toggle="collapse" data-bs-target="#conceptsFilterCollapse">
                <i class="bi bi-chevron-down"></i>
            </button>
        </div>
        <div class="d-flex gap-2">
            <button onclick="exportConceptsPDF()" class="btn btn-outline-primary btn-sm">
                <i class="bi bi-file-earmark-pdf"></i> PDF
            </button>
            <?php if (Auth::isAdmin()): ?>
            <button onclick="exportConceptsCSV()" class="btn btn-outline-success btn-sm">
                <i class="bi bi-file-earmark-csv"></i> CSV
            </button>
            <?php endif; ?>
        </div>
    </div>
    <div class="collapse show" id="conceptsFilterCollapse">
        <div class="card-body">
            <form id="conceptsFilter">
                <div class="row g-3">
                    <div class="col-md-12">
                        <label class="form-label">Concepto</label>
                        <select name="filter_concept" class="form-select">
                            <option value="">Todos los conceptos</option>
                            <?php
                            require_once __DIR__ . '/../../models/CollectionConcept.php';
                            $allConcepts = CollectionConcept::all(true);
                            foreach ($allConcepts as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= ($_GET['filter_concept'] ?? '') == $c['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['name']) ?> - <?= date('d/m/Y', strtotime($c['concept_date'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search"></i> Aplicar Filtros
                        </button>
                        <a href="/dashboard.php?page=reportes&type=concepts" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> Limpiar Filtros
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$filterConceptId = $_GET['filter_concept'] ?? null;
$conceptsToDisplay = [];

if ($filterConceptId) {
    $concept = CollectionConcept::findById($filterConceptId);
    if ($concept) {
        $status = CollectionConcept::getCollectionStatus($filterConceptId);
        $payments = CollectionConcept::getPaymentsByConcept($filterConceptId);
        $conceptsToDisplay[] = [
            'concept' => $concept,
            'status' => $status,
            'payments' => $payments
        ];
    }
} else {
    $allConcepts = CollectionConcept::all(true);
    foreach ($allConcepts as $c) {
        $status = CollectionConcept::getCollectionStatus($c['id']);
        $payments = CollectionConcept::getPaymentsByConcept($c['id']);
        $conceptsToDisplay[] = [
            'concept' => $c,
            'status' => $status,
            'payments' => $payments
        ];
    }
}
?>

<?php foreach ($conceptsToDisplay as $conceptData): ?>
    <?php $concept = $conceptData['concept']; $status = $conceptData['status']; $payments = $conceptData['payments']; ?>
<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="bi bi-collection"></i> <?= htmlspecialchars($concept['name']) ?>
            <small class="text-muted">(<?= date('d/m/Y', strtotime($concept['concept_date'])) ?>)</small>
        </h5>
    </div>
    <div class="card-body">
        <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>
                        <h5 class="text-primary">$<?= number_format($concept['amount_per_house'], 2) ?></h5>
                    </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>
                        <h5 class="text-success">$<?= number_format($status['total_collected'], 2) ?></h5>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-info">
                    <div class="card-body text-center">
                        <h6 class="text-muted">Esperado</h6>
                        <h5 class="text-info">$<?= number_format($status['total_expected'], 2) ?></h5>
                    </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</h6>
                        <h5 class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">
                            $<?= number_format($status['total_collected'], 2) ?>
                        </h5>
                    </div>
                </div>
            </div>
        </div>

        <h6 class="mb-3">Pagos por Casa</h6>
        <?php if (empty($payments)): ?>
            <div class="alert alert-info text-center">
                No hay pagos registrados para este concepto.
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead class="table-primary">
                        <tr>
                            <th>Casa</th>
                            <th>Propietario</th>
                            <th>Monto Pagado</th>
                            <th>Fecha de Pago</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payments as $payment):
                            $rowClass = $payment['amount'] > 0 ? 'table-success' : 'table-light';
                        ?>
                            <tr class="<?= $rowClass ?>">
                                <td><strong><?= $payment['house_number'] ?></strong></td>
                                <td><?= htmlspecialchars($payment['owner_name'] ?? '-') ?></td>
                                <td class="text-end">
                                    <?= $payment['amount'] > 0 ? '$' . number_format($payment['amount'], 2) : '-' ?>
                                </td>
                                <td>
                                    <?= $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-' ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-dark">
                        <tr>
                            <th colspan="2" class="text-end">Total Recaudado:</th>
                            <th class="text-end">$<?= number_format($status['total_collected'], 2) ?></th>
                            <th></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>

<script>
document.getElementById('conceptsFilter').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const params = new URLSearchParams();

    if (formData.get('filter_concept')) {
        params.append('filter_concept', formData.get('filter_concept'));
    }

    window.location.href = '/dashboard.php?page=reportes&type=concepts&' + params.toString();
});

function exportConceptsPDF() {
    const conceptId = '<?= $filterConceptId ?? '' ?>';
    let url = '/dashboard.php?page=reportes_actions&action=export_pdf_report&type=concepts';
    if (conceptId) {
        url += '&filter_concept=' + conceptId;
    }
    window.open(url, '_blank');
}

function exportConceptsCSV() {
    const conceptId = '<?= $filterConceptId ?? '' ?>';
    let url = '/dashboard.php?page=reportes_actions&action=export_csv_concepts';
    if (conceptId) {
        url += '&filter_concept=' + conceptId;
    }
    window.open(url, '_blank');
}
</script>

</script>

<?php elseif ($reportType == 'electricity-debtors' && isset($electricityDebtors)): ?>
<?php
$hasFilters = !empty($electricityDebtors['filters']['year']) || !empty($electricityDebtors['filters']['periods']) || !empty($electricityDebtors['filters']['house_id']);
$filterText = [];
if (!empty($electricityDebtors['filters']['year'])) {
    $filterText[] = "Año: " . $electricityDebtors['filters']['year'];
}
if (!empty($electricityDebtors['filters']['periods'])) {
    $filterText[] = "Periodos: " . implode(', ', $electricityDebtors['filters']['periods']);
}
if (!empty($electricityDebtors['filters']['house_id'])) {
    require_once __DIR__ . '/../../models/House.php';
    $house = House::findById($electricityDebtors['filters']['house_id']);
    $filterText[] = "Casa: " . ($house['number'] ?? 'N/A');
}
?>
<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="bi bi-funnel"></i> Filtros de Deudores de Luz
            <?php if ($hasFilters): ?>
                <span class="badge bg-warning text-dark ms-2"><?= implode(' | ', $filterText) ?></span>
            <?php endif; ?>
        </h5>
        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#filtersCollapse">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    <div class="collapse <?php echo $hasFilters ? '' : 'show'; ?>" id="filtersCollapse">
        <div class="card-body">
            <form id="electricityDebtorsFilter">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Año</label>
                        <select name="filter_year" class="form-select">
                            <option value="">Todos los años</option>
                            <?php for ($y = 2024; $y <= date('Y') + 1; $y++): ?>
                                <option value="<?= $y ?>" <?= ($_GET['filter_year'] ?? '') == $y ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Casa</label>
                        <select name="filter_house" class="form-select">
                            <option value="">Todas las casas</option>
                            <?php
                            require_once __DIR__ . '/../../models/House.php';
                            $allHouses = House::getAccessible();
                            foreach ($allHouses as $h): ?>
                                <option value="<?= $h['id'] ?>" <?= ($_GET['filter_house'] ?? '') == $h['id'] ? 'selected' : '' ?>><?= $h['number'] ?> - <?= htmlspecialchars($h['owner_name'] ?? '') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Periodos</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php
                            require_once __DIR__ . '/../../models/ElectricityBill.php';
                            $allPeriods = ElectricityBill::getPeriods();
                            $selectedPeriods = explode(',', $_GET['filter_periods'] ?? '');
                            foreach ($allPeriods as $p): ?>
                                <div class="form-check">
                                    <input type="checkbox" name="filter_periods[]" value="<?= $p ?>"
                                           class="form-check-input period-checkbox"
                                           id="period_<?= str_replace(' ', '', $p) ?>"
                                           <?= in_array($p, $selectedPeriods) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="period_<?= str_replace(' ', '', $p) ?>"><?= $p ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search"></i> Aplicar Filtros
                        </button>
                        <a href="/dashboard.php?page=reportes&type=electricity-debtors" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> Limpiar Filtros
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('electricityDebtorsFilter').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const params = new URLSearchParams();

    if (formData.get('filter_year')) {
        params.append('filter_year', formData.get('filter_year'));
    }
    if (formData.get('filter_house')) {
        params.append('filter_house', formData.get('filter_house'));
    }

    const selectedPeriods = formData.getAll('filter_periods[]');
    if (selectedPeriods.length > 0) {
        params.append('filter_periods', selectedPeriods.join(','));
    }

    window.location.href = '/dashboard.php?page=reportes&type=electricity-debtors&' + params.toString();
});
</script>

<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="card border-warning">
            <div class="card-body">
                <h6 class="text-muted">Total Adeudado (Luz)</h6>
                <h3 class="text-warning">$<?= number_format($electricityDebtors['total_due'], 2) ?></h3>
                <small class="text-muted">Total general de deudas</small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-info">
            <div class="card-body">
                <h6 class="text-muted">Total Esperado</h6>
                <h3 class="text-info">$<?= number_format($electricityDebtors['total_expected'], 2) ?></h3>
                <small class="text-muted">Total configurado</small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-success">
            <div class="card-body">
                <h6 class="text-muted">Total Pagado</h6>
                <h3 class="text-success">$<?= number_format($electricityDebtors['total_paid'], 2) ?></h3>
                <small class="text-muted">Total recaudado</small>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0"><i class="bi bi-exclamation-triangle"></i> Deudores de Luz - Cámara</h5>
        <button onclick="exportElectricityDebtorsPDF()" class="btn btn-outline-warning btn-sm">
            <i class="bi bi-file-earmark-pdf"></i> Exportar PDF
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($electricityDebtors['debtors'])): ?>
            <p class="text-muted">No hay deudores registrados</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead class="table-warning">
                        <tr>
                            <th>Casa</th>
                            <th>Propietario</th>
                            <th>Periodos Adeudados</th>
                            <th>Total Debe</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($electricityDebtors['debtors'] as $debtor): ?>
                            <tr>
                                <td><strong><?= $debtor['house_number'] ?></strong></td>
                                <td><?= htmlspecialchars($debtor['owner_name'] ?? '-') ?></td>
                                <td>
                                    <table class="table table-sm mb-0">
                                        <?php foreach ($debtor['periods_due'] as $period): ?>
                                            <tr>
                                                <td><?= $period['year'] ?> - <?= $period['period'] ?></td>
                                                <td class="text-end">$<?= number_format($period['due'], 2) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </table>
                                </td>
                                <td class="text-end fw-bold text-danger">$<?= number_format($debtor['total_due'], 2) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-dark">
                        <tr>
                            <th colspan="3" class="text-end">TOTAL GENERAL:</th>
                            <th class="text-end">$<?= number_format($electricityDebtors['total_due'], 2) ?></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function exportElectricityDebtorsPDF() {
    const form = document.getElementById('electricityDebtorsFilter');
    const params = new URLSearchParams();
    
    params.append('action', 'export_pdf_report');
    params.append('type', 'electricity-debtors');

    if (form) {
        const formData = new FormData(form);
        
        if (formData.get('filter_year')) {
            params.append('filter_year', formData.get('filter_year'));
        }
        if (formData.get('filter_house')) {
            params.append('filter_house', formData.get('filter_house'));
        }

        const selectedPeriods = formData.getAll('filter_periods[]');
        if (selectedPeriods.length > 0) {
            params.append('filter_periods', selectedPeriods.join(','));
        }
    } else {
        // Fallback si no hay formulario (por ejemplo si se ocultó), usar parámetros de URL actual
        const currentParams = new URLSearchParams(window.location.search);
        if (currentParams.get('filter_year')) params.append('filter_year', currentParams.get('filter_year'));
        if (currentParams.get('filter_house')) params.append('filter_house', currentParams.get('filter_house'));
        if (currentParams.get('filter_periods')) params.append('filter_periods', currentParams.get('filter_periods'));
    }

    window.open('/dashboard.php?page=reportes_actions&' + params.toString(), '_blank');
}
</script>

<?php else: ?>
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
            <i class="bi bi-funnel"></i> Filtro por Año
        </h5>
        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#yearFilterCollapse">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    <div class="collapse show" id="yearFilterCollapse">
        <div class="card-body">
            <form id="yearFilter">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Año</label>
                        <select name="filter_year" class="form-select">
                            <option value="">Todos los años</option>
                            <?php
                            $years = range(2024, date('Y') + 1);
                            foreach ($years as $y): ?>
                                <option value="<?= $y ?>" <?= ($_GET['filter_year'] ?? '') == $y ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search"></i> Aplicar Filtro
                        </button>
                        <a href="/dashboard.php?page=reportes" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> Limpiar Filtro
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('yearFilter').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const params = new URLSearchParams();

    if (formData.get('filter_year')) {
        params.append('filter_year', formData.get('filter_year'));
    }

    window.location.href = '/dashboard.php?page=reportes&' + params.toString();
});
</script>


<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="card border-success">
            <div class="card-body">
                <h6 class="text-muted">Ingresos Totales</h6>
                <h4 class="text-success">$<?= number_format($balance['total_incomes'], 2) ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-primary">
            <div class="card-body">
                <h6 class="text-muted">Conceptos</h6>
                <h4 class="text-primary">$<?= number_format($balance['concept_incomes'], 2) ?></h4>
            </div>
        </div>
    </div>
    <?php if (!Auth::isLector()): ?>
    <div class="col-md-3">
        <div class="card border-danger">
            <div class="card-body">
                <h6 class="text-muted">Egresos</h6>
                <h4 class="text-danger">$<?= number_format($balance['total_expenses'], 2) ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card <?= $balance['balance'] >= 0 ? 'border-success' : 'border-danger' ?>">
            <div class="card-body">
                <h6 class="text-muted">Balance Neto</h6>
                <h4 class="<?= $balance['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">
                    $<?= number_format($balance['balance'], 2) ?>
                </h4>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<div class="row">
    <?php if (!Auth::isLector()): ?>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Gastos por Categoría</h5>
                <button onclick="exportExpensesPDF()" class="btn btn-outline-danger btn-sm">
                    <i class="bi bi-file-earmark-pdf"></i> PDF
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($expensesByCategory)): ?>
                    <p class="text-muted">No hay gastos registrados</p>
                <?php else: ?>
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Categoría</th>
                                <th class="text-end">Monto</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($expensesByCategory as $cat): ?>
                                <tr>
                                    <td><?= htmlspecialchars($cat['category'] ?? 'Sin categoría') ?></td>
                                    <td class="text-end">$<?= number_format($cat['total'], 2) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="col-md-<?= Auth::isLector() ? '12' : '12' ?>">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    Resumen Financiero
                    <?php if (!empty($conceptDetails['year'])): ?>
                        <small class="text-muted">(<?= $conceptDetails['year'] ?>)</small>
                    <?php endif; ?>
                </h5>
                <button onclick="exportBalancePDF()" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-file-earmark-pdf"></i> PDF
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($conceptDetails['concepts'])): ?>
                    <p class="text-muted">No hay conceptos especiales registrados para el año seleccionado.</p>
                <?php else: ?>
                    <table class="table table-sm table-bordered">
                        <thead class="table-primary">
                            <tr>
                                <th>Concepto</th>
                                <th class="text-end">Esperado</th>
                                <th class="text-end">Recaudado</th>
                                <th class="text-end">Pendiente</th>
                                <th class="text-end">Gastos Asociados</th>
                                <th class="text-end">Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($conceptDetails['concepts'] as $cd): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($cd['concept']['name']) ?></strong>
                                        <?php if (!empty($cd['concept']['description'])): ?>
                                            <small class="text-muted d-block"><?= htmlspecialchars($cd['concept']['description']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">$<?= number_format($cd['expected'], 2) ?></td>
                                    <td class="text-end text-success">$<?= number_format($cd['collected'], 2) ?></td>
                                    <td class="text-end text-warning">$<?= number_format($cd['pending'], 2) ?></td>
                                    <?php if (!Auth::isLector()): ?>
                                    <td class="text-end text-danger">$<?= number_format($cd['expenses'], 2) ?></td>
                                    <td class="text-end fw-bold <?= $cd['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">
                                        $<?= number_format($cd['balance'], 2) ?>
                                    </td>
                                    <?php else: ?>
                                    <td class="text-end" colspan="2">-</td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="table-dark">
                            <tr>
                                <th><strong>TOTALES:</strong></th>
                                <th class="text-end">$<?= number_format($conceptDetails['totals']['expected'], 2) ?></th>
                                <th class="text-end">$<?= number_format($conceptDetails['totals']['collected'], 2) ?></th>
                                <th class="text-end">$<?= number_format($conceptDetails['totals']['pending'], 2) ?></th>
                                <?php if (!Auth::isLector()): ?>
                                <th class="text-end">$<?= number_format($conceptDetails['totals']['expenses'], 2) ?></th>
                                <th class="text-end fw-bold <?= $conceptDetails['totals']['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">
                                    $<?= number_format($conceptDetails['totals']['balance'], 2) ?>
                                </th>
                                <?php else: ?>
                                <th class="text-end" colspan="2">-</th>
                                <?php endif; ?>
                            </tr>
                        </tfoot>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="card mt-4">
    <div class="card-header">
        <h5 class="card-title mb-0">Exportar Reportes</h5>
    </div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <button onclick="exportBalancePDF()" class="btn btn-outline-primary w-100">
                    <i class="bi bi-file-earmark-bar-graph"></i> Balance General (PDF)
                </button>
            </div>
            <?php if (Auth::isAdmin()): ?>
            <div class="col-md-3">
                <button onclick="exportBalanceCSV()" class="btn btn-outline-success w-100">
                    <i class="bi bi-file-earmark-csv"></i> Balance General (CSV)
                </button>
            </div>
            <?php endif; ?>
            <?php if (!Auth::isLector()): ?>
            <div class="col-md-3">
                <button onclick="exportExpensesPDF()" class="btn btn-outline-danger w-100">
                    <i class="bi bi-receipt"></i> Gastos (PDF)
                </button>
            </div>
            <?php if (Auth::isAdmin()): ?>
            <div class="col-md-3">
                <button onclick="exportExpensesCSV()" class="btn btn-outline-secondary w-100">
                    <i class="bi bi-file-earmark-csv"></i> Gastos (CSV)
                </button>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function exportBalancePDF() {
    const filterYear = '<?= $_GET['filter_year'] ?? '' ?>';
    let url = '/dashboard.php?page=reportes_actions&action=export_pdf_report&type=balance';
    if (filterYear) {
        url += '&filter_year=' + filterYear;
    }
    window.open(url, '_blank');
}

function exportBalanceCSV() {
    const filterYear = '<?= $_GET['filter_year'] ?? '' ?>';
    let url = '/dashboard.php?page=reportes_actions&action=export_csv_balance';
    if (filterYear) {
        url += '&filter_year=' + filterYear;
    }
    window.open(url, '_blank');
}

function exportExpensesPDF() {
    window.open('/dashboard.php?page=reportes_actions&action=export_pdf_report&type=expenses', '_blank');
}

function exportExpensesCSV() {
    window.open('/dashboard.php?page=reportes_actions&action=export_csv_expenses', '_blank');
}
</script>
<?php endif; ?>
