<?php
$role = isset($role) ? $role : null;
$modules_grouped = isset($modules_grouped) ? $modules_grouped : array();
$perm_map = isset($perm_map) ? $perm_map : array();
$page_title = isset($page_title) ? $page_title : 'Permissions';
$is_super = !empty($role->is_superadmin);
?>
<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2 align-items-center">
        <div class="col-sm-8">
          <h1><?php echo htmlspecialchars($page_title); ?></h1>
          <p class="report-lead">
            Tick <strong>View</strong> to open a report. Tick <strong>Export</strong> for PDF / Excel / Word.
            Export automatically includes view.
          </p>
        </div>
        <div class="col-sm-4 text-sm-right">
          <a href="<?php echo base_url('index.php/permissions'); ?>" class="btn btn-outline-secondary btn-sm">&larr; Roles</a>
        </div>
      </div>
    </div>
  </section>
  <section class="content">
    <div class="container-fluid">
      <?php if (!empty($flash_success)) { ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($flash_success); ?></div>
      <?php } ?>
      <?php if ($is_super) { ?>
        <div class="alert alert-info">Super Admin always has full view &amp; export on every module. Saving refreshes the grant.</div>
      <?php } ?>

      <form method="post" action="<?php echo base_url('index.php/permissions/save/' . (int) $role->id); ?>" id="permForm">
        <div class="mb-3 d-flex flex-wrap align-items-center" style="gap:.5rem">
          <button type="button" class="btn btn-outline-secondary btn-sm" id="checkAllView">Check all View</button>
          <button type="button" class="btn btn-outline-secondary btn-sm" id="checkAllExport">Check all Export</button>
          <button type="button" class="btn btn-outline-secondary btn-sm" id="uncheckAll">Clear all</button>
          <button type="submit" class="btn btn-primary btn-sm ml-auto" <?php echo $is_super ? '' : ''; ?>>
            <i class="fas fa-save mr-1"></i> Save permissions
          </button>
        </div>

        <?php foreach ($modules_grouped as $group => $modules) { ?>
          <div class="report-card card mb-3">
            <div class="card-header">
              <h3 class="card-title"><?php echo htmlspecialchars($group); ?></h3>
              <span class="card-title-meta"><?php echo count($modules); ?> modules</span>
            </div>
            <div class="card-body table-responsive p-0">
              <table class="table table-sm table-hover mb-0 perm-matrix">
                <thead>
                  <tr>
                    <th>Module</th>
                    <th class="text-center" style="width:110px">View</th>
                    <th class="text-center" style="width:110px">Export</th>
                  </tr>
                </thead>
                <tbody>
                <?php foreach ($modules as $mod) {
                  $key = $mod->module_key;
                  $pv = isset($perm_map[$key]['can_view']) ? (int) $perm_map[$key]['can_view'] : 0;
                  $pe = isset($perm_map[$key]['can_export']) ? (int) $perm_map[$key]['can_export'] : 0;
                  if ($is_super) {
                      $pv = 1;
                      $pe = 1;
                  }
                  $is_admin_mod = (strpos($key, 'manage_') === 0);
                ?>
                  <tr>
                    <td>
                      <?php echo htmlspecialchars($mod->module_name); ?>
                      <div class="text-muted small"><code><?php echo htmlspecialchars($key); ?></code></div>
                    </td>
                    <td class="text-center">
                      <div class="custom-control custom-checkbox d-inline-block">
                        <input type="checkbox" class="custom-control-input js-perm-view"
                               id="v_<?php echo htmlspecialchars($key); ?>"
                               name="perm[<?php echo htmlspecialchars($key); ?>][can_view]"
                               value="1" <?php echo $pv ? 'checked' : ''; ?>
                               <?php echo $is_super ? 'disabled' : ''; ?>>
                        <label class="custom-control-label" for="v_<?php echo htmlspecialchars($key); ?>"></label>
                      </div>
                    </td>
                    <td class="text-center">
                      <?php if ($is_admin_mod) { ?>
                        <span class="text-muted small">—</span>
                        <input type="hidden" name="perm[<?php echo htmlspecialchars($key); ?>][can_export]" value="0">
                      <?php } else { ?>
                      <div class="custom-control custom-checkbox d-inline-block">
                        <input type="checkbox" class="custom-control-input js-perm-export"
                               id="e_<?php echo htmlspecialchars($key); ?>"
                               name="perm[<?php echo htmlspecialchars($key); ?>][can_export]"
                               value="1" <?php echo $pe ? 'checked' : ''; ?>
                               data-view="#v_<?php echo htmlspecialchars($key); ?>"
                               <?php echo $is_super ? 'disabled' : ''; ?>>
                        <label class="custom-control-label" for="e_<?php echo htmlspecialchars($key); ?>"></label>
                      </div>
                      <?php } ?>
                    </td>
                  </tr>
                <?php } ?>
                </tbody>
              </table>
            </div>
          </div>
        <?php } ?>

        <div class="mb-4">
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save mr-1"></i> Save permissions
          </button>
        </div>
      </form>
    </div>
  </section>
</div>
<script>
(function ($) {
  $(function () {
    $(document).on('change', '.js-perm-export', function () {
      if (this.checked) {
        var viewSel = $(this).data('view');
        if (viewSel) { $(viewSel).prop('checked', true); }
      }
    });
    $('#checkAllView').on('click', function () {
      $('.js-perm-view:not(:disabled)').prop('checked', true);
    });
    $('#checkAllExport').on('click', function () {
      $('.js-perm-export:not(:disabled)').prop('checked', true).trigger('change');
    });
    $('#uncheckAll').on('click', function () {
      $('.js-perm-view:not(:disabled), .js-perm-export:not(:disabled)').prop('checked', false);
    });
  });
})(jQuery);
</script>
