<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../../config/database.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$conn = getConnection();

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function bulanIndo(int $bulan): string
{
    $arr = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
        5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
    ];
    return $arr[$bulan] ?? '-';
}

function postText(string $key): string
{
    return trim((string)($_POST[$key] ?? ''));
}

function postInt(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function getCurrentRole(): string
{
    $raw = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user')));
    return $raw === 'superadmin' ? 'admin' : $raw;
}

function getReportTypeName(string $type): string
{
    return match ($type) {
        'ranap' => 'RAWAT INAP',
        'gabungan' => 'GABUNGAN',
        default => 'RAWAT JALAN',
    };
}

function getUnitSectionTemplates(): array
{
    return [
        'data_pelayanan' => 'A. Data Pelayanan Unit',
        'keterlambatan_staf' => 'B. Data Keterlambatan Staf',
        'capaian_rka' => 'C. Capaian RKA',
        'kejadian_keselamatan' => 'D. Kejadian Keselamatan Pasien',
        'permasalahan_unit' => 'E. Permasalahan Unit',
    ];
}

function getSectionColumns(string $code): array
{
    return match ($code) {
        'ketenagaan' => ['Jumlah Tenaga', 'Komposisi', 'Keterangan'],
        'jumlah_pasien' => ['Jumlah Pasien / Aktivitas', 'Jumlah Perawat', 'Rasio / BOR', 'Analisa'],
        'makp' => ['Jumlah PP', 'Jumlah PA', 'Metode / Capaian', 'Kendala', 'Rencana Tindak Lanjut'],
        'permasalahan' => ['Hari / Tanggal', 'Permasalahan', 'Unit Terkait', 'Hasil Koordinasi', 'RTL / Realisasi'],
        'mutu' => ['Indikator / Monev', 'Bulan', 'Capaian', 'Analisa / RTL'],
        'ikp' => ['Jenis Insiden', 'Tanggal', 'Kronologi Singkat', 'Tindak Lanjut', 'Keterangan'],
        'data_pelayanan' => [
            'Jumlah Pasien / Bulan',
            'Jumlah Staf',
            'Jumlah Staf Sakit',
            'Lama Sakit',
            'Penyebab Sakit',
            'Jumlah Staf Hamil',
            'BOR Unit',
            'Rasio Pasien : Perawat',
            'Beban Kerja Unit',
        ],
        'keterlambatan_staf' => [
            'Nama Staf',
            'Jumlah Terlambat',
            'Total Menit Terlambat',
            'Keterangan',
        ],
        'capaian_rka' => [
            'Kegiatan / Project',
            'Bulan',
            'Capaian',
            'Tindak Lanjut',
        ],
        'kejadian_keselamatan' => [
            'Jenis Kejadian',
            'Siapa yang Menemukan',
            'Tindakan yang Sudah Dilakukan',
            'Keterangan',
        ],
        'permasalahan_unit' => [
            'Permasalahan',
            'Unit Terkait',
            'Solusi',
            'Keterangan',
        ],
        default => ['Uraian', 'Bulan', 'Capaian', 'Keterangan / RTL'],
    };
}

function getSectionColumnsByTitle(string $code, string $title): array
{
    $columns = getSectionColumns($code);
    $title = strtolower($title);

    if (str_contains($title, 'ketenagaan')) {
        return ['Jumlah Tenaga', 'Komposisi', 'Kualifikasi / Pendidikan', 'Keterangan'];
    }
    if (str_contains($title, 'jumlah pasien') || str_contains($title, 'aktivitas pelayanan')) {
        return ['Jumlah Pasien / Aktivitas', 'Jumlah Perawat', 'Rasio / BOR', 'Analisa'];
    }
    if (str_contains($title, 'capaian rka') || str_contains($title, 'program kerja')) {
        return ['Kegiatan / Project', 'Bulan', 'Capaian', 'Tindak Lanjut'];
    }
    if (str_contains($title, 'makp') || str_contains($title, 'asuhan keperawatan')) {
        return ['Jumlah PP', 'Jumlah PA', 'Metode / Capaian', 'Kendala', 'Rencana Tindak Lanjut'];
    }
    if (str_contains($title, 'permasalahan')) {
        return ['Hari / Tanggal', 'Permasalahan', 'Unit Terkait', 'Hasil Koordinasi', 'RTL / Realisasi'];
    }
    if (str_contains($title, 'mutu') || str_contains($title, 'monev')) {
        return ['Indikator / Monev', 'Bulan', 'Capaian', 'Analisa / RTL'];
    }
    if (str_contains($title, 'insiden') || str_contains($title, 'keselamatan pasien')) {
        return ['Jenis Insiden', 'Tanggal', 'Kronologi Singkat', 'Tindak Lanjut', 'Keterangan'];
    }

    return $columns;
}

function resolveUserUnitId(mysqli $conn): int
{
    $sessionUnitId = (int)($_SESSION['unit_id'] ?? $_SESSION['user']['unit_id'] ?? 0);
    if ($sessionUnitId > 0) {
        return $sessionUnitId;
    }

    $sessionUnitName = trim((string)($_SESSION['unit'] ?? $_SESSION['user']['unit'] ?? $_SESSION['unit_name'] ?? ''));
    if ($sessionUnitName !== '') {
        $stmt = $conn->prepare("SELECT id FROM units WHERE is_active = 1 AND (name = ? OR code = ?) LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('ss', $sessionUnitName, $sessionUnitName);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            if ($row) {
                return (int)$row['id'];
            }
        }
    }

    $sessionEmployeeId = (int)($_SESSION['employee_id'] ?? $_SESSION['user']['employee_id'] ?? $_SESSION['user_id'] ?? 0);
    if ($sessionEmployeeId > 0) {
        $stmt = $conn->prepare("SELECT unit_id FROM employees WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('i', $sessionEmployeeId);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            if ($row && (int)$row['unit_id'] > 0) {
                return (int)$row['unit_id'];
            }
        }
    }

    return 0;
}

function getUnitInfo(mysqli $conn, int $unitId): ?array
{
    $stmt = $conn->prepare("
        SELECT u.*, ns.name AS subdivision_name, nd.name AS division_name
        FROM units u
        LEFT JOIN nursing_subdivisions ns ON ns.id = u.subdivision_id
        LEFT JOIN nursing_divisions nd ON nd.id = u.division_id
        WHERE u.id = ? LIMIT 1
    ");
    $stmt->bind_param('i', $unitId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function findOrCreateUnitReport(
    mysqli $conn,
    int $unitId,
    int $subdivisionId,
    int $divisionId,
    int $bulan,
    int $tahun,
    int $userId,
    string $reportType
): int {
    $stmt = $conn->prepare("
        SELECT id
        FROM monthly_report_headers
        WHERE report_level = 'unit'
          AND unit_id = ?
          AND bulan = ?
          AND tahun = ?
        LIMIT 1
    ");
    $stmt->bind_param('iii', $unitId, $bulan, $tahun);
    $stmt->execute();
    $existing = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($existing) {
        return (int)$existing['id'];
    }

    $unitInfo = getUnitInfo($conn, $unitId);
    $unitName = strtoupper((string)($unitInfo['name'] ?? 'UNIT'));
    $title = 'LAPORAN BULANAN UNIT ' . $unitName . ' - ' . bulanIndo($bulan) . ' ' . $tahun;

    $stmt = $conn->prepare("
        INSERT INTO monthly_report_headers
        (report_type, report_level, unit_id, subdivision_id, division_id, bulan, tahun, title, status, created_by, updated_by)
        VALUES (?, 'unit', ?, ?, ?, ?, ?, ?, 'draft', ?, ?)
    ");
    $stmt->bind_param(
        'siiiiisii',
        $reportType,
        $unitId,
        $subdivisionId,
        $divisionId,
        $bulan,
        $tahun,
        $title,
        $userId,
        $userId
    );
    $stmt->execute();
    $reportId = (int)$stmt->insert_id;
    $stmt->close();

    $urut = 1;
    foreach (getUnitSectionTemplates() as $code => $titleSection) {
        $stmt = $conn->prepare("
            INSERT INTO monthly_report_sections (report_id, section_code, section_title, urut)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param('issi', $reportId, $code, $titleSection, $urut);
        $stmt->execute();
        $stmt->close();
        $urut++;
    }

    return $reportId;
}

function getReportHeader(mysqli $conn, int $reportId): ?array
{
    $stmt = $conn->prepare("SELECT * FROM monthly_report_headers WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $reportId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function getSections(mysqli $conn, int $reportId): array
{
    $rows = [];
    $stmt = $conn->prepare("SELECT * FROM monthly_report_sections WHERE report_id = ? ORDER BY urut ASC, id ASC");
    $stmt->bind_param('i', $reportId);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function getSectionRows(mysqli $conn, int $sectionId): array
{
    $rows = [];
    $stmt = $conn->prepare("SELECT * FROM monthly_report_rows WHERE section_id = ? ORDER BY urut ASC, id ASC");
    $stmt->bind_param('i', $sectionId);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function saveSectionRows(mysqli $conn, int $sectionId, array $rows): void
{
    $stmt = $conn->prepare("DELETE FROM monthly_report_rows WHERE section_id = ?");
    $stmt->bind_param('i', $sectionId);
    $stmt->execute();
    $stmt->close();

    $urut = 1;
    foreach ($rows as $r) {
        $hasValue = false;
        for ($i = 1; $i <= 10; $i++) {
            if (trim((string)($r["col{$i}"] ?? '')) !== '') {
                $hasValue = true;
                break;
            }
        }
        if (!$hasValue && trim((string)($r['notes'] ?? '')) === '') {
            continue;
        }

        $stmt = $conn->prepare("
            INSERT INTO monthly_report_rows
            (section_id, urut, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $notes = $r['notes'] ?? '';
        $col1 = $r['col1'] ?? '';
        $col2 = $r['col2'] ?? '';
        $col3 = $r['col3'] ?? '';
        $col4 = $r['col4'] ?? '';
        $col5 = $r['col5'] ?? '';
        $col6 = $r['col6'] ?? '';
        $col7 = $r['col7'] ?? '';
        $col8 = $r['col8'] ?? '';
        $col9 = $r['col9'] ?? '';
        $col10 = $r['col10'] ?? '';
        $stmt->bind_param(
            'iisssssssssss',
            $sectionId,
            $urut,
            $col1,
            $col2,
            $col3,
            $col4,
            $col5,
            $col6,
            $col7,
            $col8,
            $col9,
            $col10,
            $notes
        );
        $stmt->execute();
        $stmt->close();
        $urut++;
    }
}

$userId = (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
$userRole = getCurrentRole();

$allowedRoles = ['admin', 'kepala_unit', 'user', 'editor'];
if (!in_array($userRole, $allowedRoles, true)) {
    echo '<div class="p-6"><div class="bg-red-50 text-red-700 border border-red-200 rounded-xl p-4">Akses form laporan unit ditolak.</div></div>';
    return;
}

$selectedUnitIdFromUrl = (int)($_GET['unit_id'] ?? 0);
$bulan = (int)($_GET['bulan'] ?? date('n'));
$tahun = (int)($_GET['tahun'] ?? date('Y'));
if ($bulan < 1 || $bulan > 12) $bulan = (int)date('n');
if ($tahun < 2020 || $tahun > 2100) $tahun = (int)date('Y');

$userUnitId = resolveUserUnitId($conn);
$selectedUnitId = $userRole === 'admin'
    ? (int)($_GET['unit_id'] ?? $_POST['unit_id'] ?? $userUnitId)
    : $userUnitId;

$message = '';
$messageType = 'success';

$unitOptions = [];
if ($userRole === 'admin') {
    $res = $conn->query("SELECT id, name, code, report_type FROM units WHERE is_active = 1 ORDER BY name ASC");
    while ($row = $res->fetch_assoc()) {
        $unitOptions[] = $row;
    }
}

$reportId = 0;
$unit = null;
$header = null;
$sections = [];
$sectionRows = [];

if ($selectedUnitId > 0) {
    $unit = getUnitInfo($conn, $selectedUnitId);

    if ($unit) {
        $reportType = (string)($unit['report_type'] ?? 'rajal');
        $subdivisionId = (int)($unit['subdivision_id'] ?? 0);
        $divisionId = (int)($unit['division_id'] ?? 0);

        $reportId = findOrCreateUnitReport(
            $conn,
            $selectedUnitId,
            $subdivisionId,
            $divisionId,
            $bulan,
            $tahun,
            $userId,
            $reportType
        );

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $formType = $_POST['form_type'] ?? '';

            try {
                if ($formType === 'save_unit_report') {
                    $title = postText('title');
                    $pendahuluan = postText('pendahuluan');
                    $simpulan = postText('simpulan');
                    $penutup = postText('penutup');
                    $signedName = postText('signed_name');
                    $signedPosition = postText('signed_position');
                    $status = (($_POST['submit_final'] ?? '0') === '1') ? 'submitted' : 'draft';
                    $submittedAt = $status === 'submitted' ? date('Y-m-d H:i:s') : null;

                    $stmt = $conn->prepare("
                        UPDATE monthly_report_headers
                        SET title = ?,
                            pendahuluan = ?,
                            simpulan = ?,
                            penutup = ?,
                            signed_name = ?,
                            signed_position = ?,
                            status = ?,
                            updated_by = ?,
                            submitted_at = ?
                        WHERE id = ?
                    ");
                    $stmt->bind_param(
                        'sssssssisi',
                        $title,
                        $pendahuluan,
                        $simpulan,
                        $penutup,
                        $signedName,
                        $signedPosition,
                        $status,
                        $userId,
                        $submittedAt,
                        $reportId
                    );
                    $stmt->execute();
                    $stmt->close();

                    $sections = getSections($conn, $reportId);
                    foreach ($sections as $section) {
                        $sectionId = (int)$section['id'];
                        $code = (string)$section['section_code'];

                        $introText = postText('intro_' . $code);
                        $stmt = $conn->prepare("UPDATE monthly_report_sections SET intro_text = ? WHERE id = ?");
                        $stmt->bind_param('si', $introText, $sectionId);
                        $stmt->execute();
                        $stmt->close();

                        $rows = [];
                        $rowCount = count($_POST[$code . '_row_index'] ?? []);
                        for ($i = 0; $i < $rowCount; $i++) {
                            $row = [];
                            for ($c = 1; $c <= 10; $c++) {
                                $row["col{$c}"] = trim((string)($_POST[$code . "_col{$c}"][$i] ?? ''));
                            }
                            $row['notes'] = trim((string)($_POST[$code . '_notes'][$i] ?? ''));
                            $rows[] = $row;
                        }

                        saveSectionRows($conn, $sectionId, $rows);
                    }

                    if ($status === 'submitted') {
                        $actionType = 'submit';
                        $actionRole = $userRole;
                        $notes = 'Laporan unit dikirim ke Kasubdiv';

                        $stmt = $conn->prepare("
                            INSERT INTO monthly_report_approvals (report_id, action_type, action_by, action_role, notes)
                            VALUES (?, ?, ?, ?, ?)
                        ");
                        $stmt->bind_param('isiss', $reportId, $actionType, $userId, $actionRole, $notes);
                        $stmt->execute();
                        $stmt->close();
                    }

                    $message = $status === 'submitted'
                        ? 'Laporan unit berhasil disimpan dan dikirim ke Kasubdiv.'
                        : 'Draft laporan unit berhasil disimpan.';
                }
            } catch (Throwable $e) {
                $message = 'Terjadi error: ' . $e->getMessage();
                $messageType = 'error';
            }
        }

        $header = getReportHeader($conn, $reportId);
        $sections = getSections($conn, $reportId);
        foreach ($sections as $sec) {
            $rows = getSectionRows($conn, (int)$sec['id']);
            if (!$rows) {
                $blankCount = $sec['section_code'] === 'data_pelayanan' ? 1 : 3;
                $rows = array_fill(0, $blankCount, [
                    'col1' => '', 'col2' => '', 'col3' => '', 'col4' => '', 'col5' => '',
                    'col6' => '', 'col7' => '', 'col8' => '', 'col9' => '', 'col10' => '',
                    'notes' => '',
                ]);
            }
            $sectionRows[$sec['section_code']] = $rows;
        }
    }
}
?>
<style>
.tbl{width:100%;border-collapse:collapse}
.tbl th,.tbl td{border:1px solid #e5e7eb;padding:8px;vertical-align:top}
.tbl th{background:#f8fafc;font-size:12px;font-weight:700;color:#334155}
.input{width:100%;border:1px solid #cbd5e1;border-radius:10px;padding:8px 10px;font-size:14px}
.textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;padding:10px;font-size:14px}
.card{background:#fff;border:1px solid #e2e8f0;border-radius:18px;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.card-head{padding:16px 20px;border-bottom:1px solid #e2e8f0;background:#f8fafc}
.card-body{padding:20px}
.btn{padding:10px 14px;border-radius:12px;font-weight:600;display:inline-flex;align-items:center;gap:6px}
.btn-sm{padding:6px 10px;border-radius:10px;font-size:12px}
</style>

<div class="p-6 space-y-6">
    <div class="card">
        <div class="card-body flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h1 class="text-2xl font-bold text-slate-800">Laporan Bulanan Unit</h1>
                <p class="text-sm text-slate-500">Form laporan unit untuk dikirim ke Kasubdiv setiap bulan.</p>
            </div>

            <form method="get" action="index.php" class="flex flex-wrap gap-3 items-end">
                <input type="hidden" name="module" value="laporan_bulanan">
                <input type="hidden" name="page" value="unit_form">

                <?php if ($userRole === 'admin'): ?>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Unit</label>
                        <select name="unit_id" class="input">
                            <option value="">-- pilih unit --</option>
                            <?php foreach ($unitOptions as $opt): ?>
                                <option value="<?= (int)$opt['id'] ?>" <?= $selectedUnitId === (int)$opt['id'] ? 'selected' : '' ?>>
                                    <?= e($opt['name']) ?> (<?= e(strtoupper((string)$opt['report_type'])) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endif; ?>

                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Bulan</label>
                    <select name="bulan" class="input">
                        <?php for ($i = 1; $i <= 12; $i++): ?>
                            <option value="<?= $i ?>" <?= $bulan === $i ? 'selected' : '' ?>><?= e(bulanIndo($i)) ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Tahun</label>
                    <select name="tahun" class="input">
                        <?php for ($y = date('Y') - 2; $y <= date('Y') + 2; $y++): ?>
                            <option value="<?= $y ?>" <?= $tahun === $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <button type="submit" class="btn bg-blue-600 text-white hover:bg-blue-700">Tampilkan</button>
            </form>
        </div>
    </div>

    <?php if ($message !== ''): ?>
        <div class="rounded-2xl p-4 <?= $messageType === 'error' ? 'bg-red-50 border border-red-200 text-red-700' : 'bg-emerald-50 border border-emerald-200 text-emerald-700' ?>">
            <?= e($message) ?>
        </div>
    <?php endif; ?>

    <?php if ($selectedUnitId <= 0): ?>
        <div class="bg-amber-50 text-amber-700 border border-amber-200 rounded-xl p-4">
            Unit belum terdeteksi. <?= $userRole === 'admin' ? 'Silakan pilih unit di atas.' : 'Pastikan session user memiliki unit_id / unit yang valid.' ?>
        </div>
    <?php elseif (!empty($unit) && $reportId > 0): ?>
        <div class="flex flex-wrap gap-3">
            <a href="index.php?module=laporan_bulanan&page=preview&report_id=<?= $reportId ?>" target="_blank"
               class="btn bg-slate-700 text-white hover:bg-slate-800">Preview</a>
            <a href="index.php?module=laporan_bulanan&page=export_word&report_id=<?= $reportId ?>"
               class="btn bg-emerald-600 text-white hover:bg-emerald-700">Export Word</a>
        </div>

        <form method="post" class="space-y-6">
            <input type="hidden" name="module" value="laporan_bulanan">
            <input type="hidden" name="page" value="unit_form">
            <input type="hidden" name="unit_id" value="<?= (int)$selectedUnitId ?>">
            <input type="hidden" name="bulan" value="<?= (int)$bulan ?>">
            <input type="hidden" name="tahun" value="<?= (int)$tahun ?>">
            <input type="hidden" name="form_type" value="save_unit_report">

            <div class="card">
                <div class="card-head">
                    <h2 class="text-lg font-bold text-slate-800">Header Laporan</h2>
                </div>
                <div class="card-body space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Judul</label>
                            <input type="text" name="title" class="input" value="<?= e($header['title'] ?? '') ?>">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Unit</label>
                            <input type="text" class="input bg-slate-50" readonly value="<?= e((string)$unit['name']) ?>">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Jenis</label>
                            <input type="text" class="input bg-slate-50" readonly value="<?= e(getReportTypeName((string)$header['report_type'])) ?>">
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-2">Pendahuluan</label>
                        <textarea name="pendahuluan" rows="5" class="textarea"><?= e($header['pendahuluan'] ?? '') ?></textarea>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Penanda Tangan</label>
                            <input type="text" name="signed_name" class="input" value="<?= e($header['signed_name'] ?? ($_SESSION['full_name'] ?? '')) ?>">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Jabatan Penanda Tangan</label>
                            <input type="text" name="signed_position" class="input" value="<?= e($header['signed_position'] ?? ($_SESSION['jabatan'] ?? 'Kepala Unit')) ?>">
                        </div>
                    </div>
                </div>
            </div>

            <?php foreach ($sections as $section): ?>
                <?php
                $code = (string)$section['section_code'];
                $rows = $sectionRows[$code] ?? [];
                $columns = getSectionColumnsByTitle($code, (string)$section['section_title']);
                ?>
                <div class="card">
                    <div class="card-head flex items-center justify-between">
                        <h2 class="text-lg font-bold text-slate-800"><?= e($section['section_title']) ?></h2>
                        <button type="button" class="btn btn-sm bg-blue-50 text-blue-700 border border-blue-200"
                                onclick="addRow('<?= e($code) ?>', <?= count($columns) ?>)">
                            + Tambah Baris
                        </button>
                    </div>
                    <div class="card-body space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Pengantar Section</label>
                            <textarea name="intro_<?= e($code) ?>" rows="3" class="textarea"><?= e($section['intro_text'] ?? '') ?></textarea>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="tbl">
                                <thead>
                                    <tr>
                                        <th style="width:60px;">No</th>
                                        <?php foreach ($columns as $col): ?>
                                            <th><?= e($col) ?></th>
                                        <?php endforeach; ?>
                                        <th style="min-width:180px;">Catatan</th>
                                    </tr>
                                </thead>
                                <tbody id="tbody_<?= e($code) ?>">
                                    <?php foreach ($rows as $idx => $row): ?>
                                        <tr>
                                            <td>
                                                <?= $idx + 1 ?>
                                                <input type="hidden" name="<?= e($code) ?>_row_index[]" value="<?= $idx ?>">
                                            </td>
                                            <?php for ($c = 1; $c <= count($columns); $c++): ?>
                                                <td>
                                                    <textarea name="<?= e($code) ?>_col<?= $c ?>[]" rows="2" class="textarea"><?= e($row["col{$c}"] ?? '') ?></textarea>
                                                </td>
                                            <?php endfor; ?>
                                            <td>
                                                <textarea name="<?= e($code) ?>_notes[]" rows="2" class="textarea"><?= e($row['notes'] ?? '') ?></textarea>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <div class="card">
                <div class="card-head">
                    <h2 class="text-lg font-bold text-slate-800">Simpulan & Penutup</h2>
                </div>
                <div class="card-body space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-2">Simpulan</label>
                        <textarea name="simpulan" rows="5" class="textarea"><?= e($header['simpulan'] ?? '') ?></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-2">Penutup</label>
                        <textarea name="penutup" rows="4" class="textarea"><?= e($header['penutup'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="flex flex-wrap gap-3">
                <button type="submit" class="btn bg-blue-600 text-white hover:bg-blue-700">Simpan Draft</button>
                <button type="submit" name="submit_final" value="1" class="btn bg-emerald-600 text-white hover:bg-emerald-700">
                    Simpan & Kirim ke Kasubdiv
                </button>
            </div>
        </form>
    <?php endif; ?>
</div>

<script>
function addRow(sectionCode, colCount) {
    const tbody = document.getElementById('tbody_' + sectionCode);
    if (!tbody) return;

    const rowIndex = tbody.querySelectorAll('tr').length;
    const tr = document.createElement('tr');

    let html = '<td>' + (rowIndex + 1) +
        '<input type="hidden" name="' + sectionCode + '_row_index[]" value="' + rowIndex + '"></td>';

    for (let c = 1; c <= colCount; c++) {
        html += '<td><textarea name="' + sectionCode + '_col' + c + '[]" rows="2" class="textarea"></textarea></td>';
    }

    html += '<td><textarea name="' + sectionCode + '_notes[]" rows="2" class="textarea"></textarea></td>';
    tr.innerHTML = html;
    tbody.appendChild(tr);
}
</script>
