<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">Sistem Payroll</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">
        <h3 class="card-title mr-auto"><i class="fa fa-calculator mr-1"></i> Daftar Periode Payroll</h3>
        <?php if (($mode ?? 'all') !== 'approval'): ?>
        <button type="button" class="btn btn-danger btn-sm" id="btn-open-create-payroll">
          <i class="fa fa-plus mr-1"></i> Buat Periode
        </button>
        <?php endif; ?>
      </div>
      <div class="card-body">
        <?php if (!empty($list)): ?>
        <table id="tbl-payroll" class="table table-bordered table-hover table-striped">
          <thead>
            <tr>
              <th style="width:40px;">#</th>
              <th>Periode</th>
              <th>Jenis</th>
              <th>Status</th>
              <th>Proses</th>
              <th style="text-align:center;">Pegawai</th>
              <th style="text-align:right;">Total Neto</th>
              <th>Tanggal Proses</th>
              <th style="width:220px;">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($list as $i => $row): 
              $status_badge = 'badge-secondary';
              if ($row->status === 'DRAFT') $status_badge = 'badge-warning';
              elseif ($row->status === 'PROCESSED') $status_badge = 'badge-info';
              elseif ($row->status === 'APPROVED') $status_badge = 'badge-success';
              elseif ($row->status === 'LOCKED') $status_badge = 'badge-danger';

              $mode = strtolower((string) ($row->proses_mode ?? ''));
              $mode_label = '-';
              $mode_badge = 'badge-light';
              if ($mode === 'tanpa_absensi') {
                $mode_label = 'Tanpa Absensi';
                $mode_badge = 'badge-warning';
              } elseif ($mode === 'absensi') {
                $mode_label = 'Dengan Absensi';
                $mode_badge = 'badge-secondary';
              }
            ?>
            <tr>
              <td><?php echo $i + 1; ?></td>
              <td>
                <strong><?php echo bulan_indonesia($row->bulan) . ' ' . $row->tahun; ?></strong>
              </td>
              <td>
                <?php if (isset($row->tipe_periode) && $row->tipe_periode === 'THR'): ?>
                  <span class="badge badge-warning">THR</span>
                <?php else: ?>
                  <span class="badge badge-info">Reguler</span>
                <?php endif; ?>
              </td>
              <td>
                <span class="badge <?php echo $status_badge; ?>"><?php echo html_escape($row->status); ?></span>
              </td>
              <td>
                <span class="badge <?php echo $mode_badge; ?>"><?php echo $mode_label; ?></span>
              </td>
              <td style="text-align:center;"><?php echo (int) ($row->total_pegawai ?? 0); ?></td>
              <td style="text-align:right;">Rp <?php echo rupiah($row->total_neto); ?></td>
              <td><?php echo $row->processed_at ? format_tanggal_waktu($row->processed_at) : '-'; ?></td>
              <td>
                <a href="<?php echo site_url('transaksi/payroll/detail/' . $row->id_periode); ?>" class="btn btn-xs btn-primary" title="Detail"><i class="fa fa-eye"></i></a>
                <?php if (in_array($row->status, ['DRAFT', 'PROCESSED', 'APPROVED'])): ?>
                <button type="button" class="btn btn-xs btn-warning btn-open-proses" data-id="<?php echo $row->id_periode; ?>" title="Proses"><i class="fa fa-play"></i></button>
                <?php endif; ?>
                <?php if ($row->status === 'PROCESSED'): ?>
                <a href="<?php echo site_url('transaksi/payroll/approve/' . $row->id_periode); ?>" class="btn btn-xs btn-success btn-confirm" data-msg="Approve payroll periode ini?" title="Approve"><i class="fa fa-check"></i></a>
                <?php endif; ?>
                <?php if (in_array($row->status, ['APPROVED', 'LOCKED'])): ?>
                <a href="<?php echo site_url('transaksi/payroll/lock/' . $row->id_periode); ?>" class="btn btn-xs btn-danger btn-confirm" data-msg="Lock payroll periode ini?" title="Lock"><i class="fa fa-lock"></i></a>
                <?php endif; ?>
                <?php if ($row->status === 'DRAFT' || (string) $this->session->userdata('role') === 'SUPERADMIN'): ?>
                <a href="<?php echo site_url('transaksi/payroll/hapus/' . $row->id_periode); ?>" class="btn btn-xs btn-danger btn-confirm" data-msg="<?= ((string) $this->session->userdata('role') === 'SUPERADMIN' && $row->status !== 'DRAFT') ? 'Hapus permanen periode payroll ini beserta hasil hitungnya?' : 'Hapus periode draft ini?' ?>" title="Hapus"><i class="fa fa-trash"></i></a>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <?php else: ?>
        <div class="alert alert-info mb-0"><i class="fa fa-info-circle mr-1"></i> Belum ada periode payroll. Buat periode baru untuk mulai proses.</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</section>

