<?php
declare(strict_types=1);
session_start();

require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) { header("Location: index.html?e=1"); exit; }

$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');

$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$userId = (int)($_GET['id'] ?? 0);
if ($userId <= 0) { http_response_code(400); exit('رقم الموظف غير صحيح'); }

/* اكتشاف أعمدة جدول permissions تلقائياً */
$permCols = [];
try {
  $stc = $pdo->query("SHOW COLUMNS FROM `permissions`");
  $permCols = $stc->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (Throwable $e) {
  $permCols = [];
}

$nameCol = '';
$codeCol = '';

foreach (['name','name_ar','title','label','permission_name'] as $c) {
  if (in_array($c, $permCols, true)) { $nameCol = $c; break; }
}
foreach (['code','permission_code','perm_code','key'] as $c) {
  if (in_array($c, $permCols, true)) { $codeCol = $c; break; }
}

if ($nameCol === '' || $codeCol === '') {
  if ($debug) {
    echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
    echo "permissions columns:\n"; print_r($permCols);
    echo "\nDetected nameCol={$nameCol} codeCol={$codeCol}\n";
    echo "</pre>";
    exit;
  }
  exit('هيكل جدول permissions غير مطابق. فعّل debug=1 لمعرفة الأعمدة.');
}

/* جلب كل الصلاحيات */
$perms = [];
$st = $pdo->query("SELECT * FROM `permissions` ORDER BY id ASC");
$perms = $st->fetchAll();

/* جلب صلاحيات الموظف الحالية */
$current = [];
$st2 = $pdo->prepare("SELECT permission_code FROM employee_permissions WHERE user_id=?");
$st2->execute([$userId]);
$current = $st2->fetchAll(PDO::FETCH_COLUMN);

/* حفظ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $pdo->prepare("DELETE FROM employee_permissions WHERE user_id=?")->execute([$userId]);

  foreach (($_POST['perms'] ?? []) as $permCode) {
    $permCode = trim((string)$permCode);
    if ($permCode === '') continue;

    $ins = $pdo->prepare("INSERT INTO employee_permissions (user_id, permission_code) VALUES (?,?)");
    $ins->execute([$userId, $permCode]);
  }

  header("Location: employee_permissions.php?id=".$userId."&saved=1");
  exit;
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>تعديل صلاحيات الموظف</title>
<style>
body{font-family:Tajawal,system-ui; background:#f5f7fb; padding:40px;}
.box{background:#fff; padding:28px; border-radius:14px; max-width:900px; margin:auto; box-shadow:0 10px 30px rgba(0,0,0,.08);}
.top{display:flex; align-items:center; justify-content:space-between; gap:14px; flex-wrap:wrap;}
h2{margin:0; font-size:22px;}
.btn{background:#0a7cff; color:#fff; border:0; padding:10px 18px; border-radius:10px; cursor:pointer; font-size:14px;}
.btn:hover{opacity:.92;}
.note{margin:14px 0; padding:10px 12px; background:#f1f5ff; border:1px solid #dfe8ff; border-radius:10px; color:#123;}
.grid{display:grid; grid-template-columns:repeat(3, minmax(0,1fr)); gap:12px; margin-top:14px;}
@media(max-width:900px){.grid{grid-template-columns:repeat(2, minmax(0,1fr));}}
@media(max-width:520px){.grid{grid-template-columns:1fr;}}
.item{display:flex; align-items:center; gap:10px; padding:12px; border-radius:12px; background:#f7f8fb; border:1px solid #eef0f6;}
.item input{width:18px;height:18px;}
.small{color:#667; font-size:12px; margin-top:10px;}
.controls{display:flex; gap:10px; margin-top:14px; flex-wrap:wrap;}
.linkbtn{background:#111827; color:#fff; border:0; padding:10px 14px; border-radius:10px; cursor:pointer; font-size:13px;}
.linkbtn.gray{background:#6b7280;}
</style>
</head>
<body>

<div class="box">
  <div class="top">
    <h2>تعديل صلاحيات الموظف</h2>
    <button class="btn" type="submit" form="permForm">حفظ الصلاحيات</button>
  </div>

  <?php if (isset($_GET['saved'])): ?>
    <div class="note">تم حفظ الصلاحيات بنجاح</div>
  <?php endif; ?>

  <?php if (count($perms) === 0): ?>
    <div class="note">
      لا توجد صلاحيات للعرض. لازم تضيف بيانات داخل جدول permissions.
      <?php if ($debug): ?>
        <div class="small">debug: perms_count=0, nameCol=<?=h($nameCol)?>, codeCol=<?=h($codeCol)?></div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <div class="controls">
    <button type="button" class="linkbtn" onclick="toggleAll(true)">تحديد الكل</button>
    <button type="button" class="linkbtn gray" onclick="toggleAll(false)">إلغاء الكل</button>
  </div>

  <form id="permForm" method="post">
    <div class="grid">
      <?php foreach ($perms as $p): 
        $code = (string)($p[$codeCol] ?? '');
        $name = (string)($p[$nameCol] ?? $code);
        if ($code === '') continue;
        $checked = in_array($code, $current, true) ? 'checked' : '';
      ?>
        <label class="item">
          <input type="checkbox" name="perms[]" value="<?=h($code)?>" <?=$checked?>>
          <span><?=h($name)?></span>
        </label>
      <?php endforeach; ?>
    </div>
  </form>

  <?php if ($debug): ?>
    <div class="small">debug: perms_count=<?=count($perms)?>, current_count=<?=count($current)?>, nameCol=<?=h($nameCol)?>, codeCol=<?=h($codeCol)?></div>
  <?php endif; ?>
</div>

<script>
function toggleAll(on){
  document.querySelectorAll('input[type="checkbox"][name="perms[]"]').forEach(cb => cb.checked = !!on);
}
</script>

</body>
</html>