<?php
declare(strict_types=1);
if (!ob_get_level()) ob_start();

/**
 * modules/laporan/index.php
 * Laporan Bulanan Keperawatan Bertingkat
 * Unit → Kasubdiv → Kadiv
 * 
 * Menggunakan common.php dari sistem yang sudah ada.
 */

/* ── Bootstrap ── */
try {
    require_once __DIR__ . '/common.php';
} catch (Throwable $bootErr) {
    echo '<div style="background:#fee2e2;padding:1rem;border-radius:8px;margin:1rem;font-family:monospace">';
    echo '<b>Error loading common.php:</b><br>';
    echo htmlspecialchars($bootErr->getMessage()).'<br>';
    echo htmlspecialchars($bootErr->getFile().':'.$bootErr->getLine());
    echo '</div>';
    return;
}
try {
    $conn = lr_conn();
} catch (Throwable $connErr) {
    echo '<div style="background:#fee2e2;padding:1rem;border-radius:8px;margin:1rem;font-family:monospace">';
    echo '<b>Error lr_conn():</b><br>'.htmlspecialchars($connErr->getMessage());
    echo '</div>';
    return;
}
if (!$conn) {
    echo '<div style="background:#fee2e2;padding:1rem;border-radius:8px;margin:1rem">lr_conn() mengembalikan null/false</div>';
    return;
}

/* ── Output JS functions & passcode bypass ── */
lr_render_scripts();
?>
<script>
/* ═══ PASSCODE MODAL BYPASS untuk Laporan Bulanan ═══════════════
   Intercept SEMUA mekanisme passcode yang mungkin:
   1. Selector berbasis class text-red / btn-danger
   2. Selector berbasis teks "Hapus"  
   3. data-* attribute
   4. Global click handler
*/
(function() {
    // Tandai semua tombol laporan kita agar dikenali
    document.querySelectorAll && document.addEventListener('DOMContentLoaded', function() {
        // Override window.showPasscodeModal jika ada
        if (typeof window.showPasscodeModal === 'function') {
            const _orig = window.showPasscodeModal;
            window.showPasscodeModal = function(callback, el) {
                // Jika elemen berasal dari tabel laporan, langsung jalankan callback
                if (el && el.closest && el.closest('[data-section-table],[data-section-body]')) {
                    if (typeof callback === 'function') callback();
                    return;
                }
                return _orig.apply(this, arguments);
            };
        }
        // Override confirmPasscode / requirePasscode / passCode variants
        ['confirmPasscode','requirePasscode','checkPasscode','openPasscodeModal',
         'showActionPasscode','actionPasscode'].forEach(function(fn) {
            if (typeof window[fn] === 'function') {
                const _o = window[fn];
                window[fn] = function() {
                    const el = arguments[0] || (window.event && window.event.target);
                    if (el && el.closest && el.closest('[data-section-table],[data-section-body]')) {
                        const cb = arguments[1] || arguments[0];
                        if (typeof cb === 'function') cb();
                        return;
                    }
                    return _o.apply(this, arguments);
                };
            }
        });
    });

    // useCapture=true: jalan SEBELUM semua handler lain
    document.addEventListener('click', function(e) {
        const btn = e.target && e.target.closest ? 
            e.target.closest('[data-section-table] button, [data-section-body] button, button[onclick*="lrRemoveRow"], button[onclick*="lrClearTarikan"], button[onclick*="lrAddRow"]')
            : null;
        if (btn) {
            e.stopImmediatePropagation();
            // Jalankan onclick langsung tanpa propagasi
        }
    }, true);

    // Override jQuery jika ada
    if (typeof jQuery !== 'undefined') {
        jQuery(document).on('click.passcode', function(e) {
            if (jQuery(e.target).closest('[data-section-table],[data-section-body]').length) {
                e.stopImmediatePropagation();
            }
        });
    }
})();
</script>
<?php

/* Output wrapper div dengan data-no-passcode agar semua elemen laporan dibebaskan dari passcode modal */
?>
<div id="laporan-bulanan-wrapper" data-no-passcode="1" style="display:contents">
<?php
/* ── lr_ensure_schema ── */
try {
    lr_ensure_schema($conn);
} catch (Throwable $schErr) {
    echo '<div style="background:#fef9c3;padding:1rem;border-radius:8px;margin:1rem;font-family:monospace">';
    echo '<b>Warning lr_ensure_schema:</b><br>'.htmlspecialchars($schErr->getMessage());
    echo '</div>';
}

/* ── Identitas user ── */
$lbUserId  = lr_user_id();
$lbRole    = lr_role();
$lbIsAdmin = in_array($lbRole, ['admin','superadmin'], true);

function lb_jabatan(): string {
    return strtolower(trim((string)($_SESSION['jabatan'] ?? $_SESSION['user']['jabatan'] ?? '')));
}
function lb_level(): string {
    global $lbIsAdmin;
    if ($lbIsAdmin) return 'kadiv';
    $j = lb_jabatan();
    if (str_contains($j,'kadiv') || str_contains($j,'kepala divisi')) return 'kadiv';
    if (str_contains($j,'kasubdiv') || str_contains($j,'sub div'))    return 'kasubdiv';
    return 'kaunit';
}
$lbLevel = lb_level();

/* ── Unit user (kaunit) ── */
$lbUnitId   = 0;
$lbUnitName = (string)($_SESSION['unit'] ?? $_SESSION['user']['unit'] ?? '');
if ($lbUnitName !== '') {
    $ur = $conn->query("SELECT id FROM units WHERE name=".($conn->real_escape_string($lbUnitName) ? "'".$conn->real_escape_string($lbUnitName)."'" : "''")." LIMIT 1");
    if ($ur && ($urow = $ur->fetch_assoc())) $lbUnitId = (int)$urow['id'];
}