<div class="modal fade" id="modalCreatePayroll" tabindex="-1" role="dialog" aria-labelledby="modalCreatePayrollLabel" 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="modalCreatePayrollLabel"><i class="fa fa-calendar mr-1"></i> Buat Periode Payroll</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <?php echo form_open('transaksi/payroll/simpan', ['id' => 'form-create-payroll']); ?>
      <div class="modal-body">
        <div class="row">
          <div class="col-sm-4">
            <div class="form-group">
              <label>Bulan <span class="text-danger">*</span></label>
              <select name="bulan" class="form-control" required>
                <?php for ($b = 1; $b <= 12; $b++): ?>
                <option value="<?php echo $b; ?>" <?php echo ((int) ($form_defaults['bulan'] ?? date('n')) === $b) ? 'selected' : ''; ?>>
                  <?php echo str_pad($b, 2, '0', STR_PAD_LEFT); ?>
                </option>
                <?php endfor; ?>
              </select>
            </div>
          </div>
          <div class="col-sm-4">
            <div class="form-group">
              <label>Tahun <span class="text-danger">*</span></label>
              <input type="number" name="tahun" class="form-control" min="2020" max="2100" value="<?php echo (int) ($form_defaults['tahun'] ?? date('Y')); ?>" required>
            </div>
          </div>
          <div class="col-sm-4">
            <div class="form-group">
              <label>Jenis Periode <span class="text-danger">*</span></label>
              <select name="tipe_periode" class="form-control" required>
                <option value="REGULER" <?php echo (($form_defaults['tipe_periode'] ?? 'REGULER') === 'REGULER') ? 'selected' : ''; ?>>Reguler</option>
                <option value="THR" <?php echo (($form_defaults['tipe_periode'] ?? 'REGULER') === 'THR') ? 'selected' : ''; ?>>THR</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-group mb-0">
          <label>Catatan</label>
          <textarea name="catatan" rows="3" class="form-control" placeholder="Catatan periode payroll (opsional)"><?php echo html_escape((string) ($form_defaults['catatan'] ?? '')); ?></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <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 Periode</button>
      </div>
      <?php echo form_close(); ?>
    </div>
  </div>
</div>

<script>
(function waitForJquery(){
  if (typeof jQuery === 'undefined') { setTimeout(waitForJquery, 50); return; }
  jQuery(function($){
    <?php if (!empty($list)): ?>
    $('#tbl-payroll').DataTable({
      pageLength: 25,
      order: [[1, 'desc']],
      language: {
        search: 'Cari:',
        lengthMenu: 'Show _MENU_ entries',
        info: 'Showing _START_ to _END_ of _TOTAL_ entries',
        paginate: {
          previous: 'Previous',
          next: 'Next'
        },
        zeroRecords: 'Tidak ada data',
        infoEmpty: 'Showing 0 to 0 of 0 entries',
        infoFiltered: '(filtered from _MAX_ total entries)'
      }
    });
    <?php endif; ?>

    $('.btn-confirm').click(function(e) {
      var msg = $(this).data('msg') || 'Lanjutkan proses ini?';
      if (!confirm(msg)) {
        e.preventDefault();
      }
    });

    $('#btn-open-create-payroll').on('click', function () {
      $('#modalCreatePayroll').modal('show');
    });

    <?php if (!empty($open_create_modal)): ?>
    $('#modalCreatePayroll').modal('show');
    <?php endif; ?>
  });
})();
</script>

