<?= $this->extend('layouts/admin') ?>   <!-- sesuaikan layout kamu -->
<?= $this->section('content') ?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4>Menu Management</h4>
        <div>
            <button id="btnAdd" class="btn btn-primary">Add Menu</button>
            <button id="btnPerm" class="btn btn-secondary">Manage Permissions</button>
        </div>
    </div>

    <table id="dt_menus" class="table table-striped table-bordered w-100">
        <thead>
            <tr>
                <th>No</th>
                <th>Title</th>
                <th>URL</th>
                <th>Parent</th>
                <th>Icon</th>
                <th>Active</th>
                <th>Aksi</th>
            </tr>
        </thead>
    </table>
</div>

<!-- Modal Add/Edit -->
<div class="modal fade" id="modalForm">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <form id="formMenu">
      <div class="modal-header">
        <h5 class="modal-title">Menu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
          <input type="hidden" name="id" id="m_id">
          <div class="mb-3">
              <label>Title</label>
              <input class="form-control" name="title" id="m_title" required>
          </div>
          <div class="mb-3">
              <label>URL</label>
              <input class="form-control" name="url" id="m_url">
          </div>
          <div class="mb-3">
              <label>Parent</label>
              <select class="form-control" name="parent_id" id="m_parent">
                  <option value="0">-- None --</option>
                  <?php foreach (\Config\Database::connect()->table('menus')->where('parent_id',0)->get()->getResult() as $p): ?>
                      <option value="<?= $p->id ?>"><?= esc($p->title) ?></option>
                  <?php endforeach ?>
              </select>
          </div>
          <div class="mb-3">
              <label>Icon (Fontawesome)</label>
              <input class="form-control" name="icon" id="m_icon">
              <small class="text-muted">eg: fas fa-home or far fa-circle</small>
          </div>
          <div class="form-check">
              <input type="checkbox" class="form-check-input" id="m_active" name="is_active" checked>
              <label class="form-check-label" for="m_active">Active</label>
          </div>
          <div class="mb-3">
              <label>Sort Order</label>
              <input type="number" name="sort_order" id="m_sort" class="form-control" value="0">
          </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Close</button>
        <button class="btn btn-primary" type="submit">Save</button>
      </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Permissions -->
<div class="modal fade" id="modalPerm">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header"><h5>Manage Permissions</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="row mb-2">
            <div class="col-sm-4">
                <select id="selectRole" class="form-control"></select>
            </div>
        </div>

        <div id="permList">
            <!-- permission table will be loaded here -->
        </div>

      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Close</button>
        <button class="btn btn-success" id="savePerm">Save Permissions</button>
      </div>
    </div>
  </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<!-- DataTables, bootstrap JS must be included in layout -->
<script>
let dt;
$(function(){
    dt = $('#dt_menus').DataTable({
        processing:true,
        serverSide:true,
        ajax: { url: "<?= site_url('admin/menus/list') ?>", type: "POST" },
        columns:[
            { data: 'no' },
            { data: 'title' },
            { data: 'url' },
            { data: 'parent_id', render: (v)=> v==0 ? '-' : v },
            { data: 'icon', render: d=> d ? `<i class="${d}"></i> ${d}` : '' },
            { data: 'is_active', render: d=> d==1 ? 'Yes' : 'No' },
            { data: 'id', render: id => `
                <button class="btn btn-sm btn-info btn-edit" data-id="${id}">Edit</button>
                <button class="btn btn-sm btn-danger btn-del" data-id="${id}">Delete</button>
            `}
        ]
    });

    $('#btnAdd').on('click', ()=> {
        $('#formMenu')[0].reset();
        $('#m_id').val('');
        $('#modalForm').modal('show');
    });

    $(document).on('click','.btn-edit', function(){
        let id = $(this).data('id');
        $.post('<?= site_url('admin/menus/get') ?>/'+id, {}, function(res){
            $('#m_id').val(res.id);
            $('#m_title').val(res.title);
            $('#m_url').val(res.url);
            $('#m_icon').val(res.icon);
            $('#m_parent').val(res.parent_id);
            $('#m_sort').val(res.sort_order);
            $('#m_active').prop('checked', res.is_active==1);
            $('#modalForm').modal('show');
        }, 'json');
    });

    $('#formMenu').on('submit', function(e){
        e.preventDefault();
        let data = $(this).serialize();
        $.post('<?= site_url('admin/menus/store') ?>', data, function(res){
            dt.ajax.reload(null,false);
            $('#modalForm').modal('hide');
            alert(res.msg);
        }, 'json');
    });

    $(document).on('click','.btn-del', function(){
        if (!confirm('Delete this menu?')) return;
        let id = $(this).data('id');
        $.post('<?= site_url('admin/menus/delete') ?>/'+id, {}, function(res){
            dt.ajax.reload(null,false);
            alert(res.msg);
        }, 'json');
    });

    // Permissions
    $('#btnPerm').on('click', function(){
        $('#modalPerm').modal('show');
        loadRoles();
    });

    function loadRoles(){
        $.getJSON('<?= site_url('admin/menus/list') ?>', {}, function(){ /* not used */ });
        // load roles to select
        $.getJSON('<?= site_url('admin/menus') ?>', {}, function(){});
        // better: fetch roles via endpoint — we'll inline simple approach:
        $.get('<?= site_url('admin/menus') ?>', {}, function(){ /* noop */ });
        // For simplicity: fetch roles from server via small endpoint
        $.getJSON('<?= site_url('admin/menus') ?>', function(){});
    }

    // For brevity: simple approach — we will request roles via /admin/roles (create separate endpoint if needed)
    // Below: assume an endpoint /admin/roles/list returning [{id, name}]
    $.getJSON('<?= site_url('admin/roles/list') ?>', function(roles){
        let opt = '<option value="">-- pilih role --</option>';
        roles.forEach(r=> opt += `<option value="${r.id}">${r.name}</option>`);
        $('#selectRole').html(opt);
    });

    $('#selectRole').on('change', function(){
        let rid = $(this).val();
        if(!rid) return $('#permList').html('');
        // fetch menu + perms for role
        $.post('<?= site_url('admin/menus') ?>'+'/get-perms',{role_id:rid}, function(html){
            $('#permList').html(html);
        });
    });

    // save perms button
    $('#savePerm').on('click', function(){
        let role_id = $('#selectRole').val();
        if(!role_id) return alert('Choose role first');
        // collect perms
        let perms = {};
        $('#permTable tbody tr').each(function(){
            let mid = $(this).data('id');
            perms[mid] = {
                can_view: $(this).find('.p_view').is(':checked')?1:0,
                can_create: $(this).find('.p_create').is(':checked')?1:0,
                can_update: $(this).find('.p_update').is(':checked')?1:0,
                can_delete: $(this).find('.p_delete').is(':checked')?1:0,
            };
        });
        $.post('<?= site_url('admin/menus/save-perms') ?>', {role_id:role_id, perms: JSON.stringify(perms)}, function(res){
            alert(res.msg);
            $('#modalPerm').modal('hide');
        }, 'json');
    });

});
</script>
<?= $this->endSection() ?>
