<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
$BLN = ['','Januari','Februari','Maret','April','Mei','Juni',
        'Juli','Agustus','September','Oktober','November','Desember'];
$pb = $bulan-1; $py = $tahun; if($pb<1){$pb=12;$py--;}
$nb = $bulan+1; $ny = $tahun; if($nb>12){$nb=1;$ny++;}
$PW = [
    'Legi'   => ['bg'=>'#10b981','text'=>'#fff'],
    'Pahing' => ['bg'=>'#f59e0b','text'=>'#fff'],
    'Pon'    => ['bg'=>'#3b82f6','text'=>'#fff'],
    'Wage'   => ['bg'=>'#ef4444','text'=>'#fff'],
    'Kliwon' => ['bg'=>'#8b5cf6','text'=>'#fff'],
];
$WARNA = ['#3b82f6','#10b981','#f59e0b','#ef4444','#8b5cf6','#ec4899','#0ea5e9','#64748b'];
// Bisa buat jadwal: warga login ATAU admin
$bisa_jadwal = isset($bisa_jadwal) ? $bisa_jadwal : ($warga_id > 0);
$is_admin_view = isset($is_admin) ? $is_admin : false;
?>
<style>
.kw{font-family:'Plus Jakarta Sans',system-ui,sans-serif;}
/* ── Header ── */
.kw-hd{display:flex;align-items:center;justify-content:space-between;
  background:linear-gradient(135deg,#0d9488,#14b8a6,#2dd4bf);
  border-radius:16px;padding:18px 24px;color:#fff;
  box-shadow:0 8px 28px rgba(13,148,136,.3);margin-bottom:14px;}
.kw-nav{background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.28);
  color:#fff;border-radius:10px;padding:8px 18px;font-weight:700;
  text-decoration:none;font-size:.85rem;transition:.15s;}
.kw-nav:hover{background:rgba(255,255,255,.32);color:#fff;}
.kw-title{font-size:1.25rem;font-weight:800;margin-bottom:2px;}
.kw-sub{font-size:.72rem;opacity:.78;}
.kw-today-a{display:inline-flex;align-items:center;gap:4px;margin-top:6px;
  background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.25);
  color:#fff;border-radius:8px;padding:4px 12px;font-size:.73rem;font-weight:700;
  text-decoration:none;}
