<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 active">Hari Libur</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline">
      <div class="card-header d-flex align-items-center flex-wrap">
        <h3 class="card-title mr-auto"><i class="fa fa-calendar mr-1"></i> Hari Libur <?php echo $tahun; ?></h3>
        <div class="d-flex align-items-center mr-2">
          <select onchange="window.location='<?php echo site_url('master/harlibur'); ?>?tahun='+this.value" class="form-control form-control-sm mr-2" style="width:100px;">
            <?php $years = array_unique(array_merge($tahun_list, [date('Y'), date('Y')+1])); rsort($years); ?>
            <?php foreach ($years as $y): ?>
              <option value="<?php echo $y; ?>" <?php echo $y == $tahun ? 'selected' : ''; ?>><?php echo $y; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <button type="button" class="btn btn-danger btn-sm" id="btn-sync-libur">
          <i class="fa fa-refresh mr-1"></i> Sync Nasional
        </button>
      </div>
      <div class="card-body">
        <div class="d-flex align-items-center flex-wrap mb-3" style="gap: 12px;">
          <span class="badge badge-danger px-3 py-2">Nasional</span>
          <span class="badge badge-warning px-3 py-2 text-white">Perusahaan</span>
          <span class="text-muted small">Klik tanggal kosong untuk tambah hari libur. Klik event untuk edit atau hapus.</span>
        </div>
        <div id="holiday-calendar"></div>
      </div>
    </div>
  </div>
</section>

<div class="modal fade" id="modalHoliday" tabindex="-1" role="dialog" aria-labelledby="modalHolidayLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="modalHolidayLabel"><i class="fa fa-calendar-plus-o mr-1"></i> Atur Hari Libur</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <form id="form-holiday-modal">
        <div class="modal-body">
          <input type="hidden" name="id_libur" id="holiday-id-libur" value="">
          <div class="form-group">
            <label>Tanggal <span class="text-danger">*</span></label>
            <input type="date" name="tanggal" id="holiday-tanggal" class="form-control" required>
          </div>
          <div class="form-group">
            <label>Nama Hari Libur <span class="text-danger">*</span></label>
            <input type="text" name="nama_libur" id="holiday-nama" class="form-control" maxlength="100" placeholder="Contoh: Hari Raya Nyepi" required>
          </div>
          <div class="form-group mb-0">
            <label>Jenis <span class="text-danger">*</span></label>
            <select name="jenis" id="holiday-jenis" class="form-control" required>
              <option value="NASIONAL">Hari Libur Nasional</option>
              <option value="PERUSAHAAN">Hari Libur Perusahaan</option>
            </select>
          </div>
        </div>
        <div class="modal-footer d-flex justify-content-between">
          <button type="button" class="btn btn-outline-danger" id="btn-delete-holiday" style="display:none;"><i class="fa fa-trash mr-1"></i> Hapus</button>
          <div class="ml-auto">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
            <button type="submit" class="btn btn-danger"><i class="fa fa-save mr-1"></i> Simpan</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.14/index.global.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.14/index.global.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.14/locales-all.global.min.js"></script>

<style>
#holiday-calendar {
  min-height: 720px;
}

.fc .fc-toolbar-title {
  font-size: 1.15rem;
  font-weight: 700;
}

.fc .fc-button-primary {
  background-color: #dc3545;
  border-color: #dc3545;
}

.fc .fc-button-primary:not(:disabled).fc-button-active,
.fc .fc-button-primary:not(:disabled):active,
.fc .fc-button-primary:hover {
  background-color: #bd2130;
  border-color: #bd2130;
}

.fc .fc-daygrid-day.fc-day-today {
  background-color: #fff6e8;
}

.fc .fc-daygrid-day-number {
  color: #343a40;
  font-weight: 600;
}