<style>
  #modalProsesPayroll .modal-dialog { max-width: 980px; }
  #modalProsesPayroll .modal-header,
  #modalProsesPayroll .modal-footer {
    padding: 14px 18px;
  }
  #modalProsesPayroll .modal-body {
    padding: 18px;
    background: #fbfbfc;
  }
  #modalProsesPayroll .modal-section {
    background: #fff;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
  }
  #modalProsesPayroll .modal-section:last-child {
    margin-bottom: 0;
  }
  #modalProsesPayroll .section-title {
    font-size: 14px;
    font-weight: 700;
    color: #343a40;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
  #modalProsesPayroll .section-title i {
    margin-right: 8px;
    color: #dc3545;
  }
  #modalProsesPayroll .mode-option,
  #modalProsesPayroll .check-option {
    display: inline-flex;
    align-items: center;
    background: #fff;
    border: 1px solid #dfe3e8;
    border-radius: 999px;
    padding: 9px 14px;
    margin-right: 10px;
    margin-bottom: 10px;
    font-weight: 600;
    color: #495057;
    cursor: pointer;
  }
  #modalProsesPayroll .mode-option input,
  #modalProsesPayroll .check-option input {
    margin-right: 8px;
  }
  #modalProsesPayroll .employee-table-wrap {
    border: 1px solid #e9ecef;
    border-radius: 8px;
    overflow: hidden;
    background: #fff;
  }
  #modalProsesPayroll .table {
    margin-bottom: 0;
  }
  #modalProsesPayroll .table td,
  #modalProsesPayroll .table th {
    padding: 8px 10px;
    vertical-align: middle;
  }
  #modalProsesPayroll .dataTables_wrapper .dataTables_length,
  #modalProsesPayroll .dataTables_wrapper .dataTables_filter {
    margin-bottom: 10px;
  }
  #modalProsesPayroll .dataTables_wrapper .dataTables_filter input,
  #modalProsesPayroll .dataTables_wrapper .dataTables_length select {
    border-radius: 6px;
    border-color: #ced4da;
  }
  #modalProsesPayroll .modal-footer {
    background: #fff;
  }
</style>

<!-- Modal Proses Payroll -->
<div class="modal fade" id="modalProsesPayroll" tabindex="-1" role="dialog" aria-labelledby="modalProsesLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="modalProsesLabel"><i class="fa fa-play-circle mr-1"></i> Proses Payroll</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="modal-section">
          <div class="section-title"><i class="fa fa-sliders"></i> Pilih Mode Proses</div>
          <div>
            <label class="mode-option"><input type="radio" name="proses_mode" value="absensi" checked> Dengan Absensi</label>
            <label class="mode-option"><input type="radio" name="proses_mode" value="tanpa_absensi"> Tanpa Absensi (anggap hadir semua)</label>
          </div>
        </div>

        <div class="modal-section">
          <div class="section-title"><i class="fa fa-users"></i> Pilih Pegawai</div>
          <div class="mb-2">
            <label class="check-option"><input type="checkbox" id="chk_select_all"> Pilih Semua (halaman saat ini)</label>
            <label class="check-option"><input type="checkbox" id="chk_select_all_global"> Pilih Semua (semua hasil pencarian)</label>
          </div>
          <div class="employee-table-wrap">
                <table id="tbl-employees" class="table table-sm table-bordered table-striped" style="width:100%">
                  <thead>
                    <tr><th style="width:36px"></th><th>NIP</th><th>Nama</th><th>Divisi</th></tr>
                  </thead>
                  <tbody></tbody>
                </table>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
        <button type="button" id="btnProsesSubmit" class="btn btn-danger">Proses</button>
      </div>
    </div>
  </div>
</div>

