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

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if (!function_exists('user_find')) {
function user_find(int $id): ?array { return db_one("SELECT id,name,email,role,is_active,created_at,updated_at FROM users WHERE id=?", [$id]); }

$roles = ['admin'=>'admin','supervisor'=>'supervisor','data_entry'=>'data_entry','viewer'=>'viewer'];

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

  if ($action==='create' || ($action==='edit' && $id>0)) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = $_POST['role'] ?? 'viewer';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $password = $_POST['password'] ?? '';

    if ($name==='' || $email==='') {
      flash_set('error','الاسم والبريد مطلوبان.');
      redirect(url('/index.php?page=users&action='.$action.($id?('&id='.$id):'')));
    }
    if (!isset($roles[$role])) $role = 'viewer';

    if ($action==='create') {
      if (strlen($password) < 6) {
        flash_set('error','كلمة المرور يجب أن تكون 6 أحرف على الأقل.');
        redirect(url('/index.php?page=users&action=create'));
      }
      $hash = password_hash($password, PASSWORD_BCRYPT);
      $newId = db_insert("INSERT INTO users (name,email,password_hash,role,is_active,created_at,updated_at) VALUES (?,?,?,?,?,?,?)",
        [$name,$email,$hash,$role,$is_active, now_dt(), null]
      );
      audit_log('create','users',$newId,null,user_find($newId));
      flash_set('ok','تم إنشاء المستخدم.');
      redirect(url('/index.php?page=users'));
    } else {
      $old = user_find($id);
      $params = [$name,$email,$role,$is_active, now_dt(), $id];
      $sql = "UPDATE users SET name=?, email=?, role=?, is_active=?, updated_at=? WHERE id=?";
      db_exec($sql, $params);
      if ($password !== '') {
        if (strlen($password) < 6) {
          flash_set('error','كلمة المرور يجب أن تكون 6 أحرف على الأقل.');
          redirect(url('/index.php?page=users&action=edit&id='.$id));
        }
        $hash = password_hash($password, PASSWORD_BCRYPT);
        db_exec("UPDATE users SET password_hash=?, updated_at=? WHERE id=?", [$hash, now_dt(), $id]);
      }
      $new = user_find($id);
      audit_log('update','users',$id,$old,$new);
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=users'));
    }
  }

  if ($action==='delete' && $id>0) {
    if ($id == intval($_SESSION['uid'] ?? 0)) {
      flash_set('error','لا يمكنك حذف حسابك الحالي.');
      redirect(url('/index.php?page=users'));
    }
    $old = user_find($id);
    db_exec("DELETE FROM users WHERE id=?", [$id]);
    audit_log('delete','users',$id,$old,null);
    flash_set('ok','تم حذف المستخدم.');
    redirect(url('/index.php?page=users'));
  }
}
}


$rows = db_all("SELECT id,name,email,role,is_active,created_at FROM users ORDER BY id DESC");
?>

<?php if ($action==='list'): ?>
  <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap">
    <div>
      <h1>المستخدمون</h1>
      <div class="small muted">إدارة حسابات المستخدمين وأدوارهم.</div>
    </div>
    <a class="btn primary" href="<?= e(url('/index.php?page=users&action=create')) ?>">إضافة مستخدم</a>
  </div>

  <hr>

  <div style="overflow:auto">
    <table class="table">
      <thead><tr><th>#</th><th>الاسم</th><th>البريد</th><th>الدور</th><th>نشط</th><th>تاريخ</th><th>إجراءات</th></tr></thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= e((string)$r['id']) ?></td>
            <td><?= e($r['name']) ?></td>
            <td class="small"><?= e($r['email']) ?></td>
            <td><span class="tag"><?= e($r['role']) ?></span></td>
            <td><?= intval($r['is_active'])?'<span class="badge">نعم</span>':'<span class="badge">لا</span>' ?></td>
            <td class="small"><?= e((string)$r['created_at']) ?></td>
            <td class="actions">
              <a class="btn" href="<?= e(url('/index.php?page=users&action=edit&id='.$r['id'])) ?>">تعديل</a>
              <?php if ($r['id'] != intval($_SESSION['uid'] ?? 0)): ?>
                <form method="post" action="<?= e(url('/index.php?page=users&action=delete&id='.$r['id'])) ?>" onsubmit="return confirm('حذف المستخدم؟')">
                  <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                  <button class="btn danger">حذف</button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<?php if ($action==='create' || ($action==='edit' && $id>0)): ?>
  <?php $row = ($action==='edit') ? user_find($id) : ['name'=>'','email'=>'','role'=>'viewer','is_active'=>1]; ?>
  <h1><?= $action==='create'?'إضافة مستخدم':'تعديل مستخدم' ?></h1>
  <hr>
  <form method="post">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <div class="form-grid">
      <div>
        <label class="small">الاسم</label>
        <input class="input" name="name" value="<?= e((string)$row['name']) ?>" required>
      </div>
      <div>
        <label class="small">البريد</label>
        <input class="input" name="email" value="<?= e((string)$row['email']) ?>" required>
      </div>
      <div>
        <label class="small">الدور</label>
        <select class="input" name="role">
          <?php foreach ($roles as $k=>$v): ?>
            <option value="<?= e($k) ?>" <?= (($row['role']??'')===$k)?'selected':'' ?>><?= e($v) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="small">نشط</label>
        <label class="small"><input type="checkbox" name="is_active" <?= intval($row['is_active'] ?? 0)?'checked':'' ?>> تفعيل</label>
      </div>
      <div style="grid-column:1/-1">
        <label class="small"><?= $action==='create'?'كلمة المرور':'تغيير كلمة المرور (اختياري)' ?></label>
        <input class="input" name="password" type="password" placeholder="<?= $action==='create'?'مطلوبة':'اتركه فارغاً دون تغيير' ?>">
      </div>
    </div>
    <div class="actions" style="margin-top:12px">
      <button class="btn primary">حفظ</button>
      <a class="btn" href="<?= e(url('/index.php?page=users')) ?>">عودة</a>
    </div>
  </form>
<?php endif; ?>