/* ── Parameter ── */
$page  = trim((string)($_GET['page']  ?? 'dashboard'));
$bulan = max(1, min(12, (int)($_GET['bulan'] ?? date('n'))));
$tahun = max(2024, min(2099, (int)($_GET['tahun'] ?? date('Y'))));
$repId = (int)($_GET['report_id'] ?? 0);

$bulanNama = lr_bulan($bulan);

/* ── POST Actions ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* Simpan laporan (common.php lr_save_report) */
    if (isset($_POST['save_report']) || isset($_POST['submit_report'])) {
        $rId = (int)($_POST['report_id'] ?? 0);
        if ($rId > 0) {
            lr_save_report($conn, $rId);
            $newStatus = $conn->query("SELECT status FROM monthly_report_headers WHERE id=$rId LIMIT 1")->fetch_assoc()['status'] ?? 'draft';
            echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=form&report_id=$rId&bulan=$bulan&tahun=$tahun&saved=1\");</script>"; return;
        }
    }

    /* Perbaiki subdivision_id + force-submit laporan unit yang datanya sudah lengkap tapi masih draft
       atau subdivision_id-nya salah/kosong (dipakai kasubdiv/admin saat menemukan data unit nyasar). */
    if (isset($_POST['force_submit_unit'])) {
        $frId   = (int)($_POST['force_report_id'] ?? 0);
        $fUnit  = (int)($_POST['force_unit_id'] ?? 0);
        $fSubId = (int)($_POST['force_subdivision_id'] ?? 0);
        if ($frId > 0) {
            // Perbaiki subdivision_id di header laporan unit itu
            if ($fSubId > 0) {
                $stmt = $conn->prepare("UPDATE monthly_report_headers SET subdivision_id=?, status='submitted', submitted_at=NOW(), updated_by=? WHERE id=? AND report_level='unit'");
                $stmt->bind_param('iii', $fSubId, $lbUserId, $frId); $stmt->execute(); $stmt->close();
            } else {
                $stmt = $conn->prepare("UPDATE monthly_report_headers SET status='submitted', submitted_at=NOW(), updated_by=? WHERE id=? AND report_level='unit'");
                $stmt->bind_param('ii', $lbUserId, $frId); $stmt->execute(); $stmt->close();
            }
            // Perbaiki juga subdivision_id di tabel units supaya tidak salah lagi untuk laporan berikutnya
            if ($fUnit > 0 && $fSubId > 0) {
                $stmt = $conn->prepare("UPDATE units SET subdivision_id=? WHERE id=?");
                $stmt->bind_param('ii', $fSubId, $fUnit); $stmt->execute(); $stmt->close();
            }
        }
        echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=form&report_id=$repId&bulan=$bulan&tahun=$tahun\");</script>"; return;
    }

    /* Buat/temukan laporan & redirect ke form */
    if (isset($_POST['open_report'])) {
        $rLevel = (string)($_POST['report_level'] ?? 'unit');
        $rType  = (string)($_POST['report_type']  ?? 'rajal');
        $rUnit  = (int)($_POST['unit_id'] ?? $lbUnitId);
        $rSub   = (int)($_POST['subdivision_id'] ?? 0);
        $rDiv   = (int)($_POST['division_id'] ?? 1);
        $rId = lr_find_or_create_report($conn, $rLevel, $bulan, $tahun, $rUnit ?: null, $rSub ?: null, $rDiv, $rType, $lbUserId);
        echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=form&report_id=$rId&bulan=$bulan&tahun=$tahun\");</script>"; return;
    }

    /* Tarik data dari laporan bawahan */
    if (isset($_POST['pull_children'])) {
        $rId    = (int)($_POST['report_id'] ?? 0);
        $rLevel = (string)($_POST['report_level'] ?? 'kasubdiv');
        $rSub   = (int)($_POST['subdivision_id'] ?? 0);
        $rDiv   = (int)($_POST['division_id'] ?? 1);
        if ($rId > 0) {
            $n = lr_pull_children($conn, $rId, $rLevel, $bulan, $tahun, $rSub, $rDiv);
            echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=form&report_id=$rId&bulan=$bulan&tahun=$tahun&pulled=$n\");</script>"; return;
        }
    }

    /* Approve / Reject */
    if (isset($_POST['approve_report']) || isset($_POST['reject_report'])) {
        $rId  = (int)($_POST['report_id'] ?? 0);
        $note = trim((string)($_POST['notes'] ?? ''));
        if ($rId > 0) {
            $approved  = isset($_POST['approve_report']);
            $newStatus = $approved ? 'approved' : 'rejected';
            $stmt = $conn->prepare("UPDATE monthly_report_headers SET status=?, approved_at=".($approved?'NOW()':'NULL').", rejected_note=?, updated_by=? WHERE id=?");
            $rn = $approved ? null : $note;
            $stmt->bind_param('ssii', $newStatus, $rn, $lbUserId, $rId);
            $stmt->execute(); $stmt->close();
        }
        echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=dashboard&bulan=$bulan&tahun=$tahun\");</script>"; return;
    }
}

/* ── Load data laporan per bulan ── */
$unitReports     = [];
$kasubdivReports = [];
$kadivReports    = [];

$stmt = $conn->prepare("SELECT h.*, u.name unit_name FROM monthly_report_headers h LEFT JOIN units u ON u.id=h.unit_id WHERE h.report_level='unit' AND h.bulan=? AND h.tahun=? ORDER BY u.name");
$stmt->bind_param('ii', $bulan, $tahun); $stmt->execute();
$res = $stmt->get_result(); while($r=$res->fetch_assoc()) $unitReports[]=$r; $stmt->close();