.fc .fc-event {
  border-radius: 6px;
  padding: 2px 4px;
  font-size: 12px;
  cursor: pointer;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var calendarEl = document.getElementById('holiday-calendar');
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var selectedYear = '<?php echo (int) $tahun; ?>';
  var modalEl = $('#modalHoliday');
  var formEl = document.getElementById('form-holiday-modal');
  var deleteBtn = document.getElementById('btn-delete-holiday');

  function readCookie(name) {
    var cookies = document.cookie ? document.cookie.split('; ') : [];
    for (var i = 0; i < cookies.length; i++) {
      var parts = cookies[i].split('=');
      var key = parts.shift();
      if (key === name) {
        return decodeURIComponent(parts.join('='));
      }
    }
    return '';
  }

  function resetHolidayForm() {
    document.getElementById('holiday-id-libur').value = '';
    document.getElementById('holiday-tanggal').value = '';
    document.getElementById('holiday-nama').value = '';
    document.getElementById('holiday-jenis').value = 'NASIONAL';
    deleteBtn.style.display = 'none';
  }

  function fillHolidayForm(data) {
    document.getElementById('holiday-id-libur').value = data.id_libur || '';
    document.getElementById('holiday-tanggal').value = data.tanggal || '';
    document.getElementById('holiday-nama').value = data.nama_libur || '';
    document.getElementById('holiday-jenis').value = data.jenis || 'NASIONAL';
    deleteBtn.style.display = data.id_libur ? 'inline-block' : 'none';
  }

  var calendar = new FullCalendar.Calendar(calendarEl, {
    locale: 'id',
    initialView: 'dayGridMonth',
    initialDate: selectedYear + '-01-01',
    height: 'auto',
    validRange: {
      start: selectedYear + '-01-01',
      end: (parseInt(selectedYear, 10) + 1) + '-01-01'
    },
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth'
    },
    buttonText: {
      today: 'Hari Ini',
      month: 'Kalender'
    },
    events: {
      url: '<?php echo site_url('master/harlibur/events_json'); ?>',
      method: 'GET',
      extraParams: function () {
        return { tahun: selectedYear };
      }
    },
    dateClick: function (info) {
      resetHolidayForm();
      fillHolidayForm({ tanggal: info.dateStr, jenis: 'PERUSAHAAN' });
      modalEl.modal('show');
    },
    eventClick: function (info) {
      resetHolidayForm();
      fillHolidayForm({
        id_libur: info.event.id,
        tanggal: info.event.startStr,
        nama_libur: info.event.extendedProps.nama_libur,
        jenis: info.event.extendedProps.jenis
      });
      modalEl.modal('show');
    }
  });
  calendar.render();

  formEl.addEventListener('submit', function (e) {
    e.preventDefault();
    var formData = new FormData(formEl);
    formData.append(csrfTokenName, readCookie(csrfCookieName));

    fetch('<?php echo site_url('master/harlibur/save_ajax'); ?>', {
      method: 'POST',
      credentials: 'same-origin',
      body: formData
    })
      .then(function (resp) { return resp.json(); })
      .then(function (resp) {
        if (!resp.success) {
          Swal.fire({ icon: 'error', title: 'Gagal Menyimpan', text: resp.message || 'Perubahan tidak dapat disimpan.' });
          return;
        }
        modalEl.modal('hide');
        Swal.fire({ icon: 'success', title: 'Berhasil', text: resp.message, timer: 1300, showConfirmButton: false });
        calendar.refetchEvents();
      })
      .catch(function () {
        Swal.fire({ icon: 'error', title: 'Gagal Menyimpan', text: 'Permintaan ke server gagal.' });
      });
  });

  deleteBtn.addEventListener('click', function () {
    var id = document.getElementById('holiday-id-libur').value;
    if (!id) {
      return;
    }

    Swal.fire({
      title: 'Hapus Hari Libur?',
      text: 'Data hari libur pada tanggal ini akan dihapus.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#c0392b',
      cancelButtonText: 'Batal',
      confirmButtonText: 'Ya, Hapus'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }

      var formData = new FormData();
      formData.append(csrfTokenName, readCookie(csrfCookieName));

      fetch('<?php echo site_url('master/harlibur/delete_ajax'); ?>/' + id, {
        method: 'POST',
        credentials: 'same-origin',
        body: formData
      })
        .then(function (resp) { return resp.json(); })
        .then(function (resp) {
          if (!resp.success) {
            Swal.fire({ icon: 'error', title: 'Gagal Menghapus', text: resp.message || 'Data tidak dapat dihapus.' });
            return;
          }
          modalEl.modal('hide');
          Swal.fire({ icon: 'success', title: 'Berhasil', text: resp.message, timer: 1300, showConfirmButton: false });
          calendar.refetchEvents();
        })
        .catch(function () {
          Swal.fire({ icon: 'error', title: 'Gagal Menghapus', text: 'Permintaan ke server gagal.' });
        });
    });
  });

  document.getElementById('btn-sync-libur').addEventListener('click', function () {
    Swal.fire({
      title: 'Sinkron Hari Libur Nasional?',
      text: 'Data nasional untuk tahun ' + selectedYear + ' akan di-generate dari sumber sinkron publik.',
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Ya, sinkronkan',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#dc3545'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }

      var formData = new FormData();
      formData.append('tahun', selectedYear);
      formData.append(csrfTokenName, readCookie(csrfCookieName));

      Swal.fire({ title: 'Sinkronisasi berjalan', text: 'Sedang mengambil data hari libur nasional...', allowOutsideClick: false, didOpen: function () { Swal.showLoading(); } });

      fetch('<?php echo site_url('master/harlibur/sync_nasional'); ?>', {
        method: 'POST',
        credentials: 'same-origin',
        body: formData
      })
        .then(function (resp) { return resp.json(); })
        .then(function (resp) {
          if (!resp.success) {
            Swal.fire({ icon: 'error', title: 'Sinkron Gagal', text: resp.message || 'Data tidak berhasil disinkronkan.' });
            return;
          }
          Swal.fire({ icon: 'success', title: 'Sinkron Berhasil', text: resp.message });
          calendar.refetchEvents();
        })
        .catch(function () {
          Swal.fire({ icon: 'error', title: 'Sinkron Gagal', text: 'Permintaan sinkron ke server gagal.' });
        });
    });
  });
});
</script>
