<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0"><?php echo $page_subtitle; ?></p>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></li>
          <li class="breadcrumb-item"><a href="<?php echo site_url('master/shift'); ?>">Manajemen Shift</a></li>
          <li class="breadcrumb-item active">Jadwal Kerja</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="row">

      <!-- Form Jadwal Mingguan -->
      <div class="col-md-4">
        <div class="card card-danger card-outline">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-calendar mr-1"></i> Jadwal Mingguan</h3>
          </div>
          <?php echo form_open('master/shift/simpan_assignment', ['id' => 'form-assignment']); ?>
            <div class="card-body">

              <div class="form-group">
                <label>Tipe Target <span class="text-danger">*</span></label>
                <select name="tipe" id="sel-tipe" class="form-control" required>
                  <option value="PEGAWAI" <?php echo ($f_tipe === 'PEGAWAI') ? 'selected' : ''; ?>>Per Pegawai</option>
                  <option value="DIVISI"  <?php echo ($f_tipe === 'DIVISI')  ? 'selected' : ''; ?>>Per Divisi</option>
                </select>
              </div>

              <div class="form-group">
                <label id="lbl-divisi">Divisi</label>
                <select name="divisi_filter" id="sel-divisi" class="form-control">
                  <option value="">-- Semua Divisi --</option>
                  <?php foreach ($divisi_list as $d): ?>
                  <option value="<?php echo $d->id_divisi; ?>" <?php echo ($f_divisi == $d->id_divisi) ? 'selected' : ''; ?>>
                    <?php echo html_escape($d->nama_divisi); ?>
                  </option>
                  <?php endforeach; ?>
                </select>
              </div>

              <!-- Input id_referensi tersembunyi -->
              <input type="hidden" name="id_referensi" id="inp-referensi" value="">

              <div class="form-group" id="wrap-pegawai">
                <label>Pegawai <span class="text-danger">*</span></label>
                <select name="pegawai_select" id="sel-pegawai" class="form-control">
                  <option value="">-- Pilih Divisi dulu --</option>
                </select>
              </div>

              <?php
              $hari_map = [
                1 => 'Senin',
                2 => 'Selasa',
                3 => 'Rabu',
                4 => 'Kamis',
                5 => 'Jumat',
                6 => 'Sabtu',
                7 => 'Minggu',
              ];
              $default_shift_id = !empty($default_shift->id_shift) ? (int) $default_shift->id_shift : 0;
              ?>

              <div class="form-group">
                <label>Jadwal Mingguan <span class="text-danger">*</span></label>
                <div class="table-responsive">
                  <table class="table table-sm table-bordered mb-0">
                    <thead>
                      <tr>
                        <th style="width:90px;">Hari</th>
                        <th>Shift / Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($hari_map as $hari_ke => $hari_label): ?>
                      <?php $selected_default = ($hari_ke <= 5 && $default_shift_id > 0) ? (string) $default_shift_id : 'OFF'; ?>
                      <tr>
                        <td class="font-weight-semibold"><?php echo $hari_label; ?></td>
                        <td>
                          <select name="hari_shift[<?php echo $hari_ke; ?>]" class="form-control form-control-sm" required>
                            <option value="OFF" <?php echo $selected_default === 'OFF' ? 'selected' : ''; ?>>OFF / Libur</option>
                            <?php foreach ($shift_list as $s): ?>
                            <option value="<?php echo $s->id_shift; ?>" <?php echo ($selected_default === (string) $s->id_shift) ? 'selected' : ''; ?>>
                              <?php echo html_escape($s->nama_shift); ?> (<?php echo substr($s->jam_masuk,0,5); ?>-<?php echo substr($s->jam_keluar,0,5); ?>)
                            </option>
                            <?php endforeach; ?>
                          </select>
                        </td>
                      </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
                <small class="text-muted">Atur per hari. Contoh normal 6 hari: Senin-Jumat shift normal, Sabtu shift setengah hari, Minggu OFF.</small>
              </div>

              <div class="row">
                <div class="col-sm-6">
                  <div class="form-group">
                    <label>Berlaku Mulai <span class="text-danger">*</span></label>
                    <input type="date" name="berlaku_mulai" class="form-control"
                           value="<?php echo date('Y-m-01'); ?>" required>
                  </div>
                </div>
                <div class="col-sm-6">
                  <div class="form-group">
                    <label>Berlaku Selesai</label>
                    <input type="date" name="berlaku_selesai" class="form-control"
                           placeholder="Kosong = selamanya">
                    <small class="text-muted">Kosongkan jika berlaku selamanya.</small>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label>Keterangan</label>
                <input type="text" name="keterangan" class="form-control" maxlength="255">
              </div>
            </div>
            <div class="card-footer">
              <button type="submit" class="btn btn-danger btn-block">
                <i class="fa fa-save mr-1"></i> Simpan Jadwal Mingguan
              </button>
            </div>
          <?php echo form_close(); ?>
        </div>
      </div>

      <!-- Daftar Jadwal -->
      <div class="col-md-8">
        <div class="card card-danger card-outline">
          <div class="card-header d-flex align-items-center">
            <h3 class="card-title mr-auto"><i class="fa fa-list mr-1"></i> Daftar Jadwal</h3>
            <a href="<?php echo site_url('master/shift/assignment?tipe=PEGAWAI'); ?>"
               class="btn btn-sm <?php echo ($f_tipe === 'PEGAWAI') ? 'btn-danger' : 'btn-outline-secondary'; ?> mr-1">Per Pegawai</a>
            <a href="<?php echo site_url('master/shift/assignment?tipe=DIVISI'); ?>"
               class="btn btn-sm <?php echo ($f_tipe === 'DIVISI') ? 'btn-danger' : 'btn-outline-secondary'; ?>">Per Divisi</a>
          </div>
          <div class="card-body p-0">
            <?php if (empty($list)): ?>
              <div class="text-center text-muted py-4">
                <i class="fa fa-calendar fa-2x mb-2"></i>
                <p>Belum ada jadwal kerja untuk tipe ini.</p>
              </div>
            <?php else: ?>
            <div class="table-responsive">
              <table class="table table-bordered table-hover mb-0">
                <thead>
                  <tr>
                    <?php if ($f_tipe === 'PEGAWAI'): ?>
                    <th>NIP</th>
                    <th>Nama Pegawai</th>
                    <th>Divisi</th>
                    <?php else: ?>
                    <th>Divisi</th>
                    <?php endif; ?>
                    <th>Jadwal Mingguan (Senin - Minggu)</th>
                    <th>Masa Berlaku</th>
                    <th style="width:60px;">Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  <?php 
                  $hari_singkat = [1=>'Sen', 2=>'Sel', 3=>'Rab', 4=>'Kam', 5=>'Jum', 6=>'Sab', 7=>'Min']; 
                  ?>
                  <?php foreach ($list as $a): ?>
                  <tr>
                    <?php if ($f_tipe === 'PEGAWAI'): ?>
                    <td><strong><?php echo html_escape($a->nip); ?></strong></td>
                    <td><?php echo html_escape($a->nama_lengkap); ?></td>
                    <td><?php echo html_escape($a->nama_divisi); ?></td>
                    <?php else: ?>
                    <td><strong><?php echo html_escape($a->nama_divisi); ?></strong></td>
                    <?php endif; ?>
                    <td>
                      <div class="d-flex flex-wrap" style="gap: 5px;">
                        <?php for ($h=1; $h<=7; $h++): ?>
                          <?php 
                          $d = $a->days[$h] ?? null; 
                          $is_kerja = ($d && (int)$d->is_hari_kerja === 1);
                          $bg_class = $is_kerja ? 'bg-danger' : 'bg-light text-muted';
                          $title = $is_kerja ? $d->nama_shift . ' (' . substr($d->jam_masuk,0,5) . '-' . substr($d->jam_keluar,0,5) . ')' : 'Libur/OFF';
                          ?>
                          <div class="text-center p-1 rounded border <?php echo $bg_class; ?>" 
                               style="min-width: 45px; font-size: 0.75rem;" 
                               title="<?php echo html_escape($title); ?>">
                            <div class="font-weight-bold" style="border-bottom: 1px solid rgba(0,0,0,0.1)"><?php echo $hari_singkat[$h]; ?></div>
                            <div><?php echo $is_kerja ? 'Work' : 'OFF'; ?></div>
                          </div>
                        <?php endfor; ?>
                      </div>
                      <?php if (!empty($a->keterangan)): ?>
                        <div class="mt-1 small text-muted"><em>Keterangan: <?php echo html_escape($a->keterangan); ?></em></div>
                      <?php endif; ?>
                    </td>
                    <td>
                      <div><?php echo date('d/m/Y', strtotime($a->berlaku_mulai)); ?></div>
                      <div class="small text-muted">
                        s/d <?php echo $a->berlaku_selesai ? date('d/m/Y', strtotime($a->berlaku_selesai)) : 'Selamanya'; ?>
                      </div>
                    </td>
                    <td class="text-center">
                      <div class="d-flex justify-content-center" style="gap: 5px;">
                        <button type="button" class="btn btn-info btn-xs" 
                                onclick='editJadwal(<?php echo json_encode($a); ?>)' title="Edit">
                           <i class="fa fa-edit"></i>
                        </button>
                        <a href="<?php echo site_url('master/shift/hapus_group?tipe=' . $a->tipe . '&id_referensi=' . $a->id_referensi . '&berlaku_mulai=' . $a->berlaku_mulai); ?>"
                           class="btn btn-danger btn-xs"
                           onclick="return confirm('Hapus seluruh jadwal mingguan ini?')" title="Hapus">
                           <i class="fa fa-trash"></i>
                        </a>
                      </div>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

    </div>
  </div>