$stmt = $conn->prepare("SELECT h.*, ns.name subdiv_name FROM monthly_report_headers h LEFT JOIN nursing_subdivisions ns ON ns.id=h.subdivision_id WHERE h.report_level='kasubdiv' AND h.bulan=? AND h.tahun=? ORDER BY h.id");
$stmt->bind_param('ii', $bulan, $tahun); $stmt->execute();
$res = $stmt->get_result(); while($r=$res->fetch_assoc()) $kasubdivReports[]=$r; $stmt->close();

$stmt = $conn->prepare("SELECT * FROM monthly_report_headers WHERE report_level='kadiv' AND bulan=? AND tahun=? ORDER BY id");
$stmt->bind_param('ii', $bulan, $tahun); $stmt->execute();
$res = $stmt->get_result(); while($r=$res->fetch_assoc()) $kadivReports[]=$r; $stmt->close();

/* ── Daftar subdivisi & unit ── */
$subdivisions = [];
$res = $conn->query("SELECT * FROM nursing_subdivisions WHERE is_active=1 ORDER BY id");
if ($res) while($r=$res->fetch_assoc()) $subdivisions[]=$r;

$allUnits = lr_units($conn);

/* ── Laporan corrente (untuk page=form) ── */
$currentReport = null;
if ($repId > 0) {
    $currentReport = lr_report($conn, $repId);
    if ($currentReport) {
        /* Sinkronkan section: laporan lama (dibuat sebelum update skema) otomatis dapat seksi baru */
        lr_sync_sections($conn, $repId, (string)$currentReport['report_level']);
    }
}

/* ── Status badge ── */
function lb_badge(string $s): string {
    $m = ['draft'=>'bg-slate-100 text-slate-600','submitted'=>'bg-blue-100 text-blue-700 border border-blue-200',
          'reviewed'=>'bg-violet-100 text-violet-700','approved'=>'bg-emerald-100 text-emerald-700',
          'rejected'=>'bg-rose-100 text-rose-700 border border-rose-200','final'=>'bg-green-600 text-white'];
    $l = ['draft'=>'Draft','submitted'=>'Dikirim','reviewed'=>'Direview','approved'=>'Disetujui',
          'rejected'=>'Ditolak','final'=>'Final'];
    $cls=$m[$s]??'bg-gray-100'; $lab=$l[$s]??$s;
    return "<span class='px-2 py-1 rounded-full text-xs font-bold $cls'>$lab</span>";
}

