<?php
$segment1 = $this->uri->segment(1);
$segment2 = $this->uri->segment(2);
$segment3 = $this->uri->segment(3);
$user_name = (string) $this->session->userdata('full_name');
$user_role = (string) $this->session->userdata('role');
$ai_enabled = (string) app_config('ai_enabled', '0') === '1';
$ai_api_key = trim((string) app_config('ai_api_key', ''));
$ai_connection_status = strtoupper(trim((string) app_config('ai_connection_status', 'DISCONNECTED')));
$show_ai_assistant = $ai_enabled && $ai_api_key !== '' && $ai_connection_status === 'CONNECTED';
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><?php echo isset($title) ? $title : (isset($page_title) ? $page_title . ' - ' . app_name() : app_name()); ?></title>
  <meta content="width=device-width, initial-scale=1" name="viewport">
  <?php if (app_favicon_url() !== ''): ?>
  <link rel="icon" type="image/x-icon" href="<?php echo app_favicon_url(); ?>">
  <?php endif; ?>

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+3:wght@400;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/overlayscrollbars/1.13.3/css/OverlayScrollbars.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.2.0/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.10.8/sweetalert2.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/payroll-red.css'); ?>">
</head>
<body class="hold-transition sidebar-mini layout-fixed layout-navbar-fixed">
<div class="wrapper">

  <nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fa fa-bars"></i></a>
      </li>
    </ul>

    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <span class="nav-link"><i class="fa fa-user mr-1"></i><?php echo html_escape($user_name); ?> (<?php echo html_escape($user_role); ?>)</span>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#" data-toggle="modal" data-target="#modalInfoPenggajian" title="Info Alur & Fitur">
          <i class="fa fa-info-circle"></i>
        </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="<?php echo site_url('logout'); ?>"><i class="fa fa-sign-out"></i></a>
      </li>
    </ul>
  </nav>

  <aside class="main-sidebar sidebar-dark-primary elevation-3">
    <a href="<?php echo site_url('dashboard'); ?>" class="brand-link text-center">
      <?php if (company_logo_url() !== ''): ?>
      <img src="<?php echo company_logo_url(); ?>" alt="Logo" style="max-height:28px;width:auto;margin-right:6px;">
      <?php endif; ?>
      <span class="brand-text font-weight-semibold"><?php echo strtoupper(app_name()); ?></span>
    </a>

    <div class="sidebar">
      <form action="#" method="get" class="sidebar-form form-inline mt-3">
        <div class="input-group w-100">
          <input type="text" class="form-control form-control-sidebar" placeholder="Cari menu..." id="txt_cari">
          <div class="input-group-append">
            <button type="submit" class="btn btn-sidebar">
              <i class="fa fa-search"></i>
            </button>
          </div>
        </div>
      </form>

      <nav class="mt-3 menu">
        <p class="nav-header">MENU UTAMA</p>
        <ul class="nav nav-pills nav-sidebar flex-column sidebar-menu mainlayer" data-widget="treeview" role="menu" data-accordion="false">
          <li class="nav-item">
            <a class="nav-link <?php echo ($segment1 === 'dashboard') ? 'active' : ''; ?>" href="<?php echo site_url('dashboard'); ?>">
              <i class="nav-icon fa fa-dashboard"></i>
              <p>DASHBOARD</p>
            </a>
          </li>
          <!--<li class="nav-item">
            <a class="nav-link" href="#">
              <i class="nav-icon fa fa-bell"></i>
              <p>Notifikasi Sistem <span class="right badge badge-danger">4</span></p>
            </a>
          </li>-->
        </ul>

        <p class="nav-header">MASTER DATA</p>
        <?php $master_open = ($segment1 === 'master'); ?>
        <ul class="nav nav-pills nav-sidebar flex-column sidebar-menu mainlayer" data-widget="treeview" role="menu" data-accordion="false">
          <?php $org_open = ($segment1 === 'master' && in_array($segment2, ['divisi','jabatan'])); ?>
          <li class="nav-item has-treeview <?php echo $org_open ? 'menu-open' : ''; ?>">
            <a href="#" class="nav-link <?php echo $org_open ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-sitemap"></i>
              <p>
                MANAJEMEN ORGANISASI
                <i class="right fa fa-angle-left"></i>
              </p>
            </a>
            <ul class="nav nav-treeview">
              <li class="nav-item">
                <a href="<?php echo site_url('master/divisi'); ?>"
                   class="nav-link <?php echo ($segment2 === 'divisi') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Data Divisi</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="<?php echo site_url('master/jabatan'); ?>"
                   class="nav-link <?php echo ($segment2 === 'jabatan') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Data Jabatan</p>
                </a>
              </li>
            </ul>
          </li>

          <?php $peg_open = ($segment1 === 'master' && in_array($segment2, ['pegawai', 'import_pegawai', 'shift'])); ?>
          <li class="nav-item has-treeview <?php echo $peg_open ? 'menu-open' : ''; ?>">
            <a href="#" class="nav-link <?php echo $peg_open ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-users"></i>
              <p>
                MANAJEMEN PEGAWAI
                <i class="right fa fa-angle-left"></i>
              </p>
            </a>
            <ul class="nav nav-treeview">
              <li class="nav-item">
                <a href="<?php echo site_url('master/pegawai'); ?>"
                   class="nav-link <?php echo ($segment1 === 'master' && ($segment2 === 'pegawai' || $segment2 === 'import_pegawai') && !in_array($segment3, ['riwayat'])) ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Data Pegawai</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="<?php echo site_url('master/shift'); ?>"
                   class="nav-link <?php echo ($segment2==='shift' && $segment3 !== 'assignment') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Master Shift</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="<?php echo site_url('master/shift/assignment'); ?>"
                   class="nav-link <?php echo ($segment2==='shift' && $segment3 === 'assignment') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Jadwal Kerja</p>
                </a>
              </li>
            </ul>
          </li>

          <?php $param_open = ($segment1==='master' && in_array($segment2,['komponen','harlibur','mapping_komponen'])); ?>
          <li class="nav-item has-treeview <?php echo $param_open ? 'menu-open' : ''; ?>">
            <a href="#" class="nav-link <?php echo $param_open ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-cogs"></i>
              <p>PARAMETER PENGGAJIAN<i class="right fa fa-angle-left"></i></p>
            </a>
            <ul class="nav nav-treeview">
              <li class="nav-item">
                <a href="<?php echo site_url('master/komponen'); ?>"
                   class="nav-link <?php echo ($segment2==='komponen') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Komponen Gaji</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="<?php echo site_url('master/harlibur'); ?>"
                   class="nav-link <?php echo ($segment2==='harlibur') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Hari Libur & Kalender</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="<?php echo site_url('master/mapping_komponen'); ?>"
                   class="nav-link <?php echo ($segment2==='mapping_komponen') ? 'active' : ''; ?>">
                  <i class="fa fa-circle-o nav-icon"></i><p>Mapping Gaji</p>
                </a>
              </li>
            </ul>
          </li>
        </ul>

        <p class="nav-header">MENU TRANSAKSIONAL</p>
        <ul class="nav nav-pills nav-sidebar flex-column sidebar-menu mainlayer" data-widget="treeview" role="menu" data-accordion="false">
          <li class="nav-item">
            <a href="<?php echo site_url('transaksi/absensi'); ?>" class="nav-link <?php echo ($segment1 === 'transaksi' && $segment2 === 'absensi') ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-calendar"></i>
              <p>MANAJEMEN ABSENSI</p>
            </a>
          </li>

          <li class="nav-item">
            <a href="<?php echo site_url('transaksi/izin_cuti'); ?>" class="nav-link <?php echo ($segment1 === 'transaksi' && $segment2 === 'izin_cuti') ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-file-text-o"></i>
              <p>MANAJEMEN IZIN</p>
            </a>
          </li>

          <li class="nav-item">
            <a href="<?php echo site_url('transaksi/lembur'); ?>" class="nav-link <?php echo ($segment1 === 'transaksi' && $segment2 === 'lembur') ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-clock-o"></i>
              <p>MANAJEMEN LEMBUR</p>
            </a>
          </li>

          <li class="nav-item">
            <a href="<?php echo site_url('transaksi/payroll'); ?>" class="nav-link <?php echo ($segment1 === 'transaksi' && $segment2 === 'payroll') ? 'active' : ''; ?>">
              <i class="nav-icon fa fa-calculator"></i>
              <p>SISTEM PAYROLL</p>
            </a>
          </li>
        </ul>

        <p class="nav-header">OUTPUT & LAPORAN</p>
        <ul class="nav nav-pills nav-sidebar flex-column sidebar-menu mainlayer" data-widget="treeview" role="menu" data-accordion="false">
          <li class="nav-item"><a href="<?php echo site_url('output/laporan'); ?>" class="nav-link <?php echo ($segment1 === 'output' && in_array($segment2, ['laporan', 'slip_gaji'], TRUE)) ? 'active' : ''; ?>"><i class="nav-icon fa fa-bar-chart"></i><p>PUSAT LAPORAN</p></a></li>
        </ul>

        <p class="nav-header">PENGATURAN</p>
        <ul class="nav nav-pills nav-sidebar flex-column sidebar-menu mainlayer" data-widget="treeview" role="menu" data-accordion="false">
          <?php if ($this->session->userdata('role') === 'SUPERADMIN'): ?>
          <li class="nav-item"><a href="<?php echo site_url('pengaturan/pengguna'); ?>" class="nav-link <?php echo ($segment1 === 'pengaturan' && $segment2 === 'pengguna') ? 'active' : ''; ?>"><i class="nav-icon fa fa-user-secret"></i><p>MANAJEMEN PENGGUNA</p></a></li>
          <?php endif; ?>
          <li class="nav-item"><a href="<?php echo site_url('master/konfigurasi'); ?>" class="nav-link <?php echo ($segment1 === 'master' && $segment2 === 'konfigurasi' && $segment3 !== 'bpjs') ? 'active' : ''; ?>"><i class="nav-icon fa fa-cog"></i><p>KONFIGURASI SISTEM</p></a></li>
        </ul>
      </nav>
    </div>
  </aside>

  <div class="content-wrapper">
    <?php echo $content; ?>
  </div>

  <footer class="main-footer">
    <strong>Copyright &copy; <?php echo date('Y'); ?> <?php echo app_name(); ?></strong>
  </footer>
