<?php
declare(strict_types=1);

require_once __DIR__ . '/api/db_pdo.php';
require_once __DIR__ . '/api/auth.php';
require_once __DIR__ . '/api/penduduk_feature_helper.php';
require_admin_login();

ensurePendudukFeatureSchema($pdo);
refreshAllPriorityScores($pdo);

$status = trim((string)($_GET['status'] ?? ''));
$priority = trim((string)($_GET['prioritas'] ?? ''));
$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'p.status_bantuan = ?';
    $params[] = $status;
}

if ($priority === 'tinggi') {
    $where[] = 'p.skor_prioritas >= 70';
} elseif ($priority === 'sedang') {
    $where[] = 'p.skor_prioritas BETWEEN 40 AND 69';
} elseif ($priority === 'rendah') {
    $where[] = 'p.skor_prioritas < 40';
}

$sql = "
    SELECT p.*, r.nama AS rumah_ibadah_nama
    FROM penduduk_miskin p
    LEFT JOIN rumah_ibadah r ON p.ibadah_id = r.id
";

if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= ' ORDER BY p.skor_prioritas DESC, p.id DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$summary = [
    'total' => count($rows),
    'tinggi' => count(array_filter($rows, fn($r) => (int)$r['skor_prioritas'] >= 70)),
    'belum' => count(array_filter($rows, fn($r) => $r['status_bantuan'] === 'Belum dibantu')),
    'luar' => count(array_filter($rows, fn($r) => (int)$r['is_blank_spot'] === 1)),
];

function e(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Prioritas Bantuan</title>
    <link rel="stylesheet" href="assets/css/report.css?v=<?= filemtime(__DIR__ . '/assets/css/report.css') ?>">
</head>
<body>
    <main class="report-page">
        <header class="report-header">
            <div>
                <p class="eyebrow">WebGIS Peduli</p>
                <h1>Laporan Prioritas Bantuan</h1>
                <p>Dicetak pada <?= date('d/m/Y H:i') ?> oleh <?= e(current_admin_name()) ?></p>
            </div>
            <button onclick="window.print()" class="print-btn">Cetak / Simpan PDF</button>
        </header>

        <section class="summary-grid">
            <div><span>Total Data</span><strong><?= $summary['total'] ?></strong></div>
            <div><span>Prioritas Tinggi</span><strong><?= $summary['tinggi'] ?></strong></div>
            <div><span>Belum Dibantu</span><strong><?= $summary['belum'] ?></strong></div>
            <div><span>Luar Radius</span><strong><?= $summary['luar'] ?></strong></div>
        </section>

        <section class="report-note">
            <strong>Keterangan:</strong> Skor prioritas dihitung dari status bantuan, jumlah tanggungan, lansia/balita,
            penghasilan, kondisi rumah, kebutuhan mendesak, dan posisi terhadap radius layanan.
        </section>

        <table>
            <thead>
                <tr>
                    <th>No</th>
                    <th>Kepala Keluarga</th>
                    <th>Prioritas</th>
                    <th>Kebutuhan</th>
                    <th>Status</th>
                    <th>Tindak Lanjut</th>
                    <th>Rumah Ibadah</th>
                    <th>Jarak</th>
                    <th>Catatan</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $i => $row): ?>
                    <tr>
                        <td><?= $i + 1 ?></td>
                        <td>
                            <strong><?= e($row['kk_nama']) ?></strong><br>
                            <small><?= e($row['alamat']) ?></small>
                        </td>
                        <td>
                            <strong><?= (int)$row['skor_prioritas'] ?></strong><br>
                            <small><?= e(getPriorityLabel((int)$row['skor_prioritas'])) ?></small>
                        </td>
                        <td><?= e($row['kategori_kebutuhan'] ?: 'Belum diisi') ?></td>
                        <td><?= e($row['status_bantuan']) ?></td>
                        <td><?= e($row['tindak_lanjut'] ?: 'Belum disurvei') ?></td>
                        <td><?= e($row['rumah_ibadah_nama'] ?: '-') ?></td>
                        <td>
                            Lurus: <?= e((string)$row['jarak_m']) ?> m<br>
                            <small>Rute: <?= e((string)($row['jarak_rute_m'] ?? '-')) ?> m</small>
                        </td>
                        <td><?= e($row['catatan_survei'] ?: $row['deskripsi_kebutuhan'] ?: '-') ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$rows): ?>
                    <tr><td colspan="9" class="empty">Tidak ada data sesuai filter.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </main>
</body>
</html>