.kw-today-a:hover{background:rgba(255,255,255,.28);color:#fff;}
/* ── Legend ── */
.kw-leg{display:flex;gap:10px;flex-wrap:wrap;align-items:center;
  background:#fff;border-radius:10px;padding:9px 14px;
  margin-bottom:12px;border:1px solid #e2e8f0;font-size:.73rem;}
.kw-leg-item{display:flex;align-items:center;gap:5px;font-weight:600;color:#475569;}
.kw-ldot{width:9px;height:9px;border-radius:50%;flex-shrink:0;}
.kw-lbar{width:16px;height:6px;border-radius:3px;flex-shrink:0;}
/* ── Grid ── */
.kw-grid{background:#fff;border-radius:16px;overflow:hidden;
  box-shadow:0 1px 4px rgba(0,0,0,.06),0 4px 20px rgba(0,0,0,.07);
  border:1px solid #e2e8f0;}
.kw-hrow{display:grid;grid-template-columns:repeat(7,1fr);
  background:linear-gradient(90deg,#f0fdfa,#f8fafc);border-bottom:2px solid #e2e8f0;}
.kw-hcell{padding:10px 4px;text-align:center;font-size:.72rem;
  font-weight:800;color:#64748b;text-transform:uppercase;letter-spacing:.05em;}
.kw-hcell.mg{color:#ef4444;}.kw-hcell.sb{color:#f59e0b;}
.kw-row{display:grid;grid-template-columns:repeat(7,1fr);border-bottom:1px solid #f1f5f9;}
.kw-row:last-child{border-bottom:none;}
/* ── Cell ── */
.kw-cell{min-height:110px;padding:7px 7px 5px;border-right:1px solid #f1f5f9;
  position:relative;cursor:pointer;transition:background .12s;overflow:hidden;}
.kw-cell:last-child{border-right:none;}
.kw-cell:hover{background:#f0fdfa;}
.kw-cell.empty{background:#fafafa;cursor:default;pointer-events:none;}
.kw-cell.today{background:linear-gradient(135deg,#ecfdf5,#f0fdfa);
  outline:2px solid #14b8a6;outline-offset:-2px;}
.kw-cell.libur{background:#fff7ed;}
.kw-cell.cmg .kw-tgl{color:#ef4444;}
.kw-cell.csb .kw-tgl{color:#f59e0b;}
/* ── Tanggal + badge ── */
.kw-tgl-row{display:flex;align-items:center;gap:5px;margin-bottom:5px;flex-wrap:wrap;}
.kw-tgl{font-size:.95rem;font-weight:800;color:#1e293b;line-height:1;flex-shrink:0;}
.kw-tgl-circle{display:inline-flex;align-items:center;justify-content:center;
  width:26px;height:26px;background:#14b8a6;color:#fff;
  border-radius:50%;font-size:.85rem;font-weight:800;flex-shrink:0;}
.kw-today-pill{position:absolute;top:3px;right:3px;background:#14b8a6;color:#fff;
  border-radius:5px;font-size:.5rem;font-weight:800;padding:1px 5px;}
.kw-pbadge{display:inline-flex;align-items:center;padding:2px 7px;
  border-radius:99px;font-size:.63rem;font-weight:800;white-space:nowrap;line-height:1.4;}
.kw-neptu{font-size:.6rem;font-weight:600;color:#94a3b8;}
/* ── Event labels ── */
.kw-evs{margin-top:4px;}
.kw-ev{display:block;font-size:.6rem;font-weight:700;
  padding:1px 5px;border-radius:3px;margin-bottom:2px;
  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;line-height:1.5;}
.kw-ev-lb{background:#fef2f2;color:#dc2626;border-left:2px solid #ef4444;}
.kw-ev-kt{background:#fef3c7;color:#92400e;border-left:2px solid #f59e0b;}
.kw-ev-jd{color:#fff;}
/* ── Libur summary card ── */
.kw-libur-card{background:#fff;border-radius:14px;border:1px solid #e2e8f0;
  border-left:4px solid #ef4444;margin-top:14px;overflow:hidden;
  box-shadow:0 1px 6px rgba(0,0,0,.05);}
.kw-libur-head{background:linear-gradient(90deg,#fef2f2,#fff);
  border-bottom:1px solid #fecaca;padding:11px 16px;
  font-size:.82rem;font-weight:800;color:#dc2626;display:flex;align-items:center;gap:6px;}
.kw-libur-row{display:flex;align-items:center;gap:10px;
  padding:8px 16px;border-bottom:1px solid #fef2f2;font-size:.8rem;}
.kw-libur-row:last-child{border-bottom:none;}
.kw-libur-tgl{background:#fef2f2;border:1px solid #fecaca;color:#dc2626;
  padding:2px 8px;border-radius:6px;font-weight:800;
  min-width:32px;text-align:center;flex-shrink:0;}
/* ── Modal helpers ── */
.lbl-s{font-size:.7rem;font-weight:700;color:#475569;display:block;margin-bottom:3px;}
.btn-gray{background:#f1f5f9;color:#64748b;border:none;border-radius:8px;
  font-size:.8rem;padding:8px 14px;cursor:pointer;}
.kw-form-box-blue{background:#f0f9ff;border:1px solid #bae6fd;border-radius:12px;padding:14px;}
.kw-form-box-yellow{background:#fffbeb;border:1px solid #fde68a;border-radius:12px;padding:14px;}
/* ── Responsive ── */
@media(max-width:991px){
  .kw-cell{min-height:90px;padding:5px 4px;}
  .kw-tgl{font-size:.85rem;}.kw-neptu{display:none;}
}
@media(max-width:767px){
  .kw-cell{min-height:64px;padding:4px 3px;}
  .kw-evs{display:none;}.kw-hd{padding:12px 14px;}.kw-title{font-size:1rem;}
  .kw-nav{padding:7px 12px;font-size:.8rem;}
  .kw-pbadge{padding:2px 4px;}.kw-p-text{display:none;}
  .kw-neptu{display:none;}
}
@media(max-width:400px){
  .kw-cell{min-height:52px;}
  .kw-hcell{font-size:.6rem;padding:7px 2px;}
}
</style>

<div class="kw">

<!-- Header navigasi -->
<div class="kw-hd">
  <a href="<?php echo base_url('kalender?bulan='.$pb.'&tahun='.$py) ?>" class="kw-nav"><i class="bi bi-chevron-left"></i></a>
  <div class="text-center">
    <div class="kw-title"><i class="bi bi-calendar3 me-2"></i><?php echo $BLN[$bulan].' '.$tahun ?></div>
    <div class="kw-sub"><?php echo isset($kalender['bulan_jawa']) ? $kalender['bulan_jawa'] : '' ?> &middot; Klik tanggal untuk jadwal</div>
    <?php if($bulan!=date('n')||$tahun!=date('Y')): ?>
    <a href="<?php echo base_url('kalender') ?>" class="kw-today-a"><i class="bi bi-skip-forward-fill"></i>Hari ini</a>
    <?php endif; ?>
  </div>
  <a href="<?php echo base_url('kalender?bulan='.$nb.'&tahun='.$ny) ?>" class="kw-nav"><i class="bi bi-chevron-right"></i></a>
</div>

<!-- Legend -->
<div class="kw-leg">
  <?php foreach($PW as $nm=>$c): ?>
  <div class="kw-leg-item"><div class="kw-ldot" style="background:<?php echo $c['bg'] ?>"></div><?php echo $nm ?></div>
  <?php endforeach; ?>
  <div class="kw-leg-item" style="border-left:1px solid #e2e8f0;padding-left:10px;">
    <div class="kw-ldot" style="background:#ef4444"></div>Hari Libur
  </div>
  <div class="kw-leg-item"><div class="kw-lbar" style="background:#f59e0b"></div>Kegiatan RT</div>
  <div class="kw-leg-item"><div class="kw-lbar" style="background:#3b82f6"></div>Jadwal Saya</div>
</div>

<!-- Grid -->
<div class="kw-grid">
  <div class="kw-hrow">
    <?php foreach(['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'] as $i=>$h): ?>
    <div class="kw-hcell <?php echo $i==0?'mg':($i==6?'sb':'') ?>">
      <span class="d-none d-sm-inline"><?php echo $h ?></span>
      <span class="d-sm-none"><?php echo substr($h,0,3) ?></span>
    </div>
    <?php endforeach; ?>
  </div>

  <?php foreach($kalender['minggu_grid'] as $minggu): ?>
  <div class="kw-row">
    <?php foreach($minggu as $hari): ?>
      <?php if($hari===null): ?>
      <div class="kw-cell empty"></div>
      <?php else:
        $pw   = isset($PW[$hari['pasaran']]) ? $PW[$hari['pasaran']] : ['bg'=>'#64748b','text'=>'#fff'];
        $tgl  = $hari['tanggal'];
        $ds   = $hari['date_str'];
        $cls  = '';
        if($hari['is_today'])  $cls.=' today';
        if($hari['libur'])     $cls.=' libur';
        if($hari['is_minggu']) $cls.=' cmg';
        if($hari['is_sabtu'])  $cls.=' csb';
        $jlist = isset($jadwal_map[$tgl])   ? $jadwal_map[$tgl]   : [];
        $klist = isset($kegiatan_map[$tgl]) ? $kegiatan_map[$tgl] : [];
      ?>
      <div class="kw-cell<?php echo $cls ?>"
           data-tgl="<?php echo $ds ?>"
           data-weton="<?php echo htmlspecialchars($hari['weton']) ?>"
           data-neptu="<?php echo $hari['neptu'] ?>"
           data-pasaran="<?php echo $hari['pasaran'] ?>"
           onclick="kwOpen('<?php echo $ds ?>')">

        <?php if($hari['is_today']): ?>
        <div class="kw-tgl-row">
          <span class="kw-tgl-circle"><?php echo $tgl ?></span>
          <span class="kw-pbadge" style="background:<?php echo $pw['bg'] ?>;color:<?php echo $pw['text'] ?>"><span class="kw-p-text"><?php echo $hari['pasaran'] ?></span></span>
          <span class="kw-neptu">neptu <?php echo $hari['neptu'] ?></span>
        </div>
        <span class="kw-today-pill">Hari ini</span>
        <?php else: ?>
        <div class="kw-tgl-row">
          <span class="kw-tgl"><?php echo $tgl ?></span>
          <span class="kw-pbadge" style="background:<?php echo $pw['bg'] ?>;color:<?php echo $pw['text'] ?>"><span class="kw-p-text"><?php echo $hari['pasaran'] ?></span></span>
          <span class="kw-neptu">neptu <?php echo $hari['neptu'] ?></span>
        </div>
        <?php endif; ?>

        <div class="kw-evs">
          <?php if($hari['libur']): ?>
          <span class="kw-ev kw-ev-lb"><?php echo htmlspecialchars($hari['libur']) ?></span>
          <?php endif; ?>
          <?php foreach($klist as $k): ?>
          <span class="kw-ev kw-ev-kt"><?php echo htmlspecialchars($k->judul) ?></span>
          <?php endforeach; ?>
          <?php foreach(array_slice($jlist,0,2) as $j): ?>
          <span class="kw-ev kw-ev-jd" style="background:<?php echo $j->warna ?>"><?php echo htmlspecialchars($j->judul) ?></span>
          <?php endforeach; ?>
          <?php if(count($jlist)>2): ?>
          <span class="kw-ev" style="background:#e2e8f0;color:#475569;">+<?php echo count($jlist)-2 ?> lagi</span>
          <?php endif; ?>
        </div>

      </div>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>
  <?php endforeach; ?>
</div>

<!-- Ringkasan libur -->
<?php if(!empty($kalender['libur_map'])): ?>
<div class="kw-libur-card">
  <div class="kw-libur-head"><i class="bi bi-flag-fill"></i>Hari Libur Nasional &mdash; <?php echo $BLN[$bulan].' '.$tahun ?></div>
  <?php foreach($kalender['libur_map'] as $tgl=>$nama): ?>
  <div class="kw-libur-row">
    <span class="kw-libur-tgl"><?php echo $tgl ?></span>
    <span style="color:#475569"><?php echo htmlspecialchars($nama) ?></span>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

</div><!-- /kw -->


<!-- ====================================================
     MODAL KALENDER
===================================================== -->
<div class="modal fade" id="kwModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" style="max-width:500px;">
<div class="modal-content border-0" style="border-radius:18px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.2);">

  <!-- Header modal -->
  <div id="kwHead" style="padding:16px 20px 14px;color:#fff;background:linear-gradient(135deg,#0d9488,#14b8a6);">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;">
      <div>
        <div id="kwMTgl"   style="font-size:1.1rem;font-weight:800;"></div>
        <div id="kwMWeton" style="font-size:.73rem;opacity:.85;margin-top:2px;"></div>
        <div id="kwMNeptu" style="font-size:.7rem;opacity:.75;margin-top:1px;"></div>
      </div>
      <button class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button>
    </div>
  </div>

  <div class="modal-body p-0">

    <!-- Loading spinner -->
    <div id="kwSpin" style="text-align:center;padding:36px 20px;">
      <div class="spinner-border text-success" style="width:1.5rem;height:1.5rem;" role="status"></div>
      <div style="margin-top:10px;color:#94a3b8;font-size:.8rem;">Memuat data...</div>
    </div>

    <!-- Konten -->
    <div id="kwBody" style="display:none;">

      <!-- Banner libur nasional -->
      <div id="kwLiburBox" style="display:none;background:#fef2f2;border-bottom:1px solid #fecaca;
           padding:10px 18px;font-size:.8rem;color:#dc2626;font-weight:700;">
        <i class="bi bi-flag-fill me-1"></i><span id="kwLiburTxt"></span>
      </div>

      <!-- Seksi Kegiatan RT -->
      <div id="kwSeksiKgt" style="padding:14px 18px 0;">
        <div style="font-size:.68rem;font-weight:800;color:#92400e;
             text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px;">
          <i class="bi bi-megaphone-fill me-1" style="color:#f59e0b;"></i>Kegiatan RT
        </div>
        <div id="kwListKgt"></div>
      </div>

      <!-- Seksi Jadwal Saya -->
      <div style="padding:14px 18px 0;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
          <div style="font-size:.68rem;font-weight:800;color:#1e40af;text-transform:uppercase;letter-spacing:.06em;">
            <i class="bi bi-person-fill me-1" style="color:#3b82f6;"></i>Jadwal Saya
          </div>
          <?php if($bisa_jadwal): ?>
          <button id="kwBtnTambah" onclick="kwToggle('kwFrmJdwl')"
                  style="background:#3b82f6;color:#fff;border:none;border-radius:8px;
                         font-size:.72rem;font-weight:700;padding:5px 12px;cursor:pointer;">
            <i class="bi bi-plus-lg me-1"></i>Tambah
          </button>
          <?php endif; ?>
        </div>
        <div id="kwListJdwl"></div>
      </div>

      <!-- Form Jadwal Pribadi -->
      <?php if($bisa_jadwal): ?>
      <div id="kwFrmJdwl" style="display:none;margin:10px 18px 0;" class="kw-form-box-blue">
        <div style="font-size:.76rem;font-weight:800;color:#0369a1;margin-bottom:10px;">
          <i class="bi bi-pencil-square me-1"></i><span id="kwFrmJdwlTitle">Jadwal Baru</span>
        </div>
        <input type="hidden" id="kwIdEdit" value="0">
        <input type="hidden" id="kwFrmTgl" value="">
        <div class="mb-2">
          <label class="lbl-s">Judul <span style="color:#ef4444">*</span></label>
          <input type="text" id="kwJudul" class="form-control form-control-sm"
                 placeholder="cth: Rapat, Arisan, Bayar tagihan..." maxlength="150">
        </div>
        <div class="row g-2 mb-2">
          <div class="col-6">
            <label class="lbl-s">Waktu Mulai</label>
            <input type="time" id="kwMulai" class="form-control form-control-sm">
          </div>
          <div class="col-6">
            <label class="lbl-s">Waktu Selesai</label>
            <input type="time" id="kwSelesai" class="form-control form-control-sm">
          </div>
        </div>
        <div class="mb-2">
          <label class="lbl-s">Deskripsi</label>
          <textarea id="kwDesk" class="form-control form-control-sm" rows="2" placeholder="Opsional..."></textarea>
        </div>
        <div class="mb-3">
          <label class="lbl-s">Warna Label</label>
          <div style="display:flex;gap:7px;flex-wrap:wrap;margin-top:4px;">
            <?php foreach($WARNA as $wc): ?>
            <div class="kwWarnaPick" data-w="<?php echo $wc ?>"
                 onclick="kwPickWarna(this,'<?php echo $wc ?>')"
                 style="width:22px;height:22px;border-radius:50%;background:<?php echo $wc ?>;
                        cursor:pointer;border:2px solid transparent;transition:.15s;flex-shrink:0;"></div>
            <?php endforeach; ?>
          </div>
          <input type="hidden" id="kwWarna" value="#3b82f6">
        </div>
        <div class="d-flex gap-2">
          <button onclick="kwSimpanJdwl(event)"
                  style="flex:1;background:#3b82f6;color:#fff;border:none;border-radius:8px;
                         font-weight:700;font-size:.8rem;padding:9px;cursor:pointer;">
            <i class="bi bi-save me-1"></i>Simpan Jadwal
          </button>
          <button onclick="kwToggle('kwFrmJdwl',false)" class="btn-gray">Batal</button>
        </div>
      </div>
      <?php endif; ?>

      <!-- Form Kegiatan RT (admin only) -->
      <?php if($is_admin_view): ?>
      <div id="kwFrmKgt" style="display:none;margin:10px 18px 0;" class="kw-form-box-yellow">
        <div style="font-size:.76rem;font-weight:800;color:#92400e;margin-bottom:10px;">
          <i class="bi bi-megaphone me-1"></i><span id="kwFrmKgtTitle">Kegiatan RT Baru</span>
        </div>
        <input type="hidden" id="kwKgtId" value="0">
        <div class="mb-2">
          <label class="lbl-s">Judul Kegiatan <span style="color:#ef4444">*</span></label>
          <input type="text" id="kwKgtJudul" class="form-control form-control-sm"
                 placeholder="cth: Rapat RT, Kerja Bakti, Pengajian..." maxlength="150">
        </div>
        <div class="row g-2 mb-2">
          <div class="col-6">
            <label class="lbl-s">Waktu Mulai</label>
            <input type="time" id="kwKgtWaktu" class="form-control form-control-sm">
          </div>
          <div class="col-6">
            <label class="lbl-s">Tempat</label>
            <input type="text" id="kwKgtTempat" class="form-control form-control-sm" placeholder="Balai RT, Masjid...">
          </div>
        </div>
        <div class="mb-2">
          <label class="lbl-s">Deskripsi</label>
          <textarea id="kwKgtDesk" class="form-control form-control-sm" rows="2" placeholder="Opsional..."></textarea>
        </div>
        <div class="d-flex gap-2">
          <button onclick="kwSimpanKgt(event)"
                  style="flex:1;background:#f59e0b;color:#fff;border:none;border-radius:8px;
                         font-weight:700;font-size:.8rem;padding:9px;cursor:pointer;">
            <i class="bi bi-save me-1"></i>Simpan Kegiatan
          </button>
          <button onclick="kwToggle('kwFrmKgt',false)" class="btn-gray">Batal</button>
        </div>
      </div>

      <!-- Tombol buka form kegiatan RT -->
      <div style="padding:12px 18px 14px;text-align:right;">
        <button onclick="kwToggle('kwFrmKgt')"
                style="background:transparent;border:1.5px solid #f59e0b;color:#92400e;
                       border-radius:8px;font-size:.74rem;font-weight:700;padding:6px 14px;cursor:pointer;">
          <i class="bi bi-megaphone me-1"></i>+ Kegiatan RT
        </button>
      </div>
      <?php endif; ?>

      <div style="height:6px;"></div>
    </div><!-- /kwBody -->
  </div><!-- /modal-body -->

</div>
</div>
</div><!-- /modal -->

<!-- Modal Konfirmasi Hapus Kalender -->
<div class="modal fade" id="kwModalHapus" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:380px;">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-header" style="background:#fef2f2;border-bottom:1.5px solid #fecaca;padding:16px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:34px;height:34px;background:#fee2e2;border-radius:9px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-trash-fill" style="color:#dc2626;"></i>
          </div>
          <h6 class="modal-title mb-0 fw-bold" style="color:#991b1b;font-size:.92rem;" id="kwHapusTitle">Hapus Data</h6>
        </div>
        <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:18px 20px;">
        <p style="font-size:.84rem;color:#334155;margin-bottom:10px;">Anda akan menghapus:</p>
        <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:9px;padding:10px 14px;font-weight:700;font-size:.86rem;color:#991b1b;" id="kwHapusNama">-</div>
        <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:8px 13px;margin-top:10px;font-size:.76rem;color:#92400e;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>Data tidak dapat dikembalikan setelah dihapus.
        </div>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 16px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.81rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <button type="button" id="kwHapusConfirmBtn"
          style="border-radius:8px;border:none;font-size:.81rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);box-shadow:0 4px 12px rgba(220,38,38,.24);cursor:pointer;">
          <i class="bi bi-trash-fill me-1"></i>Ya, Hapus
        </button>
      </div>
    </div>
  </div>
</div>
<script>
/* ============================================================
   KALENDER JS
   - kwOpen(tgl)      : buka modal
   - kwToggle(id)     : show/hide form
   - kwPickWarna(el)  : pilih warna badge jadwal
   - kwSimpanJdwl()   : simpan jadwal pribadi
   - kwSimpanKgt()    : simpan kegiatan RT (admin)
============================================================ */
var KW_BASE  = '<?php echo base_url(); ?>';
var KW_ADMIN = <?php echo $is_admin_view ? 'true' : 'false'; ?>;
var KW_WARGA = <?php echo (int)$warga_id; ?>;
var KW_BISA  = <?php echo $bisa_jadwal ? 'true' : 'false'; ?>;

var KW_PW = {
    Legi:'#10b981', Pahing:'#f59e0b', Pon:'#3b82f6', Wage:'#ef4444', Kliwon:'#8b5cf6'
};

var kwTgl    = '';
var kwModal  = null;
var kwReload = false;   // reload grid setelah kegiatan RT berubah

/* ── Buka modal ────────────────────────────────────────── */
function kwOpen(tgl) {
    kwTgl = tgl;

    // Reset UI
    document.getElementById('kwSpin').style.display = 'block';
    document.getElementById('kwBody').style.display = 'none';
    kwToggle('kwFrmJdwl', false);
    kwToggle('kwFrmKgt',  false);
    kwResetAll();

    // Header: tanggal
    var d  = new Date(tgl + 'T00:00:00');
    var HN = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
    var BN = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
    document.getElementById('kwMTgl').textContent =
        HN[d.getDay()] + ', ' + d.getDate() + ' ' + BN[d.getMonth()] + ' ' + d.getFullYear();

    // Header: weton + neptu + warna sesuai pasaran
    var cell = document.querySelector('[data-tgl="' + tgl + '"]');
    if (cell) {
        var pasaran = cell.dataset.pasaran;
        document.getElementById('kwMWeton').textContent = 'Weton: ' + cell.dataset.weton;
        document.getElementById('kwMNeptu').textContent = 'Neptu: ' + cell.dataset.neptu;
        var gradEnd = KW_PW[pasaran] || '#14b8a6';
        document.getElementById('kwHead').style.background =
            'linear-gradient(135deg, #0d9488, ' + gradEnd + ')';
    }

    // Tampilkan modal
    if (!kwModal) {
        kwModal = new bootstrap.Modal(document.getElementById('kwModal'), {keyboard: true});
    }
    kwModal.show();

    // Load data dari server
    kwFetch(tgl);
}




/* ── Fetch detail tanggal ──────────────────────────────── */
function kwFetch(tgl) {
    kwPost('kalender/detail_tanggal', {tanggal: tgl}, function(d) {
        document.getElementById('kwSpin').style.display = 'none';
        document.getElementById('kwBody').style.display = 'block';
        kwRender(d);
    }, function() {
        document.getElementById('kwSpin').innerHTML =
            '<p class="text-danger p-3 text-center">Gagal memuat data. Coba lagi.</p>';
    });
}

/* ── Render isi modal ──────────────────────────────────── */
function kwRender(d) {
    // Banner libur
    var lb = document.getElementById('kwLiburBox');
    if (d.libur) {
        document.getElementById('kwLiburTxt').textContent = d.libur;
        lb.style.display = 'block';
    } else {
        lb.style.display = 'none';
    }

    // Kegiatan RT
    var sk  = document.getElementById('kwSeksiKgt');
    var lk  = document.getElementById('kwListKgt');
    var kgt = d.kegiatan || [];
    if (kgt.length > 0) {
        sk.style.display = 'block';
        lk.innerHTML = kgt.map(function(k) {
            var aksi = '';
            if (KW_ADMIN) {
                aksi = '<div style="margin-top:5px;display:flex;gap:10px;">' +
                    '<button onclick="kwEditKgt(' + k.id + ')" style="background:none;border:none;' +
                    'color:#f59e0b;font-size:.72rem;cursor:pointer;padding:0;font-weight:700;">' +
                    '<i class="bi bi-pencil me-1"></i>Edit</button>' +
                    '<button onclick="kwHapusKgt(' + k.id + ',\'' + kwE(k.judul) + '\')" style="background:none;border:none;' +
                    'color:#ef4444;font-size:.72rem;cursor:pointer;padding:0;font-weight:700;">' +
                    '<i class="bi bi-trash me-1"></i>Hapus</button>' +
                    '</div>';
            }
            return '<div style="background:#fffbeb;border:1px solid #fde68a;' +
                'border-radius:10px;padding:10px 13px;margin-bottom:8px;">' +
                '<div style="font-weight:800;color:#92400e;font-size:.83rem;">' + kwE(k.judul) + '</div>' +
                (k.waktu_mulai
                    ? '<div style="color:#b45309;font-size:.72rem;margin-top:3px;">' +
                      '<i class="bi bi-clock me-1"></i>' + k.waktu_mulai.substring(0,5) + '</div>'
                    : '') +
                (k.tempat
                    ? '<div style="color:#b45309;font-size:.72rem;">' +
                      '<i class="bi bi-geo-alt me-1"></i>' + kwE(k.tempat) + '</div>'
                    : '') +
                (k.deskripsi
                    ? '<div style="color:#78350f;font-size:.75rem;margin-top:3px;">' + kwE(k.deskripsi) + '</div>'
                    : '') +
                aksi + '</div>';
        }).join('');
    } else {
        sk.style.display = 'none';
        lk.innerHTML = '';
    }

    // Jadwal pribadi
    var lj  = document.getElementById('kwListJdwl');
    var jdw = d.jadwal || [];
    if (jdw.length > 0) {
        lj.innerHTML = jdw.map(function(j) {
            var done = (j.is_selesai == '1' || j.is_selesai === 1 || j.is_selesai === true);
            return '<div style="border-left:3px solid ' + j.warna + ';background:#f8fafc;' +
                'border-radius:0 10px 10px 0;padding:9px 12px;margin-bottom:7px;' +
                (done ? 'opacity:.5;' : '') + '">' +
                '<div style="display:flex;justify-content:space-between;align-items:flex-start;">' +
                '<div style="font-weight:800;color:#1e293b;font-size:.83rem;' +
                    (done ? 'text-decoration:line-through;' : '') + '">' + kwE(j.judul) + '</div>' +
                '<div style="display:flex;gap:6px;flex-shrink:0;margin-left:8px;">' +
                    '<button onclick="kwToggleSelesai(' + j.id + ')" title="' +
                        (done ? 'Batalkan' : 'Tandai selesai') + '" ' +
                        'style="background:none;border:none;cursor:pointer;font-size:1rem;padding:0;' +
                        'color:' + (done ? '#94a3b8' : '#10b981') + ';">' +
                        '<i class="bi bi-' + (done ? 'arrow-counterclockwise' : 'check-circle-fill') + '"></i>' +
                    '</button>' +
                    '<button onclick="kwEditJdwl(' + j.id + ')" ' +
                        'style="background:none;border:none;cursor:pointer;font-size:.9rem;padding:0;color:#94a3b8;">' +
                        '<i class="bi bi-pencil"></i>' +
                    '</button>' +
                    '<button onclick="kwHapusJdwl(' + j.id + ',\'' + kwE(j.judul) + '\')" ' +
                        'style="background:none;border:none;cursor:pointer;font-size:.9rem;padding:0;color:#ef4444;">' +
                        '<i class="bi bi-trash"></i>' +
                    '</button>' +
                '</div></div>' +
                (j.waktu_mulai
                    ? '<div style="color:#64748b;font-size:.71rem;margin-top:3px;">' +
                      '<i class="bi bi-clock me-1"></i>' + j.waktu_mulai.substring(0,5) +
                      (j.waktu_selesai ? ' \u2013 ' + j.waktu_selesai.substring(0,5) : '') + '</div>'
                    : '') +
                (j.deskripsi
                    ? '<div style="color:#64748b;font-size:.74rem;margin-top:3px;">' + kwE(j.deskripsi) + '</div>'
                    : '') +
                '</div>';
        }).join('');
    } else {
        lj.innerHTML =
            '<div style="text-align:center;padding:16px 0;color:#94a3b8;font-size:.8rem;">' +
            '<i class="bi bi-calendar-x d-block mb-1" style="font-size:1.3rem;"></i>' +
            'Belum ada jadwal pribadi' +
            '</div>';
    }
}

/* ── Show/hide form ────────────────────────────────────── */
function kwToggle(id, force) {
    var el = document.getElementById(id);
    if (!el) return;
    var open = (force !== undefined) ? force : (el.style.display === 'none');
    el.style.display = open ? 'block' : 'none';
    if (open) {
        setTimeout(function() {
            el.scrollIntoView({behavior: 'smooth', block: 'nearest'});
            var fi = el.querySelector('input[type=text], textarea');
            if (fi) fi.focus();
        }, 100);
    }
}

/* ── Pilih warna ───────────────────────────────────────── */
function kwPickWarna(el, w) {
    document.querySelectorAll('.kwWarnaPick').forEach(function(d) {
        d.style.border    = '2px solid transparent';
        d.style.transform = 'scale(1)';
    });
    el.style.border    = '2px solid #0f172a';
    el.style.transform = 'scale(1.3)';
    document.getElementById('kwWarna').value = w;
}
function kwSetWarna(w) {
    document.querySelectorAll('.kwWarnaPick').forEach(function(d) {
        var a = d.dataset.w === w;
        d.style.border    = a ? '2px solid #0f172a' : '2px solid transparent';
        d.style.transform = a ? 'scale(1.3)' : 'scale(1)';
    });
    document.getElementById('kwWarna').value = w || '#3b82f6';
}

/* ── Reset semua form ──────────────────────────────────── */
function kwResetAll() {
    // Form jadwal
    ['kwJudul','kwMulai','kwSelesai','kwDesk'].forEach(function(id) {
        var e = document.getElementById(id); if (e) e.value = '';
    });
    var ei = document.getElementById('kwIdEdit'); if (ei) ei.value = '0';
    var et = document.getElementById('kwFrmJdwlTitle'); if (et) et.textContent = 'Jadwal Baru';
    kwSetWarna('#3b82f6');
    // Form kegiatan
    ['kwKgtJudul','kwKgtWaktu','kwKgtTempat','kwKgtDesk'].forEach(function(id) {
        var e = document.getElementById(id); if (e) e.value = '';
    });
    var ek = document.getElementById('kwKgtId'); if (ek) ek.value = '0';
    var ekt = document.getElementById('kwFrmKgtTitle'); if (ekt) ekt.textContent = 'Kegiatan RT Baru';
}

/* ── Simpan jadwal pribadi ─────────────────────────────── */
function kwSimpanJdwl(ev) {
    var judul = document.getElementById('kwJudul').value.trim();
    if (!judul) { alert('Judul jadwal wajib diisi!'); document.getElementById('kwJudul').focus(); return; }

    var btn = ev.target.closest ? ev.target.closest('button') : ev.target;
    var orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status"></span>Menyimpan...';

    kwPost('kalender/simpan_jadwal', {
        tanggal:       kwTgl,
        judul:         judul,
        deskripsi:     document.getElementById('kwDesk').value,
        waktu_mulai:   document.getElementById('kwMulai').value,
        waktu_selesai: document.getElementById('kwSelesai').value,
        warna:         document.getElementById('kwWarna').value || '#3b82f6',
        id_edit:       document.getElementById('kwIdEdit').value,
    }, function(d) {
        btn.disabled = false; btn.innerHTML = orig;
        if (d.status === 'ok') {
            kwToggle('kwFrmJdwl', false);
            kwResetAll();
            kwFetch(kwTgl);
            kwRefreshCell(kwTgl);
        } else {
            alert(d.msg || 'Gagal menyimpan jadwal');
        }
    }, function() {
        btn.disabled = false; btn.innerHTML = orig;
        alert('Terjadi kesalahan, coba lagi');
    });
}

/* ── Edit jadwal (isi form dari server) ────────────────── */
function kwEditJdwl(id) {
    kwPost('kalender/get_jadwal', {id: id}, function(d) {
        if (d.status !== 'ok') { alert('Data tidak ditemukan'); return; }
        var j = d.data;
        document.getElementById('kwIdEdit').value  = id;
        document.getElementById('kwJudul').value   = j.judul;
        document.getElementById('kwDesk').value    = j.deskripsi || '';
        document.getElementById('kwMulai').value   = j.waktu_mulai   ? j.waktu_mulai.substring(0,5)   : '';
        document.getElementById('kwSelesai').value = j.waktu_selesai ? j.waktu_selesai.substring(0,5) : '';
        kwSetWarna(j.warna || '#3b82f6');
        document.getElementById('kwFrmJdwlTitle').textContent = 'Edit Jadwal';
        kwToggle('kwFrmJdwl', true);
    });
}


/* ── Modal hapus ── */
var _kwModalHapus = null;
var _kwHapusCb    = null;

function kwKonfirmasiHapus(title, nama, callback) {
  document.getElementById('kwHapusTitle').textContent = title;
  document.getElementById('kwHapusNama').textContent  = nama;
  _kwHapusCb = callback;
  var modalEl = document.getElementById('kwModalHapus');
  if(!_kwModalHapus) _kwModalHapus = new bootstrap.Modal(modalEl);
  _kwModalHapus.show();
}

document.getElementById('kwHapusConfirmBtn').addEventListener('click', function() {
  if(_kwModalHapus) _kwModalHapus.hide();
  if(_kwHapusCb)    _kwHapusCb();
  _kwHapusCb = null;
});
/* ── Hapus jadwal ──────────────────────────────────────── */
function kwHapusJdwl(id, nama) {
  kwKonfirmasiHapus('Hapus Jadwal Pribadi', nama || 'Jadwal #' + id, function() {
    kwPost('kalender/hapus_jadwal', {id: id}, function(d) {
      if (d.status === 'ok') { kwFetch(kwTgl); kwRefreshCell(kwTgl); }
      else alert('Gagal menghapus');
    });
  });
}

function kwHapusKgt(id, nama) {
  kwKonfirmasiHapus('Hapus Kegiatan RT', nama || 'Kegiatan #' + id, function() {
    kwPost('kalender/hapus_kegiatan', {id: id}, function(d) {
      if (d.status === 'ok') { kwFetch(kwTgl); kwReload = true; }
      else alert('Gagal menghapus kegiatan');
    });
  });
}

/* ── Toggle selesai ────────────────────────────────────── */
function kwToggleSelesai(id) {
    kwPost('kalender/toggle_selesai', {id: id}, function(d) {
        if (d.status === 'ok') kwFetch(kwTgl);
    });
}

/* ── Simpan kegiatan RT (admin) ────────────────────────── */
function kwSimpanKgt(ev) {
    var judul = document.getElementById('kwKgtJudul').value.trim();
    if (!judul) { alert('Judul kegiatan wajib diisi!'); document.getElementById('kwKgtJudul').focus(); return; }

    var btn = ev.target.closest ? ev.target.closest('button') : ev.target;
    var orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status"></span>Menyimpan...';

    kwPost('kalender/simpan_kegiatan', {
        tanggal:    kwTgl,
        judul:      judul,
        waktu_mulai: document.getElementById('kwKgtWaktu').value,
        tempat:      document.getElementById('kwKgtTempat').value,
        deskripsi:   document.getElementById('kwKgtDesk').value,
        id_edit:     document.getElementById('kwKgtId').value,
    }, function(d) {
        btn.disabled = false; btn.innerHTML = orig;
        if (d.status === 'ok') {
            kwToggle('kwFrmKgt', false);
            kwResetAll();
            kwFetch(kwTgl);
            kwReload = true;   // grid perlu reload (kegiatan RT tampil semua warga)
        } else {
            alert(d.msg || 'Gagal menyimpan kegiatan');
        }
    }, function() {
        btn.disabled = false; btn.innerHTML = orig;
        alert('Terjadi kesalahan, coba lagi');
    });
}

/* ── Edit kegiatan RT (admin) ──────────────────────────── */
function kwEditKgt(id) {
    kwPost('kalender/get_kegiatan', {id: id}, function(d) {
        if (d.status !== 'ok') { alert('Data tidak ditemukan'); return; }
        var k = d.data;
        document.getElementById('kwKgtId').value    = id;
        document.getElementById('kwKgtJudul').value = k.judul;
        document.getElementById('kwKgtWaktu').value = k.waktu_mulai   ? k.waktu_mulai.substring(0,5)   : '';
        document.getElementById('kwKgtTempat').value= k.tempat || '';
        document.getElementById('kwKgtDesk').value  = k.deskripsi || '';
        document.getElementById('kwFrmKgtTitle').textContent = 'Edit Kegiatan RT';
        kwToggle('kwFrmKgt', true);
    });
}




/* ── Refresh label event di cell (tanpa reload halaman) ── */
function kwRefreshCell(tgl) {
    kwPost('kalender/detail_tanggal', {tanggal: tgl}, function(data) {
        var cell = document.querySelector('[data-tgl="' + tgl + '"]');
        if (!cell) return;
        var evWrap = cell.querySelector('.kw-evs');
        if (!evWrap) return;

        // Hapus label jadwal lama
        evWrap.querySelectorAll('.kw-ev-jd, .kw-ev-lebih').forEach(function(e) { e.remove(); });

        // Tambah label jadwal baru
        var jdw = data.jadwal || [];
        jdw.slice(0, 2).forEach(function(j) {
            var s = document.createElement('span');
            s.className = 'kw-ev kw-ev-jd';
            s.style.background = j.warna;
            s.textContent = j.judul;
            evWrap.appendChild(s);
        });
        if (jdw.length > 2) {
            var s = document.createElement('span');
            s.className = 'kw-ev kw-ev-lebih';
            s.style.cssText = 'background:#e2e8f0;color:#475569;';
            s.textContent = '+' + (jdw.length - 2) + ' lagi';
            evWrap.appendChild(s);
        }
    });
}

/* ── Reload grid setelah modal ditutup (jika kegiatan RT berubah) */
document.getElementById('kwModal').addEventListener('hidden.bs.modal', function() {
    if (kwReload) { kwReload = false; location.reload(); }
});

/* ── Helper: AJAX POST ─────────────────────────────────── */
function kwPost(url, data, onOk, onErr) {
    fetch(KW_BASE + url, {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: new URLSearchParams(data)
    })
    .then(function(r) {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
    })
    .then(function(d) { if (onOk) onOk(d); })
    .catch(function(e) {
        console.error('kwPost error [' + url + ']:', e);
        if (onErr) onErr(e);
    });
}

/* ── Helper: escape HTML ───────────────────────────────── */
function kwE(s) {
    if (!s) return '';
    return String(s)
        .replace(/&/g,'&amp;').replace(/</g,'&lt;')
        .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>