<script>
(function waitForJqueryAndInit(){
  if (typeof jQuery === 'undefined') { setTimeout(waitForJqueryAndInit, 50); return; }
  $(function(){
    function getCookie(name) {
      var match = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)'));
      return match ? decodeURIComponent(match[1]) : null;
    }
    var baseUrl = '<?php echo site_url(''); ?>'.replace(/\/$/, '') + '/';
    var currentPeriodeId = null;
    var employeesTable = null;
    var selectedEmployees = {}; // map id => true (persist selection across pages)
    var selectAllGlobal = false;

    function initEmployeesTable(periodeId) {
      if ($.fn.DataTable.isDataTable('#tbl-employees')) {
        $('#tbl-employees').DataTable().destroy();
        $('#tbl-employees tbody').empty();
      }

      employeesTable = $('#tbl-employees').DataTable({
        serverSide: true,
        processing: true,
        pageLength: 10,
        ajax: {
          url: baseUrl + 'transaksi/payroll/ajax_employees/' + periodeId,
          type: 'POST',
          data: function(d){
            // Attach CSRF token from cookie so server-side CSRF validation passes
            d['<?= $this->security->get_csrf_token_name() ?>'] = getCookie('<?= $this->config->item('csrf_cookie_name') ?>');
          }
        },
        order: [[2, 'asc']],
        columns: [
          { data: 'id', orderable: false, searchable: false, render: function(data){
              var checked = selectedEmployees[data] ? 'checked' : '';
              return '<input type="checkbox" class="emp_chk" data-id="'+data+'" '+checked+'>';
            }
          },
          { data: 'nip' },
          { data: 'nama' },
          { data: 'divisi' }
        ],
        language: {
          search: 'Cari:',
          lengthMenu: 'Show _MENU_ entries',
          info: 'Showing _START_ to _END_ of _TOTAL_ entries',
          paginate: {
            previous: 'Previous',
            next: 'Next'
          },
          zeroRecords: 'Tidak ada data',
          infoEmpty: 'Showing 0 to 0 of 0 entries',
          infoFiltered: '(filtered from _MAX_ total entries)'
        },
        drawCallback: function(){
          // Restore checkbox states for visible rows
          $('#tbl-employees tbody').find('.emp_chk').each(function(){
            var id = $(this).data('id');
            $(this).prop('checked', !!selectedEmployees[id]);
          });
        }
      });
    }

    $(document).on('click', '.btn-open-proses', function(){
      currentPeriodeId = $(this).data('id');
      selectedEmployees = {}; // reset selection when open
      initEmployeesTable(currentPeriodeId);
      $('#chk_select_all').prop('checked', false);
      $('#modalProsesPayroll').modal('show');
    });

    // Toggle selection for individual checkbox
    $(document).on('change', '#tbl-employees .emp_chk', function(){
      var id = $(this).data('id');
      if ($(this).is(':checked')) selectedEmployees[id] = true; else delete selectedEmployees[id];
    });

    // Select all on current page
    $('#chk_select_all').on('change', function(){
      var checked = $(this).is(':checked');
      $('#tbl-employees tbody').find('.emp_chk').each(function(){
        $(this).prop('checked', checked).trigger('change');
      });
    });

    // Global select all across all pages (server-side)
    $('#chk_select_all_global').on('change', function(){
      selectAllGlobal = $(this).is(':checked');
      if (selectAllGlobal) {
        // disable page-local checkbox to avoid confusion
        $('#chk_select_all').prop('checked', false).prop('disabled', true);
      } else {
        $('#chk_select_all').prop('disabled', false);
      }
    });

    $('#btnProsesSubmit').on('click', function(){
      var mode = $('input[name="proses_mode"]:checked').val();
      var selected = Object.keys(selectedEmployees).map(function(k){ return parseInt(k); });

      // if none selected, treat as all
      if (selected.length === 0) {
        if (!confirm('Tidak ada pegawai dipilih. Lanjutkan proses untuk semua pegawai aktif?')) return;
      }

      Swal.fire({ title: 'Proses payroll', text: 'Sedang memproses payroll...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });

      var postData = { mode: mode, employees: selected };
      postData.select_all = selectAllGlobal ? 1 : 0;
      // include current search value so server can resolve matching ids when select_all used
      try { postData.search_value = (employeesTable && employeesTable.search) ? employeesTable.search() : ''; } catch(e) { postData.search_value = ''; }
      postData['<?= $this->security->get_csrf_token_name() ?>'] = getCookie('<?= $this->config->item('csrf_cookie_name') ?>');
      $.post(baseUrl + 'transaksi/payroll/proses_api/' + currentPeriodeId, postData, function(resp){
        try { var j = (typeof resp === 'string') ? JSON.parse(resp) : resp; }
        catch(e){ Swal.fire('Error','Response tidak valid','error'); return; }
        if (j.success) {
          Swal.fire('Berhasil', j.message + ' (' + (j.processed || 0) + ' pegawai)', 'success').then(function(){
            window.location.href = baseUrl + 'transaksi/payroll/detail/' + currentPeriodeId;
          });
        } else {
          Swal.fire('Gagal', j.message || 'Proses gagal', 'error');
        }
      }).fail(function(){
        Swal.fire('Error','Permintaan gagal dikirim ke server','error');
      });
    });
  });
})();
</script>