</div>

<?php if ($show_ai_assistant): ?>
<button type="button" class="ai-assistant-fab" id="aiAssistantToggle" title="AI Asisten Admin">
  <i class="fa fa-comments"></i>
</button>

<div class="ai-chatbox-panel is-hidden" id="aiAssistantPanel" aria-hidden="true">
  <div class="ai-chatbox-header">
    <h5 class="ai-chatbox-title"><i class="fa fa-comments-o mr-2"></i>AI Asisten Admin</h5>
    <div class="ai-chatbox-actions">
      <button type="button" class="ai-chatbox-btn" id="aiAssistantClose" title="Tutup">
        <i class="fa fa-times"></i>
      </button>
    </div>
  </div>
  <div class="ai-chatbox-body">
    <div class="ai-chat-shell">
      <div class="ai-session-toolbar p-2 border-bottom">
        <div class="input-group input-group-sm">
          <div class="input-group-prepend">
            <span class="input-group-text bg-white"><i class="fa fa-folder-open-o"></i></span>
          </div>
          <select class="form-control" id="aiSessionSelect"></select>
          <div class="input-group-append">
            <button type="button" class="btn btn-outline-secondary" id="aiSessionNew" title="Sesi baru">
              <i class="fa fa-plus"></i>
            </button>
            <button type="button" class="btn btn-outline-secondary" id="aiSessionDelete" title="Hapus sesi aktif">
              <i class="fa fa-trash"></i>
            </button>
          </div>
        </div>
      </div>

      <div class="ai-chat-messages p-3" id="aiChatMessages">
      </div>
      <div class="ai-history-toolbar px-3 py-2 border-top" id="aiHistoryToolbar" style="display:none;">
        <button type="button" class="btn btn-sm btn-outline-secondary btn-block" id="aiLoadOlderMessages">Muat Riwayat Sebelumnya</button>
      </div>

      <div class="ai-chat-input p-3 border-top">
        <div class="input-group">
          <input type="text" class="form-control" id="aiChatInput" placeholder="Ketik pertanyaan untuk AI Asisten...">
          <div class="input-group-append">
            <button type="button" class="btn btn-danger" id="btnSendAiPrompt">
              <i class="fa fa-paper-plane"></i>
            </button>
          </div>
        </div>
      </div>

      <div class="ai-quick-actions p-2 border-top">
        <button type="button" class="btn btn-outline-danger ai-quick-btn" data-prompt="Cek status payroll periode aktif">Status Payroll Aktif</button>
        <button type="button" class="btn btn-outline-danger ai-quick-btn" data-prompt="Tampilkan pending approval izin/cuti">Pending Izin/Cuti</button>
        <button type="button" class="btn btn-outline-danger ai-quick-btn" data-prompt="Tampilkan pending approval lembur">Pending Lembur</button>
        <button type="button" class="btn btn-outline-danger ai-quick-btn" data-prompt="Ringkasan absensi periode berjalan">Ringkasan Absensi</button>
        <button type="button" class="btn btn-outline-danger ai-quick-btn" data-prompt="Cek data pegawai belum lengkap">Data Pegawai Belum Lengkap</button>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="modal fade" id="modalInfoPenggajian" tabindex="-1" role="dialog" aria-labelledby="modalInfoPenggajianLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="modalInfoPenggajianLabel"><i class="fa fa-info-circle mr-2"></i>Info Alur & Fitur Penggajian</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 p-2 p-md-3">
        <div id="carouselInfoPenggajian" class="carousel slide" data-ride="carousel" data-interval="false">
          <ol class="carousel-indicators">
            <li data-target="#carouselInfoPenggajian" data-slide-to="0" class="active"></li>
            <li data-target="#carouselInfoPenggajian" data-slide-to="1"></li>
          </ol>
          <div class="carousel-inner rounded bg-light" style="min-height: 360px;">
            <div class="carousel-item active text-center py-3">
              <img src="<?php echo base_url('assets/penggajian-alur.jpg'); ?>" class="img-fluid" alt="Alur Penggajian" style="max-height: 70vh; object-fit: contain;">
            </div>
            <div class="carousel-item text-center py-3">
              <img src="<?php echo base_url('assets/penggajian-fitur.jpg'); ?>" class="img-fluid" alt="Fitur Penggajian" style="max-height: 70vh; object-fit: contain;">
            </div>
          </div>
          <a class="carousel-control-prev" href="#carouselInfoPenggajian" role="button" data-slide="prev">
            <span class="carousel-control-prev-icon bg-dark rounded-circle p-3" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
          </a>
          <a class="carousel-control-next" href="#carouselInfoPenggajian" role="button" data-slide="next">
            <span class="carousel-control-next-icon bg-dark rounded-circle p-3" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalAiImagePreview" tabindex="-1" role="dialog" aria-labelledby="modalAiImagePreviewLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="modalAiImagePreviewLabel"><i class="fa fa-image mr-2"></i>Preview Gambar</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 text-center p-3 p-md-4 bg-light">
        <img src="" class="img-fluid ai-preview-modal-image" id="aiPreviewModalImage" alt="Preview Gambar AI" style="max-height: 75vh; object-fit: contain;">
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/overlayscrollbars/1.13.3/js/jquery.overlayScrollbars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.2.0/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.10.8/sweetalert2.all.min.js"></script>
<script>
$(document).ready(function () {
  // Flash success
  <?php $flash_success = $this->session->flashdata('success'); ?>
  <?php
    $success_title = 'Berhasil';
    $success_text = '';
    $success_redirect = '';
    if (is_array($flash_success)) {
      $success_title = $flash_success['title'] ?? 'Berhasil';
      $success_text = $flash_success['text'] ?? '';
      $success_redirect = $flash_success['redirect'] ?? '';
    } elseif (is_string($flash_success)) {
      $success_text = $flash_success;
    }
  ?>
  <?php if (!empty($flash_success)): ?>
  Swal.fire({
    icon: 'success',
    title: '<?php echo addslashes($success_title); ?>',
    html: '<?php echo addslashes($success_text); ?>',
    confirmButtonColor: '#800000'
  })<?php if (!empty($success_redirect)): ?>.then(function(){
    window.location.href = '<?php echo site_url($success_redirect); ?>';
  })<?php endif; ?>;
  <?php endif; ?>

  // Flash error
  <?php $flash_error = $this->session->flashdata('error'); ?>
  <?php
    $error_title = 'Gagal';
    $error_text = '';
    $error_redirect = '';
    if (is_array($flash_error)) {
      $error_title = $flash_error['title'] ?? 'Gagal';
      $error_text = $flash_error['text'] ?? '';
      $error_redirect = $flash_error['redirect'] ?? '';
    } elseif (is_string($flash_error)) {
      $error_text = $flash_error;
    }
  ?>
  <?php if (!empty($flash_error)): ?>
  Swal.fire({
    icon: 'error',
    title: '<?php echo addslashes($error_title); ?>',
    html: '<?php echo addslashes($error_text); ?>',
    confirmButtonColor: '#800000'
  })<?php if (!empty($error_redirect)): ?>.then(function(){
    window.location.href = '<?php echo site_url($error_redirect); ?>';
  })<?php endif; ?>;
  <?php endif; ?>

  // Sidebar search
  $('#txt_cari').on('keyup', function () {
    var filter = $(this).val();
    $('.menu ul > li').removeClass('hide show');
    $('.menu ul > li').each(function () {
      if ($(this).text().search(new RegExp(filter, 'i')) < 0 && !$(this).hasClass('show')) {
        $(this).addClass('hide');
      } else {
        $(this).addClass('show');
        $(this).find('ul > li').addClass('show');
      }
    });
  });

  // Use custom tree toggle to avoid conflict with AdminLTE treeview data-api.
  $('.sidebar .nav-sidebar[data-widget="treeview"]').removeAttr('data-widget');

  function setTreeItemState($item, shouldOpen, animate) {
    var $submenu = $item.children('.nav-treeview');
    if (!$submenu.length) return;

    if (shouldOpen) {
      $item.addClass('menu-open');
      if (animate) {
        $submenu.stop(true, true).slideDown(180);
      } else {
        $submenu.show();
      }
      return;
    }

    $item.removeClass('menu-open');
    if (animate) {
      $submenu.stop(true, true).slideUp(160);
    } else {
      $submenu.hide();
    }
  }

  function syncTreeByActiveState(animate) {
    var isCollapsed = $('body').hasClass('sidebar-collapse') && !$('body').hasClass('sidebar-open');

    $('.sidebar .nav-item.has-treeview').each(function () {
      var $item = $(this);
      var hasActiveChild = $item.find('> .nav-treeview .nav-link.active').length > 0;
      var keepOpen = $item.attr('data-open-before-collapse') === '1';
      var shouldOpen = !isCollapsed && (keepOpen || hasActiveChild);
      setTreeItemState($item, shouldOpen, animate);
    });
  }

  // Initial sync so active branches are opened correctly.
  syncTreeByActiveState(false);

  // Stable custom open/close animation for tree menu items.
  $('.sidebar .nav-item.has-treeview > .nav-link').off('click.treeCustom').on('click.treeCustom', function (e) {
    var isCollapsed = $('body').hasClass('sidebar-collapse') && !$('body').hasClass('sidebar-open');
    if (isCollapsed) {
      return;
    }

    var $link = $(this);
    var $item = $link.closest('.nav-item.has-treeview');
    var $submenu = $item.children('.nav-treeview');
    if (!$submenu.length) {
      return;
    }

    e.preventDefault();
    e.stopImmediatePropagation();

    var isOpen = $item.hasClass('menu-open');
    setTreeItemState($item, !isOpen, true);
    $item.attr('data-open-before-collapse', !isOpen ? '1' : '0');
  });

  // Save and restore opened branches when sidebar collapse state changes.
  $(document).on('collapsed.lte.pushmenu', function () {
    $('.sidebar .nav-item.has-treeview').each(function () {
      var $item = $(this);
      var wasOpen = $item.hasClass('menu-open') ? '1' : '0';
      $item.attr('data-open-before-collapse', wasOpen);
      setTreeItemState($item, false, false);
    });
  });

  $(document).on('shown.lte.pushmenu', function () {
    syncTreeByActiveState(true);
  });

  $('#modalInfoPenggajian').on('shown.bs.modal', function () {
    $('#carouselInfoPenggajian').carousel(0);
  });

  var aiApi = {
    sessions: '<?php echo site_url('ai/chat/sessions'); ?>',
    messagesBase: '<?php echo site_url('ai/chat/messages'); ?>',
    deleteBase: '<?php echo site_url('ai/chat/session/delete'); ?>',
    send: '<?php echo site_url('ai/chat/send'); ?>'
  };
  var aiCsrfTokenName = '<?php echo $this->config->item('csrf_token_name'); ?>';
  var aiCsrfCookieName = '<?php echo $this->config->item('csrf_cookie_name') ?: $this->config->item('csrf_token_name'); ?>';
  var aiBusy = false;
  window.__aiSessions = [];
  window.__aiActiveSessionId = null;
  window.__aiMessages = [];
  window.__aiPagination = {
    page: 1,
    perPage: 30,
    hasMore: false,
    total: 0
  };

  function getCookieValue(cookieName) {
    var escaped = cookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : '';
  }

  function buildCsrfPayload() {
    var tokenValue = getCookieValue(aiCsrfCookieName);
    if (!tokenValue || !aiCsrfTokenName) {
      return {};
    }

    var payload = {};
    payload[aiCsrfTokenName] = tokenValue;
    return payload;
  }

  function postAi(url, data) {
    return $.ajax({
      url: url,
      method: 'POST',
      dataType: 'json',
      data: $.extend({}, data || {}, buildCsrfPayload())
    });
  }

  function getAi(url) {
    return $.ajax({
      url: url,
      method: 'GET',
      dataType: 'json'
    });
  }

  function setAiBusy(isBusy) {
    aiBusy = !!isBusy;
    $('#btnSendAiPrompt').prop('disabled', aiBusy);
    $('#aiChatInput').prop('disabled', aiBusy);
    $('#aiSessionNew').prop('disabled', aiBusy);
    $('#aiSessionDelete').prop('disabled', aiBusy);
    $('#aiSessionSelect').prop('disabled', aiBusy);
  }

  function syncLoadOlderButton(isLoading) {
    var $toolbar = $('#aiHistoryToolbar');
    var $btn = $('#aiLoadOlderMessages');
    if (!$toolbar.length || !$btn.length) {
      return;
    }

    var hasMore = !!(window.__aiPagination && window.__aiPagination.hasMore);
    $toolbar.toggle(hasMore);
    $btn.prop('disabled', !!isLoading);
    $btn.text(isLoading ? 'Memuat...' : 'Muat Riwayat Sebelumnya');
  }

  function appendAiMessageLocal(text, role) {
    window.__aiMessages = window.__aiMessages || [];
    window.__aiMessages.push({
      role: role === 'user' ? 'user' : 'assistant',
      text: (text || '').toString(),
      images: []
    });
    renderAiMessages();
  }

  function escapeHtml(value) {
    return $('<div>').text((value || '').toString()).html();
  }

  function formatAiMessageText(value) {
    var safeText = escapeHtml(value);
    return safeText.replace(/\n/g, '<br>');
  }

  function buildAiImageGallery(images) {
    var list = images || [];
    if (!list.length) {
      return '';
    }

    var html = '<div class="ai-msg-gallery">';
    list.forEach(function (img) {
      var url = (img && img.url) ? img.url.toString() : '';
      var title = (img && img.title) ? img.title.toString() : 'Gambar';
      if (!url) {
        return;
      }
      html += ''
        + '<button type="button" class="ai-image-card" data-image-url="' + escapeHtml(url) + '" data-image-title="' + escapeHtml(title) + '">'
        + '  <img src="' + escapeHtml(url) + '" alt="' + escapeHtml(title) + '" class="ai-image-thumb">'
        + '  <span class="ai-image-label">' + escapeHtml(title) + '</span>'
        + '</button>';
    });
    html += '</div>';

    return html;
  }

  function renderAiSessionOptions() {
    var $select = $('#aiSessionSelect');
    if (!$select.length) {
      return;
    }

    $select.empty();
    (window.__aiSessions || []).forEach(function (session) {
      var label = session.title;
      if (session.id === window.__aiActiveSessionId) {
        label += ' (aktif)';
      }
      $select.append($('<option>', { value: session.id, text: label }));
    });
    $select.val(window.__aiActiveSessionId);
  }

  function renderAiMessages(keepBottom) {
    var $box = $('#aiChatMessages');
    if (!$box.length) {
      return;
    }

    $box.empty();
    var messages = window.__aiMessages || [];
    if (!messages.length) {
      $box.append('<div class="ai-msg ai-msg-bot"><div class="ai-msg-bubble">Belum ada pesan pada sesi ini.</div></div>');
      return;
    }

    messages.forEach(function (msg) {
      var isUser = msg.role === 'user';
      var cssClass = isUser ? 'ai-msg-user' : 'ai-msg-bot';
      var bodyText = formatAiMessageText(msg.text || '');
      var imageGallery = isUser ? '' : buildAiImageGallery(msg.images || []);
      var html = ''
        + '<div class="ai-msg ' + cssClass + '">'
        + '  <div class="ai-msg-bubble">'
        + '    <div class="ai-msg-text">' + bodyText + '</div>'
        +       imageGallery
        + '  </div>'
        + '</div>';
      $box.append(html);
    });

    if (keepBottom !== false) {
      $box.scrollTop($box[0].scrollHeight);
    }
  }

  function normalizeAiMessages(rawMessages) {
    return (rawMessages || []).map(function (msg) {
      return {
        role: msg.role === 'user' ? 'user' : 'assistant',
        text: (msg.text || '').toString(),
        images: $.isArray(msg.images) ? msg.images : []
      };
    });
  }

  function loadAiMessages(sessionId, page, prependOlder) {
    var targetPage = parseInt(page, 10) || 1;
    var prepend = prependOlder === true;

    if (!sessionId) {
      window.__aiMessages = [];
      window.__aiPagination = {
        page: 1,
        perPage: window.__aiPagination && window.__aiPagination.perPage ? window.__aiPagination.perPage : 30,
        hasMore: false,
        total: 0
      };
      renderAiMessages();
      syncLoadOlderButton(false);
      return $.Deferred().resolve().promise();
    }

    syncLoadOlderButton(prepend);

    return getAi(aiApi.messagesBase + '/' + encodeURIComponent(sessionId) + '?page=' + targetPage + '&per_page=' + (window.__aiPagination.perPage || 30))
      .done(function (resp) {
        if (!resp || !resp.success) {
          window.__aiMessages = [{
            role: 'assistant',
            text: (resp && resp.message) ? resp.message : 'Gagal memuat pesan.'
          }];
          window.__aiPagination.hasMore = false;
        } else {
          var pagination = resp.pagination || {};
          window.__aiPagination.page = parseInt(pagination.page, 10) || targetPage;
          window.__aiPagination.perPage = parseInt(pagination.per_page, 10) || window.__aiPagination.perPage || 30;
          window.__aiPagination.total = parseInt(pagination.total, 10) || 0;
          window.__aiPagination.hasMore = !!pagination.has_more;

          var incoming = normalizeAiMessages(resp.messages || []);
          if (prepend) {
            var $box = $('#aiChatMessages');
            var prevHeight = $box.length ? $box[0].scrollHeight : 0;
            window.__aiMessages = incoming.concat(window.__aiMessages || []);
            renderAiMessages(false);
            if ($box.length) {
              var nextHeight = $box[0].scrollHeight;
              $box.scrollTop(nextHeight - prevHeight);
            }
          } else {
            window.__aiMessages = incoming;
            renderAiMessages(true);
          }
        }
        syncLoadOlderButton(false);
      })
      .fail(function (xhr) {
        var msg = 'Gagal memuat pesan dari server.';
        if (xhr && xhr.responseJSON && xhr.responseJSON.message) {
          msg = xhr.responseJSON.message;
        }
        if (prepend) {
          Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: msg,
            confirmButtonColor: '#800000'
          });
        } else {
          window.__aiMessages = [{ role: 'assistant', text: msg }];
          renderAiMessages();
        }
        syncLoadOlderButton(false);
      });
  }

  function loadAiSessions(ensureSession) {
    return getAi(aiApi.sessions)
      .done(function (resp) {
        if (!resp || !resp.success) {
          window.__aiSessions = [];
        } else {
          window.__aiSessions = (resp.sessions || []).map(function (s) {
            return {
              id: parseInt(s.id, 10),
              title: (s.title || '').toString()
            };
          });
        }

        if (ensureSession && window.__aiSessions.length === 0) {
          postAi(aiApi.sessions, { title: '' }).done(function () {
            loadAiSessions(false);
          }).fail(function () {
            window.__aiMessages = [{
              role: 'assistant',
              text: 'Gagal membuat sesi baru. Coba lagi.'
            }];
            renderAiMessages();
          });
          return;
        }

        var foundActive = false;
        for (var i = 0; i < window.__aiSessions.length; i++) {
          if (window.__aiSessions[i].id === window.__aiActiveSessionId) {
            foundActive = true;
            break;
          }
        }
        if (!foundActive) {
          window.__aiActiveSessionId = window.__aiSessions.length ? window.__aiSessions[0].id : null;
        }

        renderAiSessionOptions();
        window.__aiPagination.page = 1;
        window.__aiPagination.hasMore = false;
        loadAiMessages(window.__aiActiveSessionId, 1, false);
      })
      .fail(function () {
        window.__aiMessages = [{
          role: 'assistant',
          text: 'Gagal memuat sesi chat dari server.'
        }];
        renderAiMessages();
      });
  }

  function initAiSessions() {
    if (!$('#aiAssistantPanel').length) {
      return;
    }

    loadAiSessions(true);
  }

  function sendAiPrompt() {
    var $input = $('#aiChatInput');
    if (!$input.length) {
      return;
    }

    var prompt = ($input.val() || '').trim();
    if (!prompt || !window.__aiActiveSessionId || aiBusy) {
      return;
    }

    appendAiMessageLocal(prompt, 'user');
    $input.val('');

    setAiBusy(true);
    postAi(aiApi.send, {
      id_session: window.__aiActiveSessionId,
      prompt: prompt
    }).done(function (resp) {
      var assistantMessage = (resp && resp.message) ? resp.message : null;
      if (assistantMessage && (assistantMessage.text || assistantMessage.images)) {
        window.__aiMessages = window.__aiMessages || [];
        window.__aiMessages.push({
          role: 'assistant',
          text: (assistantMessage.text || '').toString(),
          images: $.isArray(assistantMessage.images) ? assistantMessage.images : []
        });
        renderAiMessages();
      } else {
        var reply = (resp && resp.reply) ? resp.reply : 'AI tidak mengembalikan jawaban.';
        appendAiMessageLocal(reply, 'assistant');
      }
      window.__aiPagination.page = 1;
      loadAiSessions(false);
    }).fail(function (xhr) {
      var message = 'Gagal mengirim pertanyaan ke AI.';
      if (xhr && xhr.responseJSON && xhr.responseJSON.message) {
        message = xhr.responseJSON.message;
      }
      appendAiMessageLocal(message, 'assistant');
    }).always(function () {
      setAiBusy(false);
      $('#aiChatInput').trigger('focus');
    });
  }

  $('#aiSessionSelect').on('change', function () {
    window.__aiActiveSessionId = parseInt($(this).val(), 10) || null;
    window.__aiPagination.page = 1;
    window.__aiPagination.hasMore = false;
    renderAiSessionOptions();
    loadAiMessages(window.__aiActiveSessionId, 1, false);
  });

  $('#aiSessionNew').on('click', function () {
    if (aiBusy) {
      return;
    }

    setAiBusy(true);
    postAi(aiApi.sessions, { title: '' }).done(function (resp) {
      if (resp && resp.success && resp.session && resp.session.id) {
        window.__aiActiveSessionId = parseInt(resp.session.id, 10);
        loadAiSessions(false);
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Gagal',
          text: 'Sesi baru gagal dibuat.',
          confirmButtonColor: '#800000'
        });
      }
    }).fail(function (xhr) {
      Swal.fire({
        icon: 'error',
        title: 'Gagal',
        text: (xhr && xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Sesi baru gagal dibuat.',
        confirmButtonColor: '#800000'
      });
    }).always(function () {
      setAiBusy(false);
    });
  });

  $('#aiSessionDelete').on('click', function () {
    if (aiBusy || !window.__aiActiveSessionId) {
      return;
    }

    var idToDelete = window.__aiActiveSessionId;
    Swal.fire({
      icon: 'warning',
      title: 'Hapus sesi?',
      text: 'Riwayat chat pada sesi ini akan dihapus permanen.',
      showCancelButton: true,
      confirmButtonText: 'Ya, hapus',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#800000'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }

      setAiBusy(true);
      postAi(aiApi.deleteBase + '/' + encodeURIComponent(idToDelete), {}).done(function (resp) {
        if (resp && resp.success) {
          window.__aiActiveSessionId = null;
          loadAiSessions(true);
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: (resp && resp.message) ? resp.message : 'Sesi gagal dihapus.',
            confirmButtonColor: '#800000'
          });
        }
      }).fail(function (xhr) {
        Swal.fire({
          icon: 'error',
          title: 'Gagal',
          text: (xhr && xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Sesi gagal dihapus.',
          confirmButtonColor: '#800000'
        });
      }).always(function () {
        setAiBusy(false);
      });
    });
  });

  $('.ai-quick-btn').on('click', function () {
    var prompt = ($(this).data('prompt') || '').toString();
    $('#aiChatInput').val(prompt).trigger('focus');
  });

  $('#aiLoadOlderMessages').on('click', function () {
    if (aiBusy || !window.__aiActiveSessionId || !window.__aiPagination.hasMore) {
      return;
    }

    var nextPage = (window.__aiPagination.page || 1) + 1;
    loadAiMessages(window.__aiActiveSessionId, nextPage, true);
  });

  $(document).on('click', '.ai-image-card', function () {
    var imageUrl = ($(this).data('image-url') || '').toString();
    var imageTitle = ($(this).data('image-title') || 'Preview Gambar').toString();
    if (!imageUrl) {
      return;
    }

    $('#aiPreviewModalImage').attr('src', imageUrl).attr('alt', imageTitle);
    $('#modalAiImagePreviewLabel').html('<i class="fa fa-image mr-2"></i>' + escapeHtml(imageTitle));
    $('#modalAiImagePreview').modal('show');
  });

  function openAiPanel() {
    var $panel = $('#aiAssistantPanel');
    if (!$panel.length) {
      return;
    }

    $panel.removeClass('is-hidden').attr('aria-hidden', 'false');
    $('#aiChatInput').trigger('focus');
  }

  function closeAiPanel() {
    var $panel = $('#aiAssistantPanel');
    if (!$panel.length) {
      return;
    }

    $panel.addClass('is-hidden').attr('aria-hidden', 'true');
  }

  $('#aiAssistantToggle').on('click', function () {
    var $panel = $('#aiAssistantPanel');
    if (!$panel.length) {
      return;
    }

    if ($panel.hasClass('is-hidden')) {
      openAiPanel();
      initAiSessions();
      return;
    }

    closeAiPanel();
  });

  $('#aiAssistantClose').on('click', closeAiPanel);

  $('#btnSendAiPrompt').on('click', sendAiPrompt);
  $('#aiChatInput').on('keydown', function (e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      sendAiPrompt();
    }
  });

  initAiSessions();
});
</script>
</body>
</html>