$savedMsg  = isset($_GET['saved'])  ? '<div class="bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl px-4 py-3 mb-4 font-bold text-sm">✓ Laporan berhasil disimpan.</div>' : '';
$pulledMsg = isset($_GET['pulled']) ? '<div class="bg-blue-50 border border-blue-200 text-blue-800 rounded-xl px-4 py-3 mb-4 font-bold text-sm">✓ '.((int)$_GET['pulled']).' baris data berhasil ditarik dari laporan bawahan.</div>' : '';
?>
<style>
.lb-card{background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:1.25rem}
.lb-dark{background:#0f172a;color:#f8fafc;border-radius:16px;padding:1.25rem}
.lb-btn{display:inline-flex;align-items:center;gap:.35rem;border-radius:10px;padding:.45rem .9rem;font-weight:700;font-size:.82rem;cursor:pointer;transition:.15s;border:none;text-decoration:none}
.lb-btn:hover{opacity:.85;transform:translateY(-1px)}
.lb-pri{background:#2563eb;color:#fff}.lb-suc{background:#059669;color:#fff}
.lb-war{background:#d97706;color:#fff}.lb-dan{background:#dc2626;color:#fff}
.lb-sec{background:#f1f5f9;color:#334155;border:1px solid #e2e8f0}
.lb-grn{background:#166534;color:#fff}
.lb-inp{width:100%;border:1px solid #e2e8f0;border-radius:8px;padding:.5rem .7rem;font-size:.9rem;outline:none;font-family:inherit}
.lb-inp:focus{border-color:#6366f1;box-shadow:0 0 0 2px rgba(99,102,241,.15)}
.lb-tbl{width:100%;border-collapse:collapse;font-size:.83rem}
.lb-tbl th{background:#f8fafc;color:#475569;font-size:.72rem;text-transform:uppercase;padding:.6rem .7rem;border-bottom:2px solid #e2e8f0;text-align:left}
.lb-tbl td{padding:.55rem .7rem;border-bottom:1px solid #f1f5f9;vertical-align:top}
.lb-tbl tr:hover td{background:#fafafa}
.lb-sect{border:1px solid #e2e8f0;border-radius:12px;margin-bottom:.85rem;overflow:hidden}
.lb-sh{background:#f8fafc;padding:.65rem 1rem;font-weight:700;font-size:.88rem;color:#1e293b;cursor:pointer;display:flex;justify-content:space-between;align-items:center}
.lb-sb{padding:1rem;display:none}.lb-sb.open{display:block}
.badge-unit{background:#dbeafe;color:#1d4ed8;padding:2px 9px;border-radius:999px;font-size:.75rem;font-weight:700}
.badge-sub{background:#ede9fe;color:#6d28d9;padding:2px 9px;border-radius:999px;font-size:.75rem;font-weight:700}
.badge-div{background:#d1fae5;color:#047857;padding:2px 9px;border-radius:999px;font-size:.75rem;font-weight:700}
</style>

<!-- Topbar -->
<div class="lb-dark mb-5 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
    <div>
        <h2 class="text-xl font-black">📋 Laporan Bulanan Keperawatan</h2>
        <p class="text-slate-400 text-sm mt-1">Pelaporan bertingkat: Unit → Sub Divisi → Divisi Keperawatan</p>
    </div>
    <div class="flex flex-wrap gap-2 items-center">
        <form method="get" class="flex gap-2 items-center">
            <input type="hidden" name="module" value="laporan_bulanan">
            <input type="hidden" name="page" value="<?=lr_e($page === 'form' ? 'dashboard' : $page)?>">
            <select name="bulan" class="lb-inp" style="width:130px" onchange="this.form.submit()">
                <?php for($i=1;$i<=12;$i++): ?>
                <option value="<?=$i?>" <?=$i===$bulan?'selected':''?>><?=lr_e(lr_bulan($i))?></option>
                <?php endfor; ?>
            </select>
            <select name="tahun" class="lb-inp" style="width:88px" onchange="this.form.submit()">
                <?php for($y=date('Y')-1;$y<=date('Y')+1;$y++): ?>
                <option value="<?=$y?>" <?=$y===$tahun?'selected':''?>><?=$y?></option>
                <?php endfor; ?>
            </select>
        </form>
        <?php if ($page !== 'dashboard'): ?>
        <a href="index.php?module=laporan_bulanan&page=dashboard&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-sec"><i class="fas fa-arrow-left"></i> Kembali</a>
        <?php endif; ?>
    </div>
</div>

<?= $savedMsg . $pulledMsg ?>

<?php if ($page === 'dashboard'): ?>
<!-- ══════════════════ DASHBOARD ══════════════════════════════════ -->

<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-5">
    <div class="lb-card text-center">
        <div class="text-3xl font-black text-blue-600"><?=count($unitReports)?></div>
        <div class="text-sm text-slate-500 mt-1">Laporan Unit</div>
        <div class="text-xs text-slate-400">
            <?=count(array_filter($unitReports,fn($r)=>$r['status']==='submitted'))?> dikirim &nbsp;·&nbsp;
            <?=count(array_filter($unitReports,fn($r)=>$r['status']==='draft'))?> draft
        </div>
    </div>
    <div class="lb-card text-center">
        <div class="text-3xl font-black text-violet-600"><?=count($kasubdivReports)?></div>
        <div class="text-sm text-slate-500 mt-1">Laporan Sub Divisi</div>
    </div>
    <div class="lb-card text-center">
        <div class="text-3xl font-black text-emerald-600"><?=count($kadivReports)?></div>
        <div class="text-sm text-slate-500 mt-1">Laporan Divisi</div>
        <div class="text-xs text-slate-400"><?=count(array_filter($kadivReports,fn($r)=>$r['status']==='final'))?> final</div>
    </div>
</div>

<div class="lb-card mb-5">
    <div class="flex flex-wrap gap-3 items-center justify-between mb-4">
        <h3 class="font-black text-slate-800">Buat / Buka Laporan <?=lr_e("$bulanNama $tahun")?></h3>
        <div class="flex flex-wrap gap-2">
            <?php if ($lbLevel === 'kaunit' || $lbIsAdmin): ?>
            <form method="post" style="display:inline">
                <input type="hidden" name="open_report"><input type="hidden" name="report_level" value="unit">
                <input type="hidden" name="unit_id" value="<?=$lbUnitId?>"><input type="hidden" name="report_type" value="rajal">
                <button class="lb-btn lb-pri"><i class="fas fa-plus"></i> Laporan Unit<?=$lbUnitName?' – '.lr_e($lbUnitName):''?></button>
            </form>
            <?php endif; ?>
            <?php if ($lbLevel === 'kasubdiv' || $lbIsAdmin): ?>
            <?php foreach($subdivisions as $sub): ?>
            <form method="post" style="display:inline">
                <input type="hidden" name="open_report"><input type="hidden" name="report_level" value="kasubdiv">
                <input type="hidden" name="subdivision_id" value="<?=(int)$sub['id']?>">
                <input type="hidden" name="division_id" value="<?=(int)($sub['division_id']??1)?>">
                <input type="hidden" name="report_type" value="<?=lr_e((string)$sub['report_type'])?>">
                <button class="lb-btn lb-sec" style="background:#ede9fe;color:#6d28d9;border-color:#c4b5fd">
                    <i class="fas fa-layer-group"></i> <?=lr_e((string)$sub['name'])?>
                </button>
            </form>
            <?php endforeach; ?>
            <?php endif; ?>
            <?php if ($lbLevel === 'kadiv' || $lbIsAdmin): ?>
            <form method="post" style="display:inline">
                <input type="hidden" name="open_report"><input type="hidden" name="report_level" value="kadiv">
                <input type="hidden" name="division_id" value="1"><input type="hidden" name="report_type" value="gabungan">
                <button class="lb-btn lb-suc"><i class="fas fa-sitemap"></i> Laporan Kadiv</button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <!-- Laporan Unit -->
    <div class="mb-1 font-bold text-slate-600 text-sm flex items-center gap-2 mt-2"><span class="badge-unit">Kepala Unit</span> Laporan Unit</div>
    <?php if ($unitReports): ?>
    <div class="overflow-x-auto mb-4">
    <table class="lb-tbl">
        <thead><tr><th>Unit</th><th>Judul</th><th>Status</th><th>Diperbarui</th><th>Aksi</th></tr></thead>
        <tbody>
        <?php foreach ($unitReports as $r): ?>
        <tr>
            <td class="font-bold"><?=lr_e($r['unit_name']??'-')?></td>
            <td><?=lr_e($r['title'])?></td>
            <td><?=lb_badge((string)$r['status'])?></td>
            <td class="text-xs text-slate-400"><?=date('d/m/Y H:i',strtotime((string)$r['updated_at']))?></td>
            <td>
                <div class="flex gap-1 flex-wrap">
                    <a href="index.php?module=laporan_bulanan&page=form&report_id=<?=(int)$r['id']?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-sec text-xs"><i class="fas fa-edit"></i> <?=in_array($r['status'],['submitted','approved','final'])?'Lihat':'Edit'?></a>
                    <?php if ($r['status']==='submitted' && ($lbIsAdmin || in_array($lbLevel,['kasubdiv','kadiv']))): ?>
                    <a href="index.php?module=laporan_bulanan&page=review&report_id=<?=(int)$r['id']?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-war text-xs"><i class="fas fa-eye"></i> Review</a>
                    <?php endif; ?>
                    <a href="modules/laporan/preview.php?report_id=<?=(int)$r['id']?>" target="_blank" class="lb-btn lb-grn text-xs"><i class="fas fa-print"></i> Preview</a>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php else: ?>
    <p class="text-sm text-slate-400 mb-4 italic">Belum ada laporan unit untuk <?=lr_e("$bulanNama $tahun")?>.</p>
    <?php endif; ?>

    <!-- Laporan Kasubdiv -->
    <div class="mb-1 font-bold text-slate-600 text-sm flex items-center gap-2 mt-3"><span class="badge-sub">Kasubdiv</span> Laporan Sub Divisi</div>
    <?php if ($kasubdivReports): ?>
    <div class="overflow-x-auto mb-4">
    <table class="lb-tbl">
        <thead><tr><th>Judul</th><th>Sub Divisi</th><th>Status</th><th>Diperbarui</th><th>Aksi</th></tr></thead>
        <tbody>
        <?php foreach ($kasubdivReports as $r): ?>
        <tr>
            <td class="font-bold"><?=lr_e($r['title'])?></td>
            <td><?=lr_e($r['subdiv_name']??'-')?></td>
            <td><?=lb_badge((string)$r['status'])?></td>
            <td class="text-xs text-slate-400"><?=date('d/m/Y H:i',strtotime((string)$r['updated_at']))?></td>
            <td>
                <div class="flex gap-1 flex-wrap">
                    <a href="index.php?module=laporan_bulanan&page=form&report_id=<?=(int)$r['id']?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-sec text-xs"><i class="fas fa-edit"></i> Edit</a>
                    <a href="modules/laporan/preview.php?report_id=<?=(int)$r['id']?>" target="_blank" class="lb-btn lb-grn text-xs"><i class="fas fa-print"></i> Preview</a>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php else: ?>
    <p class="text-sm text-slate-400 mb-4 italic">Belum ada laporan sub divisi.</p>
    <?php endif; ?>

    <!-- Laporan Kadiv -->
    <div class="mb-1 font-bold text-slate-600 text-sm flex items-center gap-2 mt-3"><span class="badge-div">Kadiv</span> Laporan Divisi</div>
    <?php if ($kadivReports): ?>
    <div class="overflow-x-auto">
    <table class="lb-tbl">
        <thead><tr><th>Judul</th><th>Status</th><th>Diperbarui</th><th>Aksi</th></tr></thead>
        <tbody>
        <?php foreach ($kadivReports as $r): ?>
        <tr>
            <td class="font-bold"><?=lr_e($r['title'])?></td>
            <td><?=lb_badge((string)$r['status'])?></td>
            <td class="text-xs text-slate-400"><?=date('d/m/Y H:i',strtotime((string)$r['updated_at']))?></td>
            <td>
                <div class="flex gap-1 flex-wrap">
                    <a href="index.php?module=laporan_bulanan&page=form&report_id=<?=(int)$r['id']?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-sec text-xs"><i class="fas fa-edit"></i> Edit</a>
                    <a href="modules/laporan/preview.php?report_id=<?=(int)$r['id']?>" target="_blank" class="lb-btn lb-grn text-xs"><i class="fas fa-print"></i> Preview</a>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php else: ?>
    <p class="text-sm text-slate-400 italic">Belum ada laporan divisi.</p>
    <?php endif; ?>
</div>

<?php
/* Notifikasi laporan unit yang perlu direview */
$needReview = array_filter($unitReports, fn($r) => $r['status'] === 'submitted');
if ($needReview && ($lbIsAdmin || in_array($lbLevel, ['kasubdiv','kadiv']))):
?>
<div class="lb-card" style="border-color:#fbbf24;background:#fffbeb">
    <h3 class="font-black text-amber-800 mb-3"><i class="fas fa-bell text-amber-500"></i> <?=count($needReview)?> laporan unit menunggu review</h3>
    <div class="flex flex-wrap gap-2">
        <?php foreach ($needReview as $r): ?>
        <a href="index.php?module=laporan_bulanan&page=review&report_id=<?=(int)$r['id']?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="lb-btn lb-war text-xs">
            <i class="fas fa-eye"></i> <?=lr_e($r['unit_name']??$r['title'])?>
        </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php elseif ($page === 'form' && $currentReport): ?>
<!-- ══════════════════ FORM LAPORAN ═══════════════════════════════ -->
<?php
$rLevel = (string)$currentReport['report_level'];
$rMode  = $rLevel; // 'unit','kasubdiv','kadiv'
$isReadonly = in_array($currentReport['status'], ['submitted','reviewed','final','approved']) && !$lbIsAdmin;
$levelName  = ['unit'=>'Kepala Unit','kasubdiv'=>'Sub Divisi','kadiv'=>'Divisi Keperawatan'][$rLevel] ?? $rLevel;
$levelBadge = ['unit'=>'badge-unit','kasubdiv'=>'badge-sub','kadiv'=>'badge-div'][$rLevel] ?? '';

/* Laporan bawahan sebagai referensi */
$refReports = [];
$lrDebugInfo = [];
if ($rLevel === 'kasubdiv') {
    $sid = (int)($currentReport['subdivision_id'] ?? 0);
    $stmt = $conn->prepare("SELECT h.*, u.name unit_name FROM monthly_report_headers h LEFT JOIN units u ON u.id=h.unit_id WHERE h.report_level='unit' AND h.bulan=? AND h.tahun=? AND h.subdivision_id=? AND h.status IN('submitted','approved','reviewed','final') ORDER BY u.name");
    $stmt->bind_param('iii', $bulan, $tahun, $sid); $stmt->execute();
    $res = $stmt->get_result(); while($r=$res->fetch_assoc()) $refReports[]=$r; $stmt->close();

    /* DEBUG: cek semua laporan unit bulan ini terlepas dari subdivision_id/status, untuk diagnosa */
    if ($lbIsAdmin) {
        $dstmt = $conn->prepare("SELECT h.id, h.title, h.status, h.subdivision_id, h.unit_id, u.name unit_name FROM monthly_report_headers h LEFT JOIN units u ON u.id=h.unit_id WHERE h.report_level='unit' AND h.bulan=? AND h.tahun=?");
        $dstmt->bind_param('ii', $bulan, $tahun); $dstmt->execute();
        $dres = $dstmt->get_result(); while($d=$dres->fetch_assoc()) $lrDebugInfo[]=$d; $dstmt->close();
        /* Hitung jumlah baris data per laporan untuk diagnosa lebih lanjut */
        foreach ($lrDebugInfo as &$dd) {
            $cstmt = $conn->prepare("SELECT COUNT(*) n FROM monthly_report_rows r JOIN monthly_report_sections s ON s.id=r.section_id WHERE s.report_id=?");
            $cstmt->bind_param('i', $dd['id']); $cstmt->execute();
            $dd['row_count'] = (int)($cstmt->get_result()->fetch_assoc()['n'] ?? 0);
            $cstmt->close();
        }
        unset($dd);
    }
} elseif ($rLevel === 'kadiv') {
    $did = (int)($currentReport['division_id'] ?? 1);
    $stmt = $conn->prepare("SELECT h.*, ns.name subdiv_name FROM monthly_report_headers h LEFT JOIN nursing_subdivisions ns ON ns.id=h.subdivision_id WHERE h.report_level='kasubdiv' AND h.bulan=? AND h.tahun=? AND h.division_id=? ORDER BY h.id");
    $stmt->bind_param('iii', $bulan, $tahun, $did); $stmt->execute();
    $res = $stmt->get_result(); while($r=$res->fetch_assoc()) $refReports[]=$r; $stmt->close();
}

/* Sections */
$reportSections = lr_sections_with_rows($conn, $repId);
?>

<!-- Header laporan -->
<div class="flex flex-wrap gap-3 items-start justify-between mb-4">
    <div>
        <span class="<?=$levelBadge?>"><?=lr_e($levelName)?></span>
        <h2 class="text-xl font-black text-slate-800 mt-1"><?=lr_e((string)$currentReport['title'])?></h2>
        <div class="mt-1 flex items-center gap-2">
            <?=lb_badge((string)$currentReport['status'])?>
            <span class="text-xs text-slate-400"><?=lr_e("$bulanNama $tahun")?></span>
        </div>
    </div>
    <div class="flex flex-wrap gap-2">
        <a href="modules/laporan/preview.php?report_id=<?=$repId?>" target="_blank" class="lb-btn lb-grn"><i class="fas fa-print"></i> Preview & Cetak</a>
        <?php if (!$isReadonly && $rLevel !== 'unit' && $refReports): ?>
        <form method="post" onsubmit="return confirm('Tarik data dari semua laporan bawahan yang sudah dikirim?')">
            <input type="hidden" name="pull_children"><input type="hidden" name="report_id" value="<?=$repId?>">
            <input type="hidden" name="report_level" value="<?=lr_e($rLevel)?>">
            <input type="hidden" name="subdivision_id" value="<?=(int)($currentReport['subdivision_id']??0)?>">
            <input type="hidden" name="division_id" value="<?=(int)($currentReport['division_id']??1)?>">
            <button class="lb-btn lb-war"><i class="fas fa-download"></i> Tarik Data Bawahan</button>
        </form>
        <?php endif; ?>
    </div>
</div>

<!-- DEBUG INFO (hanya admin) -->
<?php if ($lbIsAdmin && !empty($lrDebugInfo)): ?>
<div class="lb-card mb-4" style="background:#fef9c3;border-color:#fde047">
    <h4 class="font-black text-amber-800 mb-2 text-sm">🔍 Debug: Semua Laporan Unit Bulan Ini (subdivision target = <?=$sid?? '?'?>)</h4>
    <table class="lb-tbl text-xs">
        <thead><tr><th>ID</th><th>Unit</th><th>Judul</th><th>Status</th><th>subdivision_id</th><th>unit_id</th><th>Jml Baris Data</th><th>Akan Ditarik?</th><th>Aksi</th></tr></thead>
        <tbody>
        <?php
        $lrRanapNames = ['canigara','cempaka','ruang bayi','bayi','cendana','icu','nicu'];
        foreach($lrDebugInfo as $d):
            $subOk = (int)$d['subdivision_id']===(int)($sid??0);
            $statusOk = in_array($d['status'], ['submitted','approved','reviewed','final']);
            $willPull = $subOk && $statusOk;
            $unitNameLower = strtolower((string)($d['unit_name'] ?? ''));
            $looksLikeRanap = false;
            foreach($lrRanapNames as $rn){ if(str_contains($unitNameLower, $rn)){ $looksLikeRanap = true; break; } }
            $hasData = ($d['row_count'] ?? 0) > 0;
            $canFix = $hasData && !$willPull && ($sid??0) > 0;
        ?>
        <tr style="<?= $willPull ? 'background:#dcfce7' : 'background:#fee2e2' ?>">
            <td><?=$d['id']?></td><td><?=lr_e($d['unit_name']??'-')?><?= $looksLikeRanap ? ' <span style="color:#0891b2;font-weight:700">(harusnya Ranap)</span>' : '' ?></td>
            <td><?=lr_e($d['title'])?></td>
            <td><?=lr_e($d['status'])?></td><td><?=$d['subdivision_id']??'NULL'?></td><td><?=$d['unit_id']??'NULL'?></td>
            <td><?=$d['row_count']??0?></td>
            <td><?= $willPull ? '✅ Ya' : ($subOk ? '❌ Status belum final' : '❌ Subdivisi beda') ?></td>
            <td>
            <?php if ($canFix): ?>
                <form method="post" style="display:inline" onsubmit="return confirm('Set subdivision_id unit ini ke <?=$sid?> (Ranap) dan submit laporannya?')">
                    <input type="hidden" name="force_submit_unit"><input type="hidden" name="force_report_id" value="<?=$d['id']?>">
                    <input type="hidden" name="force_unit_id" value="<?=(int)($d['unit_id']??0)?>">
                    <input type="hidden" name="force_subdivision_id" value="<?=(int)($sid??0)?>">
                    <button data-no-passcode="1" class="lb-btn lb-war text-xs">🔧 Perbaiki &amp; Submit</button>
                </form>
            <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <p class="text-xs text-amber-700 mt-2">Baris merah = subdivision_id TIDAK cocok dengan laporan kasubdiv ini, atau status belum submitted/approved.</p>
</div>
<?php endif; ?>

<!-- Referensi laporan bawahan -->
<?php if ($refReports): ?>
<div class="lb-card mb-4" style="background:#f0fdf4;border-color:#bbf7d0">
    <h4 class="font-black text-emerald-800 mb-2 text-sm"><i class="fas fa-link"></i> Laporan <?=$rLevel==='kasubdiv'?'Unit':'Sub Divisi'?> Tersedia (referensi)</h4>
    <div class="flex flex-wrap gap-2">
        <?php foreach ($refReports as $rf): ?>
        <a href="modules/laporan/preview.php?report_id=<?=(int)$rf['id']?>" target="_blank" class="lb-btn lb-sec text-xs">
            <i class="fas fa-file-alt"></i> <?=lr_e($rf['unit_name']??$rf['subdiv_name']??$rf['title'])?>
            <?=lb_badge((string)$rf['status'])?>
        </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Form -->
<form method="post" id="lbForm">
<input type="hidden" name="report_id" value="<?=$repId?>">

<div class="lb-card mb-4">
    <h3 class="font-black text-slate-700 mb-3">Identitas & Pendahuluan</h3>
    <div class="grid grid-cols-1 gap-3">
        <div>
            <label class="text-xs font-bold text-slate-500 uppercase">Judul Laporan</label>
            <input name="title" class="lb-inp mt-1" value="<?=lr_e((string)$currentReport['title'])?>" <?=$isReadonly?'readonly':''?>>
        </div>
        <div>
            <label class="text-xs font-bold text-slate-500 uppercase">BAB I — Pendahuluan</label>
            <textarea name="pendahuluan" rows="4" class="lb-inp mt-1" <?=$isReadonly?'readonly':''?>><?=lr_e((string)($currentReport['pendahuluan']??''))?></textarea>
        </div>
    </div>
</div>

<?php foreach ($reportSections as $sec):
    $cols = lr_columns_for_mode((string)$sec['section_code'], $rMode);
    $nrows = count($sec['rows']);
?>
<div class="lb-sect">
    <div class="lb-sh" onclick="this.nextElementSibling.classList.toggle('open')">
        <span><?=lr_e((string)$sec['section_title'])?></span>
        <span class="text-slate-400 text-sm"><?=$nrows?> baris <i class="fas fa-chevron-down ml-1"></i></span>
    </div>
    <div class="lb-sb <?=$nrows>0?'open':''?>">
        <label class="text-xs font-bold text-slate-500 uppercase">Narasi / Analisa</label>
        <textarea name="section[<?=(int)$sec['id']?>][intro_text]" rows="3" class="lb-inp mt-1 mb-3" <?=$isReadonly?'readonly':''?>><?=lr_e((string)($sec['intro_text']??''))?></textarea>
        <?php lr_render_rows_editor($sec, $cols, $rMode); ?>
    </div>
</div>
<?php endforeach; ?>

<div class="lb-card mt-4">
    <h3 class="font-black text-slate-700 mb-3">BAB III — Simpulan & Penutup</h3>
    <div class="grid gap-3">
        <div>
            <label class="text-xs font-bold text-slate-500 uppercase">Kesimpulan / Analisa Akhir</label>
            <textarea name="simpulan" rows="4" class="lb-inp mt-1" <?=$isReadonly?'readonly':''?> placeholder="Kesimpulan laporan..."><?=lr_e((string)($currentReport['simpulan']??''))?></textarea>
        </div>
        <div>
            <label class="text-xs font-bold text-slate-500 uppercase">Penutup</label>
            <textarea name="penutup" rows="2" class="lb-inp mt-1" <?=$isReadonly?'readonly':''?> placeholder="Kata penutup..."><?=lr_e((string)($currentReport['penutup']??''))?></textarea>
        </div>
        <div class="grid grid-cols-2 gap-3">
            <div><label class="text-xs font-bold text-slate-500 uppercase">Nama Penandatangan</label>
            <input name="signed_name" class="lb-inp mt-1" value="<?=lr_e((string)($currentReport['signed_name']??''))?>" <?=$isReadonly?'readonly':''?>></div>
            <div><label class="text-xs font-bold text-slate-500 uppercase">Jabatan</label>
            <input name="signed_position" class="lb-inp mt-1" value="<?=lr_e((string)($currentReport['signed_position']??''))?>" <?=$isReadonly?'readonly':''?>></div>
        </div>
    </div>
</div>

<?php if (!$isReadonly): ?>
<div class="sticky bottom-3 z-20 flex flex-wrap gap-2 bg-white/95 backdrop-blur p-3 rounded-2xl border shadow-lg mt-4">
    <button name="save_report" value="1" class="lb-btn lb-suc"><i class="fas fa-save"></i> Simpan Draft</button>
    <button name="submit_report" value="1" class="lb-btn lb-pri" onclick="return confirm('Kirim laporan ke level berikutnya?')"><i class="fas fa-paper-plane"></i> Submit Laporan</button>
</div>
<?php endif; ?>
</form>

<?php elseif ($page === 'review' && $repId > 0 && $currentReport): ?>
<!-- ══════════════════ REVIEW ══════════════════════════════════════ -->
<?php
$fullSections = lr_sections_with_rows($conn, $repId);
$rLevel = (string)$currentReport['report_level'];
$rMode  = $rLevel;
?>
<div class="lb-card mb-4">
    <div class="flex items-start justify-between flex-wrap gap-3">
        <div>
            <h2 class="text-xl font-black"><?=lr_e((string)$currentReport['title'])?></h2>
            <div class="mt-1"><?=lb_badge((string)$currentReport['status'])?></div>
        </div>
        <a href="modules/laporan/preview.php?report_id=<?=$repId?>" target="_blank" class="lb-btn lb-grn"><i class="fas fa-print"></i> Preview</a>
    </div>
    <?php if ($lbIsAdmin || in_array($lbLevel,['kasubdiv','kadiv'])): ?>
    <?php if (in_array($currentReport['status'],['submitted','reviewed'])): ?>
    <div class="border-t mt-4 pt-4 flex flex-wrap gap-3">
        <form method="post" class="flex gap-2 items-end">
            <input type="hidden" name="report_id" value="<?=$repId?>">
            <div><label class="text-xs font-bold text-slate-500">Catatan</label>
            <input name="notes" class="lb-inp mt-1" style="min-width:220px" placeholder="Catatan persetujuan..."></div>
            <button name="approve_report" value="1" class="lb-btn lb-suc"><i class="fas fa-check"></i> Setujui</button>
        </form>
        <form method="post" class="flex gap-2 items-end" onsubmit="return confirm('Tolak laporan ini?')">
            <input type="hidden" name="report_id" value="<?=$repId?>">
            <div><label class="text-xs font-bold text-slate-500 text-red-500">Alasan penolakan *</label>
            <input name="notes" class="lb-inp mt-1" style="min-width:220px" placeholder="Tulis alasan..." required></div>
            <button name="reject_report" value="1" class="lb-btn lb-dan"><i class="fas fa-times"></i> Tolak</button>
        </form>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>

<?php if ($currentReport['pendahuluan']): ?>
<div class="lb-card mb-3"><h3 class="font-bold text-slate-700 mb-2">Pendahuluan</h3><p class="text-sm whitespace-pre-wrap"><?=lr_e((string)$currentReport['pendahuluan'])?></p></div>
<?php endif; ?>

<?php foreach ($fullSections as $sec):
    $cols = lr_columns_for_mode((string)$sec['section_code'], $rMode);
    if (empty($sec['rows']) && empty($sec['intro_text'])) continue;
?>
<div class="lb-card mb-3">
    <h4 class="font-bold text-slate-700 mb-2"><?=lr_e((string)$sec['section_title'])?></h4>
    <?php if ($sec['intro_text']): ?><p class="text-sm mb-2 text-slate-600 whitespace-pre-wrap"><?=lr_e((string)$sec['intro_text'])?></p><?php endif; ?>
    <?php if ($sec['rows']): ?>
    <div class="overflow-x-auto">
    <table class="lb-tbl">
        <thead><tr><th>No</th><?php foreach($cols as $c): ?><th><?=lr_e($c)?></th><?php endforeach; ?><th>Catatan</th></tr></thead>
        <tbody>
        <?php foreach($sec['rows'] as $ri=>$row): ?>
        <tr>
            <td class="text-center text-slate-400"><?=$ri+1?></td>
            <?php for($ci=1;$ci<=count($cols);$ci++): ?><td><?=nl2br(lr_e((string)($row['col'.$ci]??'')))?></td><?php endfor; ?>
            <td><?=nl2br(lr_e((string)($row['notes']??'')))?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<?php if ($currentReport['simpulan']): ?>
<div class="lb-card mb-3"><h3 class="font-bold text-slate-700 mb-2">Kesimpulan</h3><p class="text-sm whitespace-pre-wrap"><?=lr_e((string)$currentReport['simpulan'])?></p></div>
<?php endif; ?>

<?php else: ?>
<?php echo "<script>location.replace(\"index.php?module=laporan_bulanan&page=dashboard&bulan=$bulan&tahun=$tahun\");</script>"; return; ?>
<?php endif; ?>
</div><!-- /laporan-bulanan-wrapper -->
<?php if(ob_get_level()) ob_end_flush(); ?>