<?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'] ?? 'viewer')));
    return $raw === 'superadmin' ? 'admin' : $raw;
}

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

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

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

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

    return $columns;
}

$userId = (int)($_SESSION['user_id'] ?? 0);
$userRole = getCurrentRole();
$userSubdivisionId = (int)($_SESSION['subdivision_id'] ?? 0);
$userDivisionId = (int)($_SESSION['division_id'] ?? 0);

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

$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');

$selectedSubdivisionId = $userRole === 'admin'
    ? (int)($_GET['subdivision_id'] ?? 0)
    : $userSubdivisionId;

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

$sectionTemplates = [
    'data_pelayanan'       => 'A. Data Pelayanan Unit',
    'keterlambatan_staf'   => 'B. Keterlambatan Staf',
    'capaian_rka'          => 'C. Capaian RKA / Program Kerja',
    'kejadian_keselamatan' => 'D. Kejadian Keselamatan Pasien',
    'permasalahan_unit'    => 'E. Permasalahan Unit',
];

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

function findOrCreateKasubdivReport(
    mysqli $conn,
    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 = 'kasubdiv'
          AND subdivision_id = ?
          AND bulan = ?
          AND tahun = ?
        LIMIT 1
    ");
    $stmt->bind_param("iii", $subdivisionId, $bulan, $tahun);
    $stmt->execute();
    $existing = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    $title = 'LAPORAN BULANAN SUB DIV ' . strtoupper($reportType === 'ranap' ? 'RANAP' : 'RAJAL')
        . ' - ' . bulanIndo($bulan) . ' ' . $tahun;

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

    $urut = 1;
    foreach ([
        'data_pelayanan' => 'A. Data Pelayanan Unit',
        'keterlambatan_staf' => 'B. Keterlambatan Staf',
        'capaian_rka' => 'C. Capaian RKA / Program Kerja',
        'kejadian_keselamatan' => 'D. Kejadian Keselamatan Pasien',
        'permasalahan_unit' => 'E. Permasalahan Unit',
    ] 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 getUnitReportsForPeriod(mysqli $conn, int $subdivisionId, int $bulan, int $tahun): array
{
    $rows = [];
    $stmt = $conn->prepare("
        SELECT h.id, h.unit_id, u.name AS unit_name, h.report_type, h.status, h.updated_at, h.submitted_at, h.title
        FROM monthly_report_headers h
        INNER JOIN units u ON u.id = h.unit_id
        WHERE h.report_level = 'unit'
          AND h.subdivision_id = ?
          AND h.bulan = ?
          AND h.tahun = ?
        ORDER BY u.name ASC, h.id DESC
    ");
    $stmt->bind_param("iii", $subdivisionId, $bulan, $tahun);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function pullSelectedUnitReportsIntoKasubdiv(mysqli $conn, int $parentReportId, array $selectedReportIds): int
{
    if ($parentReportId <= 0 || !$selectedReportIds) return 0;

    $selectedReportIds = array_values(array_filter(array_map('intval', $selectedReportIds), fn($v) => $v > 0));
    if (!$selectedReportIds) return 0;

    $inSelected = implode(',', $selectedReportIds);

    $parentSections = [];
    $stmt = $conn->prepare("SELECT id, section_code FROM monthly_report_sections WHERE report_id = ?");
    $stmt->bind_param("i", $parentReportId);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $parentSections[(string)$row['section_code']] = (int)$row['id'];
    }
    $stmt->close();
    if (!$parentSections) return 0;

    $sectionIds = array_values($parentSections);
    $inSections = implode(',', array_map('intval', $sectionIds));

    $conn->query("DELETE FROM monthly_report_rows WHERE section_id IN ($inSections) AND source_level = 'unit'");
    $stmt = $conn->prepare("DELETE FROM monthly_report_sources WHERE parent_report_id = ? AND source_level = 'unit'");
    $stmt->bind_param("i", $parentReportId);
    $stmt->execute();
    $stmt->close();

    $inserted = 0;

    $allowedHeaders = [];
    $sqlAllowed = "
        SELECT id
        FROM monthly_report_headers
        WHERE id IN ($inSelected)
          AND report_level = 'unit'
          AND status IN ('submitted','reviewed','approved','final')
    ";
    $res = $conn->query($sqlAllowed);
    while ($row = $res->fetch_assoc()) {
        $allowedHeaders[] = (int)$row['id'];
    }
    if (!$allowedHeaders) return 0;

    foreach ($allowedHeaders as $childReportId) {
        $stmt = $conn->prepare("INSERT INTO monthly_report_sources (parent_report_id, child_report_id, source_level) VALUES (?, ?, 'unit')");
        $stmt->bind_param("ii", $parentReportId, $childReportId);
        $stmt->execute();
        $stmt->close();

        $childSections = [];
        $stmt = $conn->prepare("SELECT id, section_code FROM monthly_report_sections WHERE report_id = ?");
        $stmt->bind_param("i", $childReportId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $childSections[(string)$row['section_code']] = (int)$row['id'];
        }
        $stmt->close();

        foreach ($childSections as $sectionCode => $childSectionId) {
            if (!isset($parentSections[$sectionCode])) continue;
            $parentSectionId = (int)$parentSections[$sectionCode];

            $stmt = $conn->prepare("SELECT COALESCE(MAX(urut), 0) AS max_urut FROM monthly_report_rows WHERE section_id = ?");
            $stmt->bind_param("i", $parentSectionId);
            $stmt->execute();
            $maxUrut = (int)($stmt->get_result()->fetch_assoc()['max_urut'] ?? 0);
            $stmt->close();

            $stmt = $conn->prepare("SELECT * FROM monthly_report_rows WHERE section_id = ? ORDER BY urut ASC, id ASC");
            $stmt->bind_param("i", $childSectionId);
            $stmt->execute();
            $res = $stmt->get_result();
            $idx = 0;
            while ($row = $res->fetch_assoc()) {
                $urut = $maxUrut + $idx + 1;
                $notes = trim((string)($row['notes'] ?? ''));
                $sourceRowId = (int)($row['id'] ?? 0);

                $ins = $conn->prepare("
                    INSERT INTO monthly_report_rows
                    (section_id, urut, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, notes, source_row_id, source_level)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unit')
                ");
                $ins->bind_param(
                    "iisssssssssssi",
                    $parentSectionId, $urut,
                    $row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'], $row['col6'],
                    $row['col7'], $row['col8'], $row['col9'], $row['col10'], $notes, $sourceRowId
                );
                $ins->execute();
                $ins->close();
                $inserted++;
                $idx++;
            }
            $stmt->close();
        }
    }

    return $inserted;
}

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'] ?? '';
        $stmt->bind_param(
            "iisssssssssss",
            $sectionId,
            $urut,
            $r['col1'],
            $r['col2'],
            $r['col3'],
            $r['col4'],
            $r['col5'],
            $r['col6'],
            $r['col7'],
            $r['col8'],
            $r['col9'],
            $r['col10'],
            $notes
        );
        $stmt->execute();
        $stmt->close();
        $urut++;
    }
}

$reportId = 0;
$subdivision = null;
$header = null;
$sections = [];
$sectionRows = [];
$linkedUnitSources = 0;
$availableUnitReports = [];

if ($selectedSubdivisionId > 0) {
    $subdivision = getSubdivisionInfo($conn, $selectedSubdivisionId);

    if ($subdivision) {
        $reportType = (string)($subdivision['report_type'] ?? 'rajal');
        $divisionId = (int)($subdivision['division_id'] ?? $userDivisionId);

        $reportId = findOrCreateKasubdivReport(
            $conn,
            $selectedSubdivisionId,
            $divisionId,
            $bulan,
            $tahun,
            $userId,
            $reportType
        );

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

            try {
                if ($formType === 'pull_selected_unit_reports') {
                    $selectedReportIds = $_POST['selected_unit_reports'] ?? [];
                    if (!is_array($selectedReportIds) || !$selectedReportIds) {
                        throw new RuntimeException('Pilih minimal satu laporan unit yang ingin ditarik.');
                    }
                    $insertedRows = pullSelectedUnitReportsIntoKasubdiv($conn, $reportId, $selectedReportIds);
                    if ($insertedRows <= 0) {
                        throw new RuntimeException('Tidak ada laporan unit berstatus submitted/reviewed/approved/final yang dapat ditarik dari pilihan tersebut.');
                    }
                    $message = 'Tarik laporan unit berhasil. ' . $insertedRows . ' baris ditarik ke form kasubdiv.';
                } elseif ($formType === 'save_kasubdiv_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 kasubdiv dikirim ke kadiv';

                        $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 kasubdiv berhasil disimpan dan dikirim ke Kadiv.'
                        : 'Draft laporan kasubdiv berhasil disimpan.';
                }
            } catch (Throwable $e) {
                $message = 'Terjadi error: ' . $e->getMessage();
                $messageType = 'error';
            }
        }

        $header = getReportHeader($conn, $reportId);
        $sections = getSections($conn, $reportId);

        $stmt = $conn->prepare("SELECT COUNT(*) AS jml FROM monthly_report_sources WHERE parent_report_id = ? AND source_level = 'unit'");
        $stmt->bind_param("i", $reportId);
        $stmt->execute();
        $linkedUnitSources = (int)($stmt->get_result()->fetch_assoc()['jml'] ?? 0);
        $stmt->close();

        $availableUnitReports = getUnitReportsForPeriod($conn, $selectedSubdivisionId, $bulan, $tahun);

        foreach ($sections as $sec) {
            $rows = getSectionRows($conn, (int)$sec['id']);
            if (!$rows) {
                $rows = array_fill(0, 3, [
                    'col1' => '',
                    'col2' => '',
                    'col3' => '',
                    'col4' => '',
                    'col5' => '',
                    'col6' => '',
                    'col7' => '',
                    'col8' => '',
                    'col9' => '',
                    'col10' => '',
                    'notes' => '',
                ]);
            }
            $sectionRows[$sec['section_code']] = $rows;
        }
    }
}

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


?>
<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 Kasubdiv</h1>
                <p class="text-sm text-slate-500">Kasubdiv dapat menarik laporan unit Rajal/Ranap, menambahkan analisis bidang, lalu simpan dan kirim ke Kadiv.</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="kasubdiv_form">

                <?php if ($userRole === 'admin'): ?>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Subdivisi</label>
                        <select name="subdivision_id" class="input">
                            <option value="">-- pilih subdivisi --</option>
                            <?php foreach ($subdivisionOptions as $opt): ?>
                                <option value="<?= (int)$opt['id'] ?>" <?= $selectedSubdivisionId === (int)$opt['id'] ? 'selected' : '' ?>>
                                    <?= e($opt['name']) ?> (<?= e(strtoupper($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 (!empty($subdivision) && $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>

        <div class="card">
            <div class="card-head">
                <h2 class="text-lg font-bold text-slate-800">Daftar Laporan Unit Periode Ini</h2>
            </div>
            <div class="card-body space-y-4">
                <div class="text-sm text-slate-600">
                    <div><strong>Sumber tertaut:</strong> <?= (int)$linkedUnitSources ?> laporan unit</div>
                    <div>Kasubdiv dapat melihat status laporan unit terlebih dahulu, lalu menarik laporan yang dipilih ke struktur kasubdiv yang sama dengan form unit.</div>
                </div>

                <form method="post" class="space-y-4">
                    <input type="hidden" name="form_type" value="pull_selected_unit_reports">

                    <div class="overflow-x-auto">
                        <table class="tbl text-sm">
                            <thead>
                                <tr>
                                    <th style="width:52px">Pilih</th>
                                    <th>Unit</th>
                                    <th>Jenis</th>
                                    <th>Status</th>
                                    <th>Updated</th>
                                    <th>Submitted</th>
                                    <th>Judul</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!$availableUnitReports): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-slate-500">Belum ada laporan unit pada periode ini.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($availableUnitReports as $item): ?>
                                        <?php
                                        $status = strtolower((string)($item['status'] ?? 'draft'));
                                        $statusClass = $status === 'submitted' ? 'bg-emerald-100 text-emerald-700'
                                            : (($status === 'approved' || $status === 'final' || $status === 'reviewed') ? 'bg-blue-100 text-blue-700'
                                            : 'bg-slate-100 text-slate-700');
                                        $isAllowed = in_array($status, ['submitted','reviewed','approved','final'], true);
                                        ?>
                                        <tr>
                                            <td class="text-center">
                                                <input type="checkbox" name="selected_unit_reports[]" value="<?= (int)$item['id'] ?>" <?= $isAllowed ? '' : 'disabled' ?>>
                                            </td>
                                            <td><?= e($item['unit_name'] ?? '-') ?></td>
                                            <td><?= e(strtoupper((string)($item['report_type'] ?? '-'))) ?></td>
                                            <td><span class="inline-flex px-2 py-1 rounded-full text-xs font-semibold <?= $statusClass ?>"><?= e(strtoupper($status)) ?></span></td>
                                            <td><?= e((string)($item['updated_at'] ?? '-')) ?></td>
                                            <td><?= e((string)($item['submitted_at'] ?? '-')) ?></td>
                                            <td><?= e((string)($item['title'] ?? '-')) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="flex flex-wrap gap-3">
                        <button type="submit" class="btn bg-blue-600 text-white hover:bg-blue-700">Tarik yang Dipilih</button>
                    </div>
                </form>
            </div>
        </div>

        <form method="post" class="space-y-6">
            <input type="hidden" name="form_type" value="save_kasubdiv_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-2 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">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>
                        <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 class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Nama Penanda Tangan</label>
                            <input type="text" name="signed_name" class="input"
                                   value="<?= e($header['signed_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'] ?? '') ?>">
                        </div>
                    </div>
                </div>
            </div>

            <?php foreach ($sections as $section): ?>
                <?php
                $code = $section['section_code'];
                $rows = $sectionRows[$code] ?? [];
                $columns = getSectionColumnsByTitle($code, (string)$section['section_title']);
                ?>
                <div class="card section-card" data-section="<?= e($code) ?>">
                    <div class="card-head flex items-center justify-between gap-4">
                        <h2 class="text-lg font-bold text-slate-800"><?= e($section['section_title']) ?></h2>
                        <button type="button"
                                class="btn-sm bg-blue-600 text-white hover:bg-blue-700 add-row-btn"
                                data-section="<?= e($code) ?>">
                            + Tambah Baris
                        </button>
                    </div>
                    <div class="card-body space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Narasi 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 text-sm section-table" data-section="<?= e($code) ?>">
                                <thead>
                                    <tr>
                                        <th style="width:60px">No</th>
                                        <?php foreach ($columns as $colKey => $label): ?>
                                            <th><?= e($label) ?></th>
                                        <?php endforeach; ?>
                                        <th>Catatan</th>
                                        <th style="width:90px">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rows as $i => $row): ?>
                                        <tr>
                                            <td>
                                                <span class="row-no"><?= $i + 1 ?></span>
                                                <input type="hidden" name="<?= e($code) ?>_row_index[]" value="<?= $i ?>">
                                            </td>

                                            <?php for ($c = 1; $c <= 10; $c++): ?>
                                                <?php if (isset($columns["col{$c}"])): ?>
                                                    <td>
                                                        <textarea class="textarea"
                                                                  name="<?= e($code) ?>_col<?= $c ?>[]"
                                                                  rows="2"><?= e($row["col{$c}"] ?? '') ?></textarea>
                                                    </td>
                                                <?php else: ?>
                                                    <input type="hidden" name="<?= e($code) ?>_col<?= $c ?>[]" value="<?= e($row["col{$c}"] ?? '') ?>">
                                                <?php endif; ?>
                                            <?php endfor; ?>

                                            <td>
                                                <textarea class="textarea" name="<?= e($code) ?>_notes[]" rows="2"><?= e($row['notes'] ?? '') ?></textarea>
                                            </td>
                                            <td>
                                                <button type="button" class="btn-sm bg-red-600 text-white hover:bg-red-700 remove-row-btn">
                                                    Hapus
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <template id="tpl-<?= e($code) ?>">
                        <tr>
                            <td>
                                <span class="row-no">0</span>
                                <input type="hidden" name="<?= e($code) ?>_row_index[]" value="0">
                            </td>

                            <?php for ($c = 1; $c <= 10; $c++): ?>
                                <?php if (isset($columns["col{$c}"])): ?>
                                    <td>
                                        <textarea class="textarea" name="<?= e($code) ?>_col<?= $c ?>[]" rows="2"></textarea>
                                    </td>
                                <?php else: ?>
                                    <input type="hidden" name="<?= e($code) ?>_col<?= $c ?>[]" value="">
                                <?php endif; ?>
                            <?php endfor; ?>

                            <td>
                                <textarea class="textarea" name="<?= e($code) ?>_notes[]" rows="2"></textarea>
                            </td>
                            <td>
                                <button type="button" class="btn-sm bg-red-600 text-white hover:bg-red-700 remove-row-btn">
                                    Hapus
                                </button>
                            </td>
                        </tr>
                    </template>
                </div>
            <?php endforeach; ?>

            <div class="flex flex-wrap gap-3">
                <button type="submit" name="submit_final" value="0"
                        class="btn bg-slate-700 text-white hover:bg-slate-800">
                    Simpan Draft
                </button>
                <button type="submit" name="submit_final" value="1"
                        class="btn bg-indigo-600 text-white hover:bg-indigo-700">
                    Kirim ke Kadiv
                </button>
            </div>
        </form>
    <?php else: ?>
        <div class="card">
            <div class="card-body">
                <div class="text-slate-600">Pilih subdivisi dulu untuk mulai menyusun laporan kasubdiv.</div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('click', function (e) {
    const addBtn = e.target.closest('.add-row-btn');
    if (addBtn) {
        const section = addBtn.getAttribute('data-section');
        const tpl = document.getElementById('tpl-' + section);
        const table = document.querySelector('.section-table[data-section="' + section + '"] tbody');
        if (tpl && table) {
            table.insertAdjacentHTML('beforeend', tpl.innerHTML);
            renumberRows(table);
        }
    }

    const removeBtn = e.target.closest('.remove-row-btn');
    if (removeBtn) {
        const row = removeBtn.closest('tr');
        const tbody = row ? row.closest('tbody') : null;
        if (row && tbody) {
            row.remove();
            renumberRows(tbody);
        }
    }
});

function renumberRows(tbody) {
    const rows = tbody.querySelectorAll('tr');
    rows.forEach((row, index) => {
        const no = row.querySelector('.row-no');
        const idxInput = row.querySelector('input[type="hidden"][name$="_row_index[]"]');
        if (no) no.textContent = index + 1;
        if (idxInput) idxInput.value = index;
    });
}
</script>