</section>

<script>
(function() {
  var selTipe    = document.getElementById('sel-tipe');
  var selDivisi  = document.getElementById('sel-divisi');
  var selPegawai = document.getElementById('sel-pegawai');
  var wrapPeg    = document.getElementById('wrap-pegawai');
  var lblDivisi  = document.getElementById('lbl-divisi');
  var inpRef     = document.getElementById('inp-referensi');

  window.editJadwal = function(data) {
    selTipe.value = data.tipe;
    toggleTipe();
    
    if (data.tipe === 'DIVISI') {
      selDivisi.value = data.id_referensi;
      inpRef.value = data.id_referensi;
    } else {
      selDivisi.value = data.id_divisi;
      loadPegawai(data.id_referensi); // Pass the ID to select after load
    }
    
    // Set hari_shift
    for (var h = 1; h <= 7; h++) {
      var select = document.getElementsByName('hari_shift[' + h + ']')[0];
      if (select) {
        var dayData = data.days[h];
        if (dayData && dayData.is_hari_kerja == 1) {
          select.value = dayData.id_shift;
        } else {
          select.value = 'OFF';
        }
      }
    }
    
    // Set dates and metadata
    document.getElementsByName('berlaku_mulai')[0].value = data.berlaku_mulai;
    document.getElementsByName('berlaku_selesai')[0].value = data.berlaku_selesai || '';
    document.getElementsByName('keterangan')[0].value = data.keterangan || '';
    
    // Scroll to form
    document.querySelector('.card-danger').scrollIntoView({ behavior: 'smooth' });
  };

  function toggleTipe() {
    var tipe = selTipe.value;
    if (tipe === 'DIVISI') {
      wrapPeg.style.display  = 'none';
      lblDivisi.textContent  = 'Divisi Target *';
      selDivisi.required     = true;
      selPegawai.required    = false;
      inpRef.value = selDivisi.value;
    } else {
      wrapPeg.style.display  = '';
      lblDivisi.textContent  = 'Filter Divisi';
      selDivisi.required     = false;
      selPegawai.required    = true;
      inpRef.value = selPegawai.value;
    }
  }

  function loadPegawai(selectedId) {
    var idDivisi = selDivisi.value;
    if (!idDivisi) {
      selPegawai.innerHTML = '<option value="">-- Pilih Divisi dulu --</option>';
      return;
    }
    if (selTipe.value !== 'PEGAWAI' && !selectedId) return;

    selPegawai.innerHTML = '<option value="">Memuat...</option>';
    fetch('<?php echo site_url('master/shift/get_pegawai_by_divisi'); ?>?id_divisi=' + idDivisi, {
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      selPegawai.innerHTML = '<option value="">-- Pilih Pegawai --</option>';
      data.forEach(function(p) {
        var selected = (selectedId && p.id_pegawai == selectedId) ? ' selected' : '';
        selPegawai.innerHTML += '<option value="' + p.id_pegawai + '"' + selected + '>' + p.nip + ' - ' + p.nama_lengkap + '</option>';
      });
      if (selectedId) {
        inpRef.value = selectedId;
      }
    });
  }

  selTipe.addEventListener('change', toggleTipe);
  selDivisi.addEventListener('change', function() {
    if (selTipe.value === 'DIVISI') { inpRef.value = this.value; }
    loadPegawai();
  });
  selPegawai.addEventListener('change', function() {
    inpRef.value = this.value;
  });

  // Sinkronisasi sebelum submit
  document.getElementById('form-assignment').addEventListener('submit', function() {
    if (selTipe.value === 'DIVISI') {
      inpRef.value = selDivisi.value;
    } else {
      inpRef.value = selPegawai.value;
    }
  });

  toggleTipe();
  if (selDivisi.value) loadPegawai();
})();
</script>
