<?php
require __DIR__ . '/_common.php';
require_perm('manage_permissions');

$roles = ['admin'=>'admin','supervisor'=>'supervisor','data_entry'=>'data_entry','viewer'=>'viewer'];
$action = $_GET['action'] ?? 'matrix';

if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();

  // Reset matrix (keeps permissions list)
  if (isset($_POST['reset_defaults'])) {
    // delete current role_permissions and re-run defaults by copying from install defaults.
    db_exec("DELETE FROM role_permissions");
    // Recreate defaults similar to install.php (without overwriting permissions table)
    $defaults = [
      'admin' => ['*'],
      'supervisor' => [
        'view_dashboard',
        'view_oases','manage_oases',
        'view_aflaj','manage_aflaj',
        'view_farms','manage_farms',
        'view_assets','manage_assets',
        'view_contractors','view_contracts',
        'view_maintenance','manage_maintenance','export_maintenance_pdf',
        'view_contractors','manage_contractors',
        'view_contracts','manage_contracts',
        'view_reports','export_reports_pdf',
        'manage_users',
        'view_audit',
      ],
      'data_entry' => [
        'view_dashboard',
        'view_oases','manage_oases',
        'view_aflaj','manage_aflaj',
        'view_farms','manage_farms',
        'view_assets','manage_assets',
        'view_contractors','view_contracts',
        'view_maintenance','manage_maintenance',
        'view_reports',
      ],
      'viewer' => [
        'view_dashboard',
        'view_oases','view_aflaj','view_farms','view_assets','view_maintenance','view_contractors','view_contracts',
        'view_reports',
      ],
    ];
    $allPerms = array_column(db_all("SELECT perm_key FROM permissions"), 'perm_key');
    foreach ($defaults as $role => $allowedList) {
      $allowedSet = [];
      if (in_array('*', $allowedList, true)) $allowedSet = array_fill_keys($allPerms, 1);
      else foreach ($allowedList as $k) $allowedSet[$k]=1;

      foreach ($allPerms as $k) {
        $allowed = isset($allowedSet[$k]) ? 1 : 0;
        db_exec("INSERT INTO role_permissions (role,perm_key,allowed,created_at,updated_at) VALUES (?,?,?,?,?)",
          [$role,$k,$allowed, now_dt(), null]
        );
      }
    }
    unset($_SESSION['perm_cache']);
    audit_log('reset_permissions','permissions',null,null,['by'=>auth_user()]);
    flash_set('ok','تمت إعادة ضبط الصلاحيات للوضع الافتراضي.');
    redirect(url('/index.php?page=permissions'));
  }

  // Update matrix
  $posted = $_POST['perm'] ?? [];
  $old = db_all("SELECT role, perm_key, allowed FROM role_permissions");
  $oldMap = [];
  foreach ($old as $r) $oldMap[$r['role'].'|'.$r['perm_key']] = intval($r['allowed']);

  // Ensure every cell exists
  $allPerms = db_all("SELECT perm_key FROM permissions ORDER BY perm_group, perm_key");
  foreach ($roles as $role) {
    foreach ($allPerms as $p) {
      $k = (string)$p['perm_key'];
      $want = isset($posted[$role][$k]) ? 1 : 0;

      // admin always allowed, and we keep it forced
      if ($role === 'admin') $want = 1;

      $exists = db_one("SELECT role FROM role_permissions WHERE role=? AND perm_key=? LIMIT 1", [$role,$k]);
      if ($exists) {
        db_exec("UPDATE role_permissions SET allowed=?, updated_at=? WHERE role=? AND perm_key=?", [$want, now_dt(), $role, $k]);
      } else {
        db_exec("INSERT INTO role_permissions (role,perm_key,allowed,created_at,updated_at) VALUES (?,?,?,?,?)", [$role,$k,$want, now_dt(), null]);
      }
    }
  }

  $new = db_all("SELECT role, perm_key, allowed FROM role_permissions");
  $changes = [];
  foreach ($new as $r) {
    $key = $r['role'].'|'.$r['perm_key'];
    $before = $oldMap[$key] ?? null;
    $after = intval($r['allowed']);
    if ($before === null || $before !== $after) {
      $changes[] = ['role'=>$r['role'], 'perm'=>$r['perm_key'], 'from'=>$before, 'to'=>$after];
    }
  }

  unset($_SESSION['perm_cache']);
  audit_log('update_permissions','permissions',null,$oldMap,$changes);
  flash_set('ok','تم حفظ الصلاحيات بنجاح.');
  redirect(url('/index.php?page=permissions'));
}

$perms = db_all("SELECT perm_group, perm_key, label FROM permissions ORDER BY perm_group, perm_key");
$matrix = db_all("SELECT role, perm_key, allowed FROM role_permissions");
$allowed = [];
foreach ($matrix as $r) $allowed[$r['role']][$r['perm_key']] = intval($r['allowed']);

$groups = [];
foreach ($perms as $p) {
  $g = (string)$p['perm_group'];
  if (!isset($groups[$g])) $groups[$g] = [];
  $groups[$g][] = $p;
}
?>

<h1>إدارة الصلاحيات</h1>
<div class="small muted">تحكم دقيق بالصلاحيات حسب الدور. (admin دائمًا كامل الصلاحيات)</div>

<hr>

<form method="post">
  <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

  <div class="actions" style="margin-bottom:12px">
    <button class="btn primary" type="submit">حفظ التعديلات</button>
    <button class="btn" type="submit" name="reset_defaults" value="1" onclick="return confirm('إعادة ضبط الصلاحيات للوضع الافتراضي؟')">إعادة ضبط افتراضي</button>
  </div>

  <?php foreach ($groups as $g => $items): ?>
    <div class="card" style="margin-bottom:12px">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap">
        <h2 style="margin:0"><?= e($g) ?></h2>
        <span class="small muted"><?= e(count($items)) ?> صلاحية</span>
      </div>

      <div style="overflow:auto;margin-top:10px">
        <table class="table">
          <thead>
            <tr>
              <th>الصلاحية</th>
              <th class="small">المفتاح</th>
              <?php foreach ($roles as $role): ?>
                <th><?= e($role) ?></th>
              <?php endforeach; ?>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $p): ?>
              <?php $key = (string)$p['perm_key']; ?>
              <tr>
                <td><?= e($p['label']) ?></td>
                <td class="small code"><?= e($key) ?></td>
                <?php foreach ($roles as $role): ?>
                  <?php
                    $isAllowed = intval($allowed[$role][$key] ?? 0) === 1;
                    $disabled = ($role === 'admin') ? 'disabled' : '';
                  ?>
                  <td style="text-align:center">
                    <input type="checkbox" name="perm[<?= e($role) ?>][<?= e($key) ?>]" <?= $isAllowed?'checked':'' ?> <?= $disabled ?>>
                  </td>
                <?php endforeach; ?>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endforeach; ?>
</form>
