<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>
    </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>

<?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() {
    window.open('/dashboard.php?page=reportes_actions&action=export_pdf_report&type=concept-debtors', '_blank');
}
</script>

<?php else: ?>

<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' : '6' ?>">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Resumen Financiero</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">
                <table class="table table-sm">
                    <tr>
                        <td>Total Ingresos (Conceptos):</td>
                        <td class="text-end text-success">$<?= number_format($balance['total_incomes'], 2) ?></td>
                    </tr>
                    <?php if (!Auth::isLector()): ?>
                    <tr class="table-light">
                        <td>Total Egresos:</td>
                        <td class="text-end text-danger">$<?= number_format($balance['total_expenses'], 2) ?></td>
                    </tr>
                    <tr class="table-dark">
                        <td><strong>Balance:</strong></td>
                        <td class="text-end fw-bold <?= $balance['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">
                            $<?= number_format($balance['balance'], 2) ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                </table>
            </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>
            <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 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>
            <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; ?>
        </div>
    </div>
</div>

<script>
function exportBalancePDF() {
    window.open('/dashboard.php?page=reportes_actions&action=export_pdf_report&type=balance', '_blank');
}

function exportBalanceCSV() {
    window.open('/dashboard.php?page=reportes_actions&action=export_csv_balance', '_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; ?>
