<?php
// modules/laporan_katim/index.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../config/telegram.php';
require_once __DIR__ . '/../../includes/telegram_helper.php';
require_once __DIR__ . '/../../includes/katim_notif_helper.php';
checkAuth();

$conn = getConnection();
if (!$conn) die('Koneksi database gagal.');

if (!function_exists('e')) {
    function e($str) { return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }
}
function bulanIndonesia($bln) {
    $b=[1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    return $b[(int)$bln]??'';
}
function laporan_katim_normalize_unit(string $name): string {
    $name=strtoupper(trim($name));
    $name=str_replace(['.','/','-','_'],['',' ',' ',' '],$name);
    $name=preg_replace('/\s+/',' ',$name);
    return trim($name);
}
function laporan_katim_canonical_key(string $normalized): string {
    return _katim_do_canonical_key($normalized);
}

// Ambil unit aktif, deduplikasi per unit fisik
$units=[]; $allUnits=[];
$resAll=$conn->query("SELECT id, name FROM units WHERE is_active=1 ORDER BY id ASC");
if($resAll){while($row=$resAll->fetch_assoc())$allUnits[]=$row;}
$seenCanonical=[];
foreach($allUnits as $row){
    $ck=laporan_katim_canonical_key(laporan_katim_normalize_unit($row['name']));
    if(!isset($seenCanonical[$ck])){$seenCanonical[$ck]=true;$units[]=['id'=>(int)$row['id'],'name'=>(string)$row['name']];}
}

$action  = $_GET['action'] ?? 'form';
$unit_id = isset($_GET['unit_id']) ? (int)$_GET['unit_id'] : 0;
$bulan   = isset($_GET['bulan'])   ? (int)$_GET['bulan']   : (int)date('m');
$tahun   = isset($_GET['tahun'])   ? (int)$_GET['tahun']   : (int)date('Y');
$currentUserId = (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
$shifts = ['Pagi','Sore','Malam'];

// SIMPAN
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['simpan'])) {
    $tanggal          = trim($_POST['tanggal']           ?? '');
    $shift            = trim($_POST['shift']             ?? '');
    $unit_id_post     = (int)($_POST['unit_id']          ?? 0);
    $total_pasien     = (int)($_POST['total_pasien']     ?? 0);
    $pasien_bz        = (int)($_POST['pasien_bz']        ?? 0);
    $pasien_rujuk     = (int)($_POST['pasien_rujuk']     ?? 0);
    $pasien_wt        = (int)($_POST['pasien_wt']        ?? 0);
    $jumlah_tenaga    = (int)($_POST['jumlah_tenaga']    ?? 0);
    $pre_op           = (int)($_POST['pre_op']           ?? 0);
    $post_op          = (int)($_POST['post_op']          ?? 0);
    $sedang_ok        = (int)($_POST['sedang_ok']        ?? 0);
    $sp_terpasang     = (int)($_POST['sp_terpasang']     ?? 0);
    $sp_tersedia      = (int)($_POST['sp_tersedia']      ?? 0);
    $sp_rusak         = (int)($_POST['sp_rusak']         ?? 0);
    $sp_tidak_dipakai = (int)($_POST['sp_tidak_dipakai'] ?? 0);
    $kondisi_khusus   = trim($_POST['kondisi_khusus']    ?? '');
    $masalah          = trim($_POST['masalah']           ?? '');
    $laporan_id=0; $telegramBedDetail=[]; $total_pasien_final=$total_pasien;

    if($tanggal===''||$shift===''||$unit_id_post<=0){echo "<script>alert('Data tanggal, shift, dan unit wajib diisi!');window.history.back();</script>";exit;}
    if(!in_array($shift,$shifts,true)){echo "<script>alert('Shift tidak valid!');window.history.back();</script>";exit;}

    $stmtUnit=$conn->prepare("SELECT id,name FROM units WHERE id=? LIMIT 1");
    if(!$stmtUnit)die("Prepare unit gagal: ".$conn->error);
    $stmtUnit->bind_param("i",$unit_id_post);$stmtUnit->execute();
    $unitInfo=$stmtUnit->get_result()->fetch_assoc();$stmtUnit->close();
    if(!$unitInfo){echo "<script>alert('Unit tidak ditemukan!');window.history.back();</script>";exit;}

    $is_igd=stripos($unitInfo['name'],'IGD')!==false;
    $conn->begin_transaction();
    try {
        if($is_igd){
            $stmt=$conn->prepare("INSERT INTO laporan_katim (tanggal,shift,unit_id,pasien_bz,pasien_rujuk,pasien_wt,jumlah_tenaga,pre_op,post_op,sedang_ok,sp_terpasang,sp_tersedia,sp_rusak,sp_tidak_dipakai,kondisi_khusus,masalah,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            if(!$stmt)throw new Exception("Prepare IGD gagal: ".$conn->error);
            $stmt->bind_param("ssiiiiiiiiiiiissi",$tanggal,$shift,$unit_id_post,$pasien_bz,$pasien_rujuk,$pasien_wt,$jumlah_tenaga,$pre_op,$post_op,$sedang_ok,$sp_terpasang,$sp_tersedia,$sp_rusak,$sp_tidak_dipakai,$kondisi_khusus,$masalah,$currentUserId);
            if(!$stmt->execute())throw new Exception("Simpan IGD gagal: ".$stmt->error);
            $laporan_id=$conn->insert_id;$stmt->close();
            $bed_numbers=$_POST['bed_number']??[];$bed_jumlah=$_POST['bed_jumlah']??[];$bed_keterangan=$_POST['bed_keterangan']??[];
            $total_pasien_igd=0;
            if(!empty($bed_numbers)){
                $stmtBed=$conn->prepare("INSERT INTO laporan_katim_bed (laporan_id,bed_number,jumlah_pasien,keterangan) VALUES (?,?,?,?)");
                if(!$stmtBed)throw new Exception("Prepare bed gagal: ".$conn->error);
                for($i=0;$i<count($bed_numbers);$i++){
                    $bn=(int)($bed_numbers[$i]??0);$jml=(int)($bed_jumlah[$i]??0);$ket=trim($bed_keterangan[$i]??'');
                    if($bn>0&&$jml>0){$stmtBed->bind_param("iiis",$laporan_id,$bn,$jml,$ket);if(!$stmtBed->execute())throw new Exception("Simpan bed gagal: ".$stmtBed->error);$total_pasien_igd+=$jml;$telegramBedDetail[]=['bed_number'=>$bn,'jumlah_pasien'=>$jml,'keterangan'=>$ket];}
                }
                $stmtBed->close();
            }
            $stmtUpd=$conn->prepare("UPDATE laporan_katim SET total_pasien=? WHERE id=?");
            if(!$stmtUpd)throw new Exception("Prepare update gagal: ".$conn->error);
            $stmtUpd->bind_param("ii",$total_pasien_igd,$laporan_id);
            if(!$stmtUpd->execute())throw new Exception("Update total pasien gagal: ".$stmtUpd->error);
            $stmtUpd->close();$total_pasien_final=$total_pasien_igd;
        } else {
            $stmt=$conn->prepare("INSERT INTO laporan_katim (tanggal,shift,unit_id,total_pasien,pasien_bz,pasien_rujuk,pasien_wt,jumlah_tenaga,pre_op,post_op,sedang_ok,sp_terpasang,sp_tersedia,sp_rusak,sp_tidak_dipakai,kondisi_khusus,masalah,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            if(!$stmt)throw new Exception("Prepare Non-IGD gagal: ".$conn->error);
            $stmt->bind_param("ssiiiiiiiiiiiiissi",$tanggal,$shift,$unit_id_post,$total_pasien,$pasien_bz,$pasien_rujuk,$pasien_wt,$jumlah_tenaga,$pre_op,$post_op,$sedang_ok,$sp_terpasang,$sp_tersedia,$sp_rusak,$sp_tidak_dipakai,$kondisi_khusus,$masalah,$currentUserId);
            if(!$stmt->execute())throw new Exception("Simpan Non-IGD gagal: ".$stmt->error);
            $laporan_id=$conn->insert_id;$stmt->close();
        }
        $conn->commit();
        $currentUser=function_exists('current_user')?current_user():null;
        $createdByName='-';
        if(is_array($currentUser))$createdByName=$currentUser['full_name']??$currentUser['nama']??$currentUser['username']??'-';
        $telegramData=['laporan_id'=>$laporan_id,'tanggal'=>$tanggal,'shift'=>$shift,'unit_name'=>$unitInfo['name']??'-','total_pasien'=>$total_pasien_final,'pasien_bz'=>$pasien_bz,'pasien_rujuk'=>$pasien_rujuk,'pasien_wt'=>$pasien_wt,'jumlah_tenaga'=>$jumlah_tenaga,'pre_op'=>$pre_op,'post_op'=>$post_op,'sedang_ok'=>$sedang_ok,'sp_terpasang'=>$sp_terpasang,'sp_tersedia'=>$sp_tersedia,'sp_rusak'=>$sp_rusak,'sp_tidak_dipakai'=>$sp_tidak_dipakai,'kondisi_khusus'=>$kondisi_khusus,'masalah'=>$masalah,'created_by_name'=>$createdByName,'bed_detail'=>$telegramBedDetail];
        $telegramError=null;$telegramSent=false;
        if(function_exists('telegram_is_configured')&&function_exists('buildLaporanKatimTelegramMessage')&&function_exists('sendTelegramMessage')&&telegram_is_configured()){
            $telegramSent=sendTelegramMessage(buildLaporanKatimTelegramMessage($telegramData),$telegramError);
            if(!$telegramSent)error_log('[Katim Telegram] Gagal: '.$laporan_id.' | '.$telegramError);
        }
        $msg=$telegramSent?'Laporan berhasil disimpan dan terkirim ke Telegram!':'Laporan berhasil disimpan, Telegram belum terkirim: '.(string)$telegramError;
        echo "<script>alert(".json_encode($msg)."); window.location.href='?module=laporan_katim';</script>";exit;
    } catch(Exception $e){$conn->rollback();die("Error: ".e($e->getMessage()));}
}

// REKAP
$rekap_bulanan=[];$chart_labels=[];$chart_pasien=[];$chart_tenaga=[];$chart_rasio=[];$chart_data=[];
if($action==='rekap'){
    $sql="SELECT lk.tanggal,lk.shift,lk.unit_id,u.name AS unit_name,COALESCE(lk.total_pasien,0) AS total_pasien,COALESCE(lk.jumlah_tenaga,0) AS total_tenaga,COALESCE(lk.sp_terpasang,0) AS total_sp_on,COALESCE(lk.sp_tersedia,0) AS total_sp_ready,COALESCE(lk.sp_rusak,0) AS total_sp_rusak,COALESCE(lk.sp_tidak_dipakai,0) AS total_sp_tidak_dipakai,COALESCE(lk.pre_op,0) AS total_preop,COALESCE(lk.post_op,0) AS total_postop FROM laporan_katim lk INNER JOIN units u ON lk.unit_id=u.id WHERE MONTH(lk.tanggal)=? AND YEAR(lk.tanggal)=?";
    $types="ii";$params=[$bulan,$tahun];
    if($unit_id>0){$sql.=" AND lk.unit_id=?";$types.="i";$params[]=$unit_id;}
    $sql.=" ORDER BY lk.tanggal ASC, FIELD(lk.shift,'Pagi','Sore','Malam') ASC";
    $stmt=$conn->prepare($sql);
    if($stmt){$stmt->bind_param($types,...$params);$stmt->execute();$result=$stmt->get_result();
        while($row=$result->fetch_assoc()){$rekap_bulanan[]=$row;$tgl=$row['tanggal'];if(!isset($chart_data[$tgl]))$chart_data[$tgl]=['pasien'=>0,'tenaga'=>0];$chart_data[$tgl]['pasien']+=(int)$row['total_pasien'];$chart_data[$tgl]['tenaga']+=(int)$row['total_tenaga'];}
        $stmt->close();}
    foreach($chart_data as $tgl=>$data){$chart_labels[]=date('d/m',strtotime($tgl));$chart_pasien[]=(int)$data['pasien'];$chart_tenaga[]=(int)$data['tenaga'];$chart_rasio[]=((int)$data['tenaga']>0)?round($data['pasien']/$data['tenaga'],2):0;}
}

// EXPORT
if($action==='export'){
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="rekap_katim_'.$bulan.'_'.$tahun.'.xls"');
    echo "<html><head><meta charset='UTF-8'></head><body><h2>REKAP LAPORAN KATIM</h2><h3>Bulan: ".e(bulanIndonesia($bulan))." ".e($tahun)."</h3>";
    if($unit_id>0){$s=$conn->prepare("SELECT name FROM units WHERE id=? LIMIT 1");if($s){$s->bind_param("i",$unit_id);$s->execute();$r=$s->get_result()->fetch_assoc();$s->close();if($r)echo "<h3>Unit: ".e($r['name'])."</h3>";}}
    echo "<table border='1' cellpadding='5'><tr><th>Tanggal</th><th>Shift</th><th>Unit</th><th>Total Pasien</th><th>Tenaga</th><th>SP On</th><th>SP Ready</th><th>SP Rusak</th><th>SP Tidak Dipakai</th><th>Pre-Op</th><th>Post-Op</th><th>Rasio</th></tr>";
    $sql="SELECT lk.tanggal,lk.shift,u.name AS unit_name,COALESCE(lk.total_pasien,0) AS total_pasien,COALESCE(lk.jumlah_tenaga,0) AS jumlah_tenaga,COALESCE(lk.sp_terpasang,0) AS sp_terpasang,COALESCE(lk.sp_tersedia,0) AS sp_tersedia,COALESCE(lk.sp_rusak,0) AS sp_rusak,COALESCE(lk.sp_tidak_dipakai,0) AS sp_tidak_dipakai,COALESCE(lk.pre_op,0) AS pre_op,COALESCE(lk.post_op,0) AS post_op FROM laporan_katim lk INNER JOIN units u ON lk.unit_id=u.id WHERE MONTH(lk.tanggal)=? AND YEAR(lk.tanggal)=?";
    $types="ii";$params=[$bulan,$tahun];
    if($unit_id>0){$sql.=" AND lk.unit_id=?";$types.="i";$params[]=$unit_id;}
    $sql.=" ORDER BY lk.tanggal DESC, FIELD(lk.shift,'Pagi','Sore','Malam') ASC";
    $stmt=$conn->prepare($sql);
    if($stmt){$stmt->bind_param($types,...$params);$stmt->execute();$result=$stmt->get_result();
        while($row=$result->fetch_assoc()){$rasio=((int)$row['jumlah_tenaga']>0)?round($row['total_pasien']/$row['jumlah_tenaga'],2):0;echo "<tr><td>".e(date('d-m-Y',strtotime($row['tanggal'])))."</td><td>".e($row['shift'])."</td><td>".e($row['unit_name'])."</td><td align='right'>".(int)$row['total_pasien']."</td><td align='right'>".(int)$row['jumlah_tenaga']."</td><td align='right'>".(int)$row['sp_terpasang']."</td><td align='right'>".(int)$row['sp_tersedia']."</td><td align='right'>".(int)$row['sp_rusak']."</td><td align='right'>".(int)$row['sp_tidak_dipakai']."</td><td align='right'>".(int)$row['pre_op']."</td><td align='right'>".(int)$row['post_op']."</td><td align='right'>".$rasio."</td></tr>";}
        $stmt->close();}
    echo "</table></body></html>";exit;
}

// STATISTIK DATA
$daily_data=[];$weekly_data=[];$monthly_data=[];
if($action==='statistik'){
    $start_date=date('Y-m-d',strtotime($_GET['start_date']??date('Y-m-01')));
    $end_date=date('Y-m-d',strtotime($_GET['end_date']??date('Y-m-t')));
    $stmt=$conn->prepare("SELECT lk.tanggal,u.id AS unit_id,u.name AS unit_name,COALESCE(SUM(lk.total_pasien),0) AS total_pasien FROM laporan_katim lk INNER JOIN units u ON lk.unit_id=u.id WHERE lk.tanggal BETWEEN ? AND ? GROUP BY lk.tanggal,lk.unit_id ORDER BY lk.tanggal ASC,u.name ASC");
    $stmt->bind_param("ss",$start_date,$end_date);$stmt->execute();$res=$stmt->get_result();while($r=$res->fetch_assoc())$daily_data[]=$r;$stmt->close();
    $stmt=$conn->prepare("SELECT YEARWEEK(lk.tanggal,1) AS yearweek,MIN(lk.tanggal) AS week_start,MAX(lk.tanggal) AS week_end,u.id AS unit_id,u.name AS unit_name,COALESCE(SUM(lk.total_pasien),0) AS total_pasien FROM laporan_katim lk INNER JOIN units u ON lk.unit_id=u.id WHERE lk.tanggal BETWEEN ? AND ? GROUP BY yearweek,lk.unit_id ORDER BY yearweek ASC,u.name ASC");
    $stmt->bind_param("ss",$start_date,$end_date);$stmt->execute();$res=$stmt->get_result();while($r=$res->fetch_assoc())$weekly_data[]=$r;$stmt->close();
    $stmt=$conn->prepare("SELECT DATE_FORMAT(lk.tanggal,'%Y-%m') AS yearmonth,u.id AS unit_id,u.name AS unit_name,COALESCE(SUM(lk.total_pasien),0) AS total_pasien FROM laporan_katim lk INNER JOIN units u ON lk.unit_id=u.id WHERE lk.tanggal BETWEEN ? AND ? GROUP BY yearmonth,lk.unit_id ORDER BY yearmonth ASC,u.name ASC");
    $stmt->bind_param("ss",$start_date,$end_date);$stmt->execute();$res=$stmt->get_result();while($r=$res->fetch_assoc())$monthly_data[]=$r;$stmt->close();
}

// Alert data
$katimMissingAlertsForm=($action==='form')?katim_get_missing_shift_alerts($conn):[];
$katimMissingWaMessages=[];
foreach($katimMissingAlertsForm as $alert)$katimMissingWaMessages[]=$alert['wa_message']??('- '.($alert['message']??''));
?>
<style id="katim-hide-top-copy-button">
button[onclick="copyPreview()"],button[onclick='copyPreview()']{display:none!important;}
</style>
<div class="w-full max-w-none"><div class="space-y-6">

<div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
    <div><h2 class="text-2xl font-semibold text-gray-800">Laporan Katim per Shift</h2><p class="text-gray-600">Input laporan harian per shift + rekap beban kerja</p></div>
    <div class="flex flex-wrap gap-2">
        <a href="?module=laporan_katim&action=form"      class="bg-blue-600   text-white px-4 py-2 rounded-lg hover:bg-blue-700"><i class="fas fa-plus mr-2"></i>Input Laporan</a>
        <a href="?module=laporan_katim&action=rekap"     class="bg-green-600  text-white px-4 py-2 rounded-lg hover:bg-green-700"><i class="fas fa-chart-bar mr-2"></i>Rekap Bulanan</a>
        <a href="?module=laporan_katim&action=statistik" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700"><i class="fas fa-chart-line mr-2"></i>Statistik Pasien</a>
    </div>
</div>

<?php if($action==='form'): ?>
<div class="bg-white rounded-xl shadow-lg p-6">
    <h3 class="text-lg font-semibold mb-4">Form Laporan Katim</h3>
    <?php if(!empty($katimMissingAlertsForm)): ?>
    <div class="mb-4 bg-red-50 border-l-4 border-red-500 rounded-xl p-4">
        <div class="flex items-start gap-3">
            <div class="text-red-600 text-xl"><i class="fas fa-bell"></i></div>
            <div>
                <div class="font-bold text-red-700">Notifikasi laporan shift sebelumnya</div>
                <div class="text-sm text-red-600 mt-1">Notifikasi ini berlaku 24 jam, dibuat otomatis, dan tidak bisa dihapus. Akan hilang setelah laporan shift terkait disubmit.</div>
                <ul class="mt-2 text-sm text-red-700 list-disc list-inside">
                    <?php foreach($katimMissingAlertsForm as $alert): ?><li><?=e($alert['message'])?></li><?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <form method="POST" id="formKatim">
        <input type="hidden" name="simpan" value="1">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Tanggal</label><input type="date" name="tanggal" id="tglInput" value="<?=e(date('Y-m-d'))?>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Shift</label><select name="shift" id="shiftSelect" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php foreach($shifts as $s):?><option value="<?=e($s)?>"><?=e($s)?></option><?php endforeach;?></select></div>
            <div class="md:col-span-2"><label class="block text-sm font-medium text-gray-700 mb-1">Unit</label><select name="unit_id" id="unitSelect" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><option value="">-- Pilih Unit --</option><?php foreach($units as $u):?><option value="<?=(int)$u['id']?>" data-igd="<?=(stripos($u['name'],'IGD')!==false)?'1':'0'?>"><?=e($u['name'])?></option><?php endforeach;?></select></div>
        </div>
        <div id="igdBlock" class="hidden border rounded-lg p-4 mb-4 bg-gray-50">
            <div class="flex justify-between items-center mb-3"><h4 class="font-semibold text-blue-800">Detail Pasien per Bed (IGD)</h4><button type="button" onclick="addBedRow()" class="bg-green-500 text-white px-3 py-1 rounded-lg text-sm hover:bg-green-600"><i class="fas fa-plus mr-1"></i>Tambah Baris</button></div>
            <div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="bg-gray-100"><th class="p-2 text-left">No.</th><th class="p-2 text-left">No. Bed</th><th class="p-2 text-left">Jumlah</th><th class="p-2 text-left">Keterangan</th><th class="p-2 text-center">Aksi</th></tr></thead><tbody id="igdBody"></tbody><tfoot><tr class="bg-gray-50"><td colspan="2" class="p-2 text-right font-semibold">Total Pasien IGD:</td><td class="p-2 font-bold text-lg" id="totalPasienIgd">0</td><td colspan="2"></td></tr></tfoot></table></div>
        </div>
        <div id="nonIgdBlock"><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label class="block text-sm font-medium text-gray-700 mb-1">Total Pasien</label><input type="number" name="total_pasien" id="totalPasien" min="0" value="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></div></div></div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4 mt-4">
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Pasien BZ</label><input type="number" name="pasien_bz" id="bz" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Pasien Rujuk</label><input type="number" name="pasien_rujuk" id="rujuk" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Pasien WT</label><input type="number" name="pasien_wt" id="wt" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Jumlah Tenaga</label><input type="number" name="jumlah_tenaga" id="tenaga" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Pre-Op</label><input type="number" name="pre_op" id="preop" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Post-Op</label><input type="number" name="post_op" id="postop" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Sedang OK</label><input type="number" name="sedang_ok" id="sedangok" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">SP Terpasang</label><input type="number" name="sp_terpasang" id="sp_on" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">SP Tersedia</label><input type="number" name="sp_tersedia" id="sp_ready" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">SP Rusak</label><input type="number" name="sp_rusak" id="sp_rusak" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">SP Tidak Dipakai</label><input type="number" name="sp_tidak_dipakai" id="sp_tidak_dipakai" min="0" value="0" class="w-full px-4 py-2 border rounded-lg"></div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Kondisi Khusus</label><textarea name="kondisi_khusus" id="kondisi" rows="3" class="w-full px-4 py-2 border rounded-lg"></textarea></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Masalah</label><textarea name="masalah" id="masalah" rows="3" class="w-full px-4 py-2 border rounded-lg"></textarea></div>
        </div>
        <div class="bg-gray-50 rounded-lg p-4 mb-4"><h4 class="font-semibold mb-2">Preview Teks Laporan</h4><pre id="preview" class="text-sm whitespace-pre-wrap bg-white p-3 rounded border min-h-[300px] font-mono"></pre></div>
        <div class="flex justify-end space-x-2">
            <a href="?module=laporan_katim" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">Batal</a>
            <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Simpan Laporan</button>
        </div>
    </form>
</div>
<?php elseif($action==='rekap'): ?>
<div class="bg-white rounded-xl shadow-lg p-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
        <h3 class="text-lg font-semibold">Rekap Bulanan</h3>
        <div class="flex flex-wrap gap-2">
            <select id="bulanSelect" class="px-3 py-2 border rounded-lg"><?php for($i=1;$i<=12;$i++):?><option value="<?=$i?>" <?=$i===$bulan?'selected':''?>><?=e(bulanIndonesia($i))?></option><?php endfor;?></select>
            <select id="tahunSelect" class="px-3 py-2 border rounded-lg"><?php for($i=date('Y')-2;$i<=date('Y')+1;$i++):?><option value="<?=$i?>" <?=(int)$i===(int)$tahun?'selected':''?>><?=e($i)?></option><?php endfor;?></select>
            <select id="unitFilter" class="px-3 py-2 border rounded-lg min-w-[200px]"><option value="0">Semua Unit</option><?php foreach($units as $u):?><option value="<?=(int)$u['id']?>" <?=(int)$u['id']===(int)$unit_id?'selected':''?>><?=e($u['name'])?></option><?php endforeach;?></select>
            <button onclick="loadRekap()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"><i class="fas fa-sync-alt mr-2"></i>Tampilkan</button>
            <a href="?module=laporan_katim&action=export&bulan=<?=(int)$bulan?>&tahun=<?=(int)$tahun?>&unit_id=<?=(int)$unit_id?>" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700"><i class="fas fa-file-excel mr-2"></i>Export Excel</a>
        </div>
    </div>
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div class="border rounded-lg p-4"><h4 class="font-semibold mb-2">Total Pasien & Tenaga per Hari</h4><div style="height:250px;position:relative;"><canvas id="chartPT"></canvas></div></div>
        <div class="border rounded-lg p-4"><h4 class="font-semibold mb-2">Rasio Pasien : Tenaga</h4><div style="height:250px;position:relative;"><canvas id="chartRasio"></canvas></div></div>
    </div>
    <div class="overflow-x-auto"><table class="w-full text-sm"><thead class="bg-gray-50"><tr><th class="px-4 py-2 text-left">Tanggal</th><th class="px-4 py-2 text-left">Shift</th><th class="px-4 py-2 text-left">Unit</th><th class="px-4 py-2 text-right">Pasien</th><th class="px-4 py-2 text-right">Tenaga</th><th class="px-4 py-2 text-right">SP On</th><th class="px-4 py-2 text-right">SP Ready</th><th class="px-4 py-2 text-right">SP Rusak</th><th class="px-4 py-2 text-right">SP Tidak Dipakai</th><th class="px-4 py-2 text-right">Pre-Op</th><th class="px-4 py-2 text-right">Post-Op</th><th class="px-4 py-2 text-right">Rasio</th></tr></thead>
    <tbody class="divide-y">
    <?php if(empty($rekap_bulanan)):?>
        <tr><td colspan="12" class="px-4 py-8 text-center text-gray-500"><i class="fas fa-info-circle mr-2"></i>Belum ada data. <a href="?module=laporan_katim&action=form" class="text-blue-600 hover:underline ml-1">Buat laporan sekarang</a></td></tr>
    <?php else: foreach($rekap_bulanan as $r): $rasio=((int)$r['total_tenaga']>0)?round($r['total_pasien']/$r['total_tenaga'],2):0;?>
        <tr class="hover:bg-gray-50"><td class="px-4 py-2"><?=e(date('d/m/Y',strtotime($r['tanggal'])))?></td><td class="px-4 py-2"><?=e($r['shift'])?></td><td class="px-4 py-2"><?=e($r['unit_name'])?></td><td class="px-4 py-2 text-right font-medium"><?=number_format((int)$r['total_pasien'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_tenaga'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_sp_on'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_sp_ready'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_sp_rusak'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_sp_tidak_dipakai'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_preop'])?></td><td class="px-4 py-2 text-right"><?=number_format((int)$r['total_postop'])?></td><td class="px-4 py-2 text-right font-semibold <?=$rasio>5?'text-red-600':'text-green-600'?>"><?=e($rasio)?></td></tr>
    <?php endforeach; endif;?>
    </tbody></table></div>
</div>
<?php elseif($action==='statistik'): ?>
<div class="bg-white rounded-xl shadow-lg p-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
        <h3 class="text-lg font-semibold">Statistik Jumlah Pasien per Unit</h3>
        <form method="GET" class="flex flex-wrap gap-2 items-end">
            <input type="hidden" name="module" value="laporan_katim"><input type="hidden" name="action" value="statistik">
            <div><label class="block text-xs font-medium text-gray-600">Tanggal Awal</label><input type="date" name="start_date" value="<?=e($start_date??date('Y-m-01'))?>" class="px-3 py-2 border rounded-lg"></div>
            <div><label class="block text-xs font-medium text-gray-600">Tanggal Akhir</label><input type="date" name="end_date" value="<?=e($end_date??date('Y-m-t'))?>" class="px-3 py-2 border rounded-lg"></div>
            <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"><i class="fas fa-filter mr-1"></i>Tampilkan</button>
            <a href="?module=laporan_katim&action=statistik" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600">Reset</a>
        </form>
    </div>
    <div class="mb-8"><h4 class="font-semibold bg-gray-100 p-2 rounded-t-lg border">📅 Harian</h4><div class="overflow-x-auto border rounded-b-lg"><table class="w-full text-sm"><thead class="bg-gray-50"><tr><th class="px-4 py-2 text-left">Tanggal</th><th class="px-4 py-2 text-left">Unit</th><th class="px-4 py-2 text-right">Total Pasien</th></tr></thead><tbody>
        <?php if(empty($daily_data)):?><tr><td colspan="3" class="px-4 py-8 text-center text-gray-500">Tidak ada data.</td></tr><?php else:foreach($daily_data as $r):?>
        <tr class="border-t hover:bg-gray-50"><td class="px-4 py-2"><?=e(date('d/m/Y',strtotime($r['tanggal'])))?></td><td class="px-4 py-2"><?=e($r['unit_name'])?></td><td class="px-4 py-2 text-right font-medium"><?=number_format($r['total_pasien'])?></td></tr>
        <?php endforeach;endif;?></tbody></table></div></div>
    <div class="mb-8"><h4 class="font-semibold bg-gray-100 p-2 rounded-t-lg border">📆 Mingguan</h4><div class="overflow-x-auto border rounded-b-lg"><table class="w-full text-sm"><thead class="bg-gray-50"><tr><th class="px-4 py-2 text-left">Periode</th><th class="px-4 py-2 text-left">Unit</th><th class="px-4 py-2 text-right">Total Pasien</th></tr></thead><tbody>
        <?php if(empty($weekly_data)):?><tr><td colspan="3" class="px-4 py-8 text-center text-gray-500">Tidak ada data.</td></tr><?php else:foreach($weekly_data as $r):?>
        <tr class="border-t hover:bg-gray-50"><td class="px-4 py-2"><?=e(date('d/m',strtotime($r['week_start'])))?> - <?=e(date('d/m/Y',strtotime($r['week_end'])))?></td><td class="px-4 py-2"><?=e($r['unit_name'])?></td><td class="px-4 py-2 text-right font-medium"><?=number_format($r['total_pasien'])?></td></tr>
        <?php endforeach;endif;?></tbody></table></div></div>
    <div><h4 class="font-semibold bg-gray-100 p-2 rounded-t-lg border">📊 Bulanan</h4><div class="overflow-x-auto border rounded-b-lg"><table class="w-full text-sm"><thead class="bg-gray-50"><tr><th class="px-4 py-2 text-left">Bulan</th><th class="px-4 py-2 text-left">Unit</th><th class="px-4 py-2 text-right">Total Pasien</th></tr></thead><tbody>
        <?php if(empty($monthly_data)):?><tr><td colspan="3" class="px-4 py-8 text-center text-gray-500">Tidak ada data.</td></tr><?php else:foreach($monthly_data as $r):$ym=explode('-',$r['yearmonth']);$bln_nama=bulanIndonesia((int)$ym[1]).' '.$ym[0];?>
        <tr class="border-t hover:bg-gray-50"><td class="px-4 py-2"><?=e($bln_nama)?></td><td class="px-4 py-2"><?=e($r['unit_name'])?></td><td class="px-4 py-2 text-right font-medium"><?=number_format($r['total_pasien'])?></td></tr>
        <?php endforeach;endif;?></tbody></table></div></div>
    <div class="mt-6 text-sm text-gray-500 border-t pt-4"><i class="fas fa-info-circle mr-1"></i>Total pasien dihitung dari kolom <code>total_pasien</code>.</div>
</div>
<?php endif; ?>

</div></div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
<?php if($action==='form'): ?>
const katimMissingAlertsForPreview=<?=json_encode($katimMissingWaMessages,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?>;
document.addEventListener('DOMContentLoaded',function(){
    const form=document.getElementById('formKatim'),unitSelect=document.getElementById('unitSelect');
    if(document.getElementById('igdBody').children.length===0)addBedRow();
    updatePreview();
    if(form)form.querySelectorAll('input,select,textarea').forEach(el=>{el.addEventListener('input',updatePreview);el.addEventListener('change',updatePreview);});
    if(unitSelect)unitSelect.addEventListener('change',function(){
        const opt=this.options[this.selectedIndex],isIgd=opt&&opt.getAttribute('data-igd')==='1';
        document.getElementById('igdBlock').classList.toggle('hidden',!isIgd);
        document.getElementById('nonIgdBlock').classList.toggle('hidden',isIgd);
        if(isIgd){document.getElementById('totalPasien').value=0;hitungTotalIgd();}
        updatePreview();
    });
});
function addBedRow(){const tbody=document.getElementById('igdBody');if(!tbody)return;const rc=tbody.children.length+1,r=document.createElement('tr');r.innerHTML=`<td class="p-2">${rc}</td><td class="p-2"><input type="number" name="bed_number[]" min="1" max="99" class="w-20 px-2 py-1 border rounded" onchange="updatePreview()"></td><td class="p-2"><input type="number" name="bed_jumlah[]" min="0" class="w-20 px-2 py-1 border rounded" oninput="hitungTotalIgd();updatePreview();"></td><td class="p-2"><input type="text" name="bed_keterangan[]" class="w-full px-2 py-1 border rounded" placeholder="keterangan" oninput="updatePreview()"></td><td class="p-2 text-center"><button type="button" onclick="removeRow(this)" class="text-red-500 hover:text-red-700"><i class="fas fa-trash"></i></button></td>`;tbody.appendChild(r);updatePreview();}
function removeRow(btn){const r=btn.closest('tr');if(!r)return;r.remove();renumberRows();hitungTotalIgd();updatePreview();}
function renumberRows(){document.querySelectorAll('#igdBody tr').forEach((r,i)=>r.cells[0].textContent=i+1);}
function hitungTotalIgd(){let t=0;document.querySelectorAll('input[name="bed_jumlah[]"]').forEach(i=>t+=parseInt(i.value||0,10)||0);const el=document.getElementById('totalPasienIgd');if(el)el.textContent=t;}
function updatePreview(){
    const tgl=document.getElementById('tglInput')?.value||'',shift=document.getElementById('shiftSelect')?.value||'',us=document.getElementById('unitSelect');
    let unit='',isIgd=false;if(us&&us.selectedIndex>0){const o=us.options[us.selectedIndex];unit=o?o.text:'';isIgd=o&&o.getAttribute('data-igd')==='1';}
    const tp=document.getElementById('totalPasien')?.value||'0',bz=document.getElementById('bz')?.value||'0',rujuk=document.getElementById('rujuk')?.value||'0',wt=document.getElementById('wt')?.value||'0',tenaga=document.getElementById('tenaga')?.value||'0',preop=document.getElementById('preop')?.value||'0',postop=document.getElementById('postop')?.value||'0',sok=document.getElementById('sedangok')?.value||'0',spOn=document.getElementById('sp_on')?.value||'0',spR=document.getElementById('sp_ready')?.value||'0',spRsk=document.getElementById('sp_rusak')?.value||'0',spD=document.getElementById('sp_tidak_dipakai')?.value||'0',kondisi=document.getElementById('kondisi')?.value||'-',masalah=document.getElementById('masalah')?.value||'-';
    let p=`LAPORAN KEPALA TIM - SHIFT ${shift}\n================================\nUnit       : ${unit}\nTanggal    : ${tgl}\n\nA. DATA PASIEN\n---------------\n`;
    if(isIgd){const bn=document.querySelectorAll('input[name="bed_number[]"]'),bj=document.querySelectorAll('input[name="bed_jumlah[]"]'),bk=document.querySelectorAll('input[name="bed_keterangan[]"]');let t=0,hd=false;for(let i=0;i<bn.length;i++){const n=bn[i]?.value||'',j=parseInt(bj[i]?.value||0,10)||0,k=bk[i]?.value||'';if(n!==''||j>0||k!==''){hd=true;t+=j;p+=`Bed ${n||'-'} : ${j} pasien`;if(k)p+=` (${k})`;p+='\n';}}if(!hd)p+=`Belum ada detail bed.\n`;p+=`Total Pasien IGD : ${t}\n\n`;}else{p+=`Total Pasien : ${tp}\n\n`;}
    p+=`BZ                 : ${bz}\nRujuk              : ${rujuk}\nWT                 : ${wt}\nJumlah Tenaga      : ${tenaga}\nPre-Op             : ${preop}\nPost-Op            : ${postop}\nSedang OK          : ${sok}\nSP Terpasang       : ${spOn}\nSP Tersedia        : ${spR}\nSP Rusak           : ${spRsk}\nSP Tidak Dipakai   : ${spD}\n\nB. KONDISI KHUSUS\n-----------------\n${kondisi}\n\nC. MASALAH\n----------\n${masalah}\n`;
    const el=document.getElementById('preview');if(el)el.textContent=p;
}
<?php endif; ?>
<?php if($action==='rekap'): ?>
function loadRekap(){window.location.href=`?module=laporan_katim&action=rekap&bulan=${document.getElementById('bulanSelect').value}&tahun=${document.getElementById('tahunSelect').value}&unit_id=${document.getElementById('unitFilter').value}`;}
document.addEventListener('DOMContentLoaded',function(){
    const labels=<?=json_encode($chart_labels)?>,pasien=<?=json_encode($chart_pasien)?>,tenaga=<?=json_encode($chart_tenaga)?>,rasio=<?=json_encode($chart_rasio)?>;
    const ctxPT=document.getElementById('chartPT');if(ctxPT)new Chart(ctxPT,{type:'bar',data:{labels,datasets:[{label:'Pasien',data:pasien,backgroundColor:'rgba(59,130,246,0.7)'},{label:'Tenaga',data:tenaga,backgroundColor:'rgba(16,185,129,0.7)'}]},options:{responsive:true,maintainAspectRatio:false}});
    const ctxR=document.getElementById('chartRasio');if(ctxR)new Chart(ctxR,{type:'line',data:{labels,datasets:[{label:'Rasio',data:rasio,borderColor:'rgba(239,68,68,1)',backgroundColor:'rgba(239,68,68,0.2)',fill:true,tension:0.3}]},options:{responsive:true,maintainAspectRatio:false}});
});
<?php endif; ?>
</script>
<!-- KATIM_SAVE_COPY_WA_PATCH_START -->
<script>
(function(){
    function fallbackCopy(t){try{var a=document.createElement('textarea');a.value=t;a.setAttribute('readonly','');a.style.cssText='position:fixed;top:-9999px;left:-9999px';document.body.appendChild(a);a.select();document.execCommand('copy');document.body.removeChild(a);return true;}catch(e){return false;}}
    async function copyPreviewForWa(){var el=document.getElementById('preview'),text=el?(el.textContent||'').trim():'';if(!text)return true;try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(text);return true;}}catch(e){}return fallbackCopy(text);}
    document.addEventListener('DOMContentLoaded',function(){
        var form=document.getElementById('formKatim');if(!form||form.dataset.saveCopyWaPatch==='1')return;form.dataset.saveCopyWaPatch='1';
        var btn=form.querySelector('button[type="submit"]');if(btn){btn.innerHTML='<i class="fas fa-save mr-2"></i>Simpan & Copy untuk WA';btn.title='Laporan disimpan dan teks preview otomatis dicopy untuk paste ke WhatsApp';btn.classList.add('katim-save-copy-wa-btn');}
        var ht=document.querySelector('#preview')?.closest('.bg-gray-50,.rounded-lg,div');if(ht&&!document.getElementById('katimSaveCopyHint')){var h=document.createElement('div');h.id='katimSaveCopyHint';h.className='mt-2 text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded-lg px-3 py-2';h.innerHTML='<i class="fas fa-info-circle mr-1"></i>Tombol <b>Simpan & Copy untuk WA</b> menyimpan laporan sekaligus menyalin teks preview untuk paste di WhatsApp.';ht.appendChild(h);}
        var isSub=false;
        form.addEventListener('submit',async function(e){if(isSub)return;e.preventDefault();if(typeof updatePreview==='function'){try{updatePreview();}catch(er){}}var copied=await copyPreviewForWa();isSub=true;if(btn){btn.disabled=true;btn.classList.add('opacity-75','cursor-wait');btn.innerHTML=copied?'<i class="fas fa-check mr-2"></i>Tersalin, menyimpan...':'<i class="fas fa-save mr-2"></i>Menyimpan...';}HTMLFormElement.prototype.submit.call(form);});
    });
})();
</script>
<style>.katim-save-copy-wa-btn{background:linear-gradient(135deg,#2563eb,#14b8a6)!important;box-shadow:0 10px 22px rgba(37,99,235,.22);}.katim-save-copy-wa-btn:hover{filter:brightness(1.03);transform:translateY(-1px);}</style>
<!-- KATIM_SAVE_COPY_WA_PATCH_END -->