<?php
$page_title = 'المستخدمون والصلاحيات';
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/settings_store.php';
require_once __DIR__ . '/admin_user_profile_lib.php';

require_login();
$conn = ensure_db(true);
if (function_exists('ensure_auth_tables')) ensure_auth_tables($conn);
if (function_exists('ua_ensure_admin_profile_columns')) ua_ensure_admin_profile_columns($conn);
if (function_exists('require_perm')) require_perm('can_manage_admins');

if (!function_exists('ua_up_col')) {
  function ua_up_col(mysqli $conn, string $col): bool {
    return function_exists('col_exists') ? col_exists($conn, 'admin_users', $col) : false;
  }
}
if (!function_exists('ua_up_post')) {
  function ua_up_post(string $key): string {
    return trim((string)($_POST[$key] ?? ''));
  }
}
if (!function_exists('ua_up_checked')) {
  function ua_up_checked(array $perms, string $key): string {
    if (function_exists('ua_permission_array_has')) {
      return ua_permission_array_has($perms, $key) ? 'checked' : '';
    }
    return (!empty($perms['all']) || !empty($perms[$key])) ? 'checked' : '';
  }
}
if (!function_exists('ua_up_get_perms')) {
  function ua_up_get_perms(mysqli $conn, int $id): array {
    $id = (int)$id;
    if ($id <= 0 || !ua_up_col($conn, 'permissions')) return [];
    $q = $conn->query("SELECT permissions FROM admin_users WHERE id=$id LIMIT 1");
    $p = ($q && $q->num_rows) ? (string)($q->fetch_assoc()['permissions'] ?? '') : '';
    $arr = $p !== '' ? json_decode($p, true) : [];
    return is_array($arr) ? $arr : [];
  }
}

$PERMISSION_GROUPS = function_exists('ua_permission_groups') ? ua_permission_groups() : [];
$PERMS = function_exists('ua_permission_catalog') ? ua_permission_catalog() : [];

$msg = '';
$err = '';
$selected_id = (int)($_GET['id'] ?? 0);

// كلمة مرور السوبر أدمن للأوامر الحساسة.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_super_admin_password'])) {
  $p1 = (string)($_POST['sa_pass1'] ?? '');
  $p2 = (string)($_POST['sa_pass2'] ?? '');
  if (trim($p1) === '' || trim($p2) === '') {
    $err = 'كلمة مرور السوبر أدمن مطلوبة.';
  } elseif ($p1 !== $p2) {
    $err = 'كلمتا المرور غير متطابقتين.';
  } elseif (mb_strlen($p1, 'UTF-8') < 6) {
    $err = 'كلمة المرور قصيرة جداً. الحد الأدنى 6 أحرف.';
  } else {
    setting_set($conn, 'super_admin_pass_hash', password_hash($p1, PASSWORD_DEFAULT));
    $msg = 'تم حفظ كلمة مرور السوبر أدمن بنجاح.';
  }
}

// حذف مستخدم مع منع حذف المستخدم الحالي.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user'])) {
  $uid = (int)($_POST['user_id'] ?? 0);
  $me = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
  if ($uid <= 0) {
    $err = 'مستخدم غير صالح.';
  } elseif ($uid === $me) {
    $err = 'لا يمكنك حذف المستخدم الحالي.';
  } else {
    $old = ua_admin_fetch_user($conn, $uid);
    if ($conn->query("DELETE FROM admin_users WHERE id=$uid LIMIT 1")) {
      if ($old) {
        ua_admin_delete_old_image($old['avatar_path'] ?? '', '');
        ua_admin_delete_old_image($old['identity_image_path'] ?? '', '');
        ua_admin_delete_old_image($old['identity_front_image_path'] ?? '', '');
        ua_admin_delete_old_image($old['identity_back_image_path'] ?? '', '');
      }
      header('Location: users_permissions.php?deleted=1');
      exit;
    }
    $err = 'DB Error: ' . $conn->error;
  }
}

// حفظ المستخدم + ملفه الشخصي + صلاحياته من مكان واحد.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_user'])) {
  $uid = (int)($_POST['user_id'] ?? 0);
  $selected_id = $uid;

  $username = ua_up_post('username');
  $full_name = ua_up_post('full_name');
  $email = ua_up_post('email');
  $phone = ua_up_post('phone');
  $phone2 = ua_up_post('phone2');
  $job_title = ua_up_post('job_title');
  $address = ua_up_post('address');
  $identity_no = ua_up_post('identity_no');
  $profile_notes = ua_up_post('profile_notes');
  $is_active = (int)($_POST['is_active'] ?? 1) === 1 ? 1 : 0;
  $new_pass = (string)($_POST['new_password'] ?? '');

  if ($username === '') {
    $err = 'اسم المستخدم مطلوب.';
  } elseif ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $err = 'صيغة البريد الإلكتروني غير صحيحة.';
  } elseif ($uid <= 0 && trim($new_pass) === '') {
    $err = 'كلمة المرور مطلوبة عند إنشاء مستخدم جديد.';
  } elseif (trim($new_pass) !== '' && mb_strlen($new_pass, 'UTF-8') < 6) {
    $err = 'كلمة المرور قصيرة جداً. الحد الأدنى 6 أحرف.';
  }

  if (!$err) {
    $u = $conn->real_escape_string($username);
    $not = $uid > 0 ? "AND id<>$uid" : '';
    $q = $conn->query("SELECT id FROM admin_users WHERE username='$u' $not LIMIT 1");
    if ($q && $q->num_rows) $err = 'اسم المستخدم مستخدم مسبقاً.';
  }

  $perms = [];
  if (!empty($_POST['perm_all'])) {
    $perms = ['all' => true];
  } else {
    foreach (array_keys($PERMS) as $key) {
      if (!empty($_POST['perm_' . $key])) $perms[$key] = true;
    }
    $perms['dashboard_permissions_configured'] = true;
  }
  $pjson = json_encode($perms, JSON_UNESCAPED_UNICODE);

  $old = $uid > 0 ? ua_admin_fetch_user($conn, $uid) : null;

  if (!$err) {
    $fields = [
      'username' => $username,
      'full_name' => $full_name,
      'email' => $email,
      'phone' => $phone,
      'phone2' => $phone2,
      'job_title' => $job_title,
      'address' => $address,
      'identity_no' => $identity_no,
      'profile_notes' => $profile_notes,
      'permissions' => $pjson,
    ];

    $sets = [];
    foreach ($fields as $col => $val) {
      if (ua_up_col($conn, $col)) $sets[] = "`$col`='".$conn->real_escape_string((string)$val)."'";
    }
    if (ua_up_col($conn, 'is_active')) $sets[] = "is_active=$is_active";
    if (ua_up_col($conn, 'updated_at')) $sets[] = "updated_at=NOW()";

    if (trim($new_pass) !== '') {
      $hash = password_hash($new_pass, PASSWORD_DEFAULT);
      $hashEsc = $conn->real_escape_string($hash);
      if (ua_up_col($conn, 'password_hash')) $sets[] = "password_hash='$hashEsc'";
      if (ua_up_col($conn, 'password')) $sets[] = "password='$hashEsc'";
    }

    if ($uid > 0) {
      $ok = !empty($sets) ? $conn->query("UPDATE admin_users SET ".implode(',', $sets)." WHERE id=$uid LIMIT 1") : true;
      if (!$ok) $err = 'DB Error: ' . $conn->error;
    } else {
      $cols = [];
      $vals = [];
      foreach ($fields as $col => $val) {
        if (ua_up_col($conn, $col)) { $cols[] = "`$col`"; $vals[] = "'".$conn->real_escape_string((string)$val)."'"; }
      }
      if (ua_up_col($conn, 'is_active')) { $cols[] = '`is_active`'; $vals[] = (string)$is_active; }
      if (trim($new_pass) !== '') {
        $hash = password_hash($new_pass, PASSWORD_DEFAULT);
        $hashEsc = $conn->real_escape_string($hash);
        if (ua_up_col($conn, 'password_hash')) { $cols[] = '`password_hash`'; $vals[] = "'$hashEsc'"; }
        if (ua_up_col($conn, 'password')) { $cols[] = '`password`'; $vals[] = "'$hashEsc'"; }
      }
      $ok = $conn->query("INSERT INTO admin_users (".implode(',', $cols).") VALUES (".implode(',', $vals).")");
      if ($ok) {
        $uid = (int)$conn->insert_id;
        $selected_id = $uid;
      } else {
        $err = 'DB Error: ' . $conn->error;
      }
    }
  }

  // الصور بعد ضمان وجود ID.
  if (!$err && $uid > 0) {
    $avatar_new = ua_admin_upload_image('avatar_image', $uid, 'avatar', $err);
    $id_front_new = !$err ? ua_admin_upload_image('identity_front_image', $uid, 'identity_front', $err) : '';
    $id_back_new = !$err ? ua_admin_upload_image('identity_back_image', $uid, 'identity_back', $err) : '';
    $imgSets = [];
    if (!$err) {
      if ($avatar_new !== '' && ua_up_col($conn, 'avatar_path')) $imgSets[] = "avatar_path='".$conn->real_escape_string($avatar_new)."'";
      elseif (!empty($_POST['remove_avatar']) && ua_up_col($conn, 'avatar_path')) $imgSets[] = "avatar_path=NULL";

      if ($id_front_new !== '') {
        if (ua_up_col($conn, 'identity_front_image_path')) $imgSets[] = "identity_front_image_path='".$conn->real_escape_string($id_front_new)."'";
        if (ua_up_col($conn, 'identity_image_path')) $imgSets[] = "identity_image_path='".$conn->real_escape_string($id_front_new)."'";
      } elseif (!empty($_POST['remove_identity_front_image'])) {
        if (ua_up_col($conn, 'identity_front_image_path')) $imgSets[] = "identity_front_image_path=NULL";
        if (ua_up_col($conn, 'identity_image_path')) $imgSets[] = "identity_image_path=NULL";
      }

      if ($id_back_new !== '' && ua_up_col($conn, 'identity_back_image_path')) $imgSets[] = "identity_back_image_path='".$conn->real_escape_string($id_back_new)."'";
      elseif (!empty($_POST['remove_identity_back_image']) && ua_up_col($conn, 'identity_back_image_path')) $imgSets[] = "identity_back_image_path=NULL";

      if ($imgSets) {
        $ok = $conn->query("UPDATE admin_users SET ".implode(',', $imgSets)." WHERE id=$uid LIMIT 1");
        if (!$ok) $err = 'DB Error: ' . $conn->error;
      }
    }
    if (!$err && $old) {
      if ($avatar_new !== '') ua_admin_delete_old_image($old['avatar_path'] ?? '', $avatar_new);
      elseif (!empty($_POST['remove_avatar'])) ua_admin_delete_old_image($old['avatar_path'] ?? '', '');
      if ($id_front_new !== '') {
        ua_admin_delete_old_image($old['identity_front_image_path'] ?? '', $id_front_new);
        ua_admin_delete_old_image($old['identity_image_path'] ?? '', $id_front_new);
      } elseif (!empty($_POST['remove_identity_front_image'])) {
        ua_admin_delete_old_image($old['identity_front_image_path'] ?? '', '');
        ua_admin_delete_old_image($old['identity_image_path'] ?? '', '');
      }
      if ($id_back_new !== '') ua_admin_delete_old_image($old['identity_back_image_path'] ?? '', $id_back_new);
      elseif (!empty($_POST['remove_identity_back_image'])) ua_admin_delete_old_image($old['identity_back_image_path'] ?? '', '');
    }
  }

  if (!$err && $uid > 0) {
    $me = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
    if ($uid === $me) {
      auth_refresh_session_perms($conn);
      $fresh = ua_admin_fetch_user($conn, $uid);
      if ($fresh) ua_admin_profile_set_session($fresh);
    }
    header('Location: users_permissions.php?id=' . $uid . '&saved=1');
    exit;
  }
}

if (!empty($_GET['saved'])) $msg = 'تم حفظ المستخدم والصلاحيات بنجاح.';
if (!empty($_GET['deleted'])) $msg = 'تم حذف المستخدم بنجاح.';

$users = [];
$rs = $conn->query("SELECT * FROM admin_users ORDER BY id DESC");
if ($rs) while ($r = $rs->fetch_assoc()) $users[] = $r;
if ($selected_id <= 0 && count($users) && empty($_GET['new'])) $selected_id = (int)$users[0]['id'];

$sel = null;
$selPerms = [];
if ($selected_id > 0) {
  $sel = ua_admin_fetch_user($conn, $selected_id);
  if ($sel) $selPerms = ua_up_get_perms($conn, (int)$sel['id']);
}
$avatar = $sel ? ua_admin_public_image_url($sel['avatar_path'] ?? '') : '';
$idfront = $sel ? ua_admin_public_image_url($sel['identity_front_image_path'] ?? '') : '';
if ($idfront === '' && $sel) $idfront = ua_admin_public_image_url($sel['identity_image_path'] ?? '');
$idback = $sel ? ua_admin_public_image_url($sel['identity_back_image_path'] ?? '') : '';
$selected_name = (string)($sel['full_name'] ?? $sel['username'] ?? 'مستخدم جديد');

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidUsersPermissions = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidUsersPermissions) $UA_PAGE_CSS = ['assets/css/android_users_permissions.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
if ($uaAndroidUsersPermissions) { require __DIR__ . '/android_users_permissions.php'; include __DIR__ . '/footer.php'; return; }
?>

<div class="content-wrapper ua-manual-page">
  <section class="content">
    <div class="container-fluid">
<div class="ua-users-perm-shell">
  <div class="ua-users-perm-head">
    <h1><i class="fa fa-users"></i> المستخدمون والصلاحيات</h1>
    <div class="d-flex gap-2 flex-wrap">
      <a class="btn btn-outline-light btn-sm" href="user_profile.php"><i class="fa fa-id-card-o"></i> ملفي الشخصي</a>
      <a class="btn btn-warning btn-sm" href="users_permissions.php?new=1&id=0"><i class="fa fa-plus"></i> مستخدم جديد</a>
    </div>
  </div>

  <?php if($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

  <div class="ua-users-perm-card">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-8">
        <label class="form-label fw-bold">اختيار مستخدم</label>
        <select name="id" class="form-control" onchange="this.form.submit()">
          <?php foreach($users as $u): $id=(int)$u['id']; ?>
            <option value="<?= $id ?>" <?= $id===$selected_id?'selected':'' ?>>
              <?= h(($u['full_name'] ?? '') ?: ($u['username'] ?? '')) ?> (<?= h($u['username'] ?? '') ?>)<?= ((int)($u['is_active'] ?? 1)===1?'':' - معطّل') ?>
            </option>
          <?php endforeach; ?>
          <option value="0" <?= $selected_id===0?'selected':'' ?>>+ إضافة مستخدم جديد</option>
        </select>
      </div>
      <div class="col-md-4">
        <button class="btn btn-outline-info w-100"><i class="fa fa-search"></i> فتح</button>
      </div>
    </form>
  </div>

  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="user_id" value="<?= (int)($sel['id'] ?? 0) ?>">
    <div class="ua-users-grid">
      <section class="ua-users-perm-card">
        <h5 class="mb-3 ua-u-accent-title"><i class="fa fa-id-card-o"></i> بيانات المستخدم</h5>
        <div class="ua-users-avatar-row mb-3">
          <div class="ua-users-avatar">
            <?php if($avatar): ?><img src="<?= h($avatar) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$avatar) ?>" alt=""><?php else: ?><?= h(mb_substr($selected_name,0,1,'UTF-8')) ?><?php endif; ?>
          </div>
          <div class="flex-grow-1">
            <label class="form-label fw-bold">صورة البروفايل</label>
            <input type="file" class="form-control" name="avatar_image" accept="image/jpeg,image/png,image/webp">
            <?php if($avatar): ?><label class="ua-muted mt-1 d-inline-flex align-items-center gap-1"><input type="checkbox" name="remove_avatar" value="1"> حذف الصورة الحالية</label><?php endif; ?>
          </div>
        </div>

        <div class="ua-users-fields">
          <div class="ua-users-field"><label>الاسم الكامل</label><input class="form-control" name="full_name" value="<?= h($sel['full_name'] ?? '') ?>"></div>
          <div class="ua-users-field"><label>اسم المستخدم</label><input class="form-control" name="username" value="<?= h($sel['username'] ?? '') ?>" autocomplete="off"></div>
          <div class="ua-users-field"><label>البريد الإلكتروني</label><input class="form-control" name="email" value="<?= h($sel['email'] ?? '') ?>" autocomplete="off"></div>
          <div class="ua-users-field"><label>الحالة</label><select class="form-control" name="is_active"><option value="1" <?= ((int)($sel['is_active'] ?? 1)===1)?'selected':'' ?>>فعّال</option><option value="0" <?= ((int)($sel['is_active'] ?? 1)===0)?'selected':'' ?>>معطّل</option></select></div>
          <div class="ua-users-field"><label>رقم الاتصال الأساسي</label><input class="form-control" name="phone" value="<?= h($sel['phone'] ?? '') ?>"></div>
          <div class="ua-users-field"><label>رقم اتصال إضافي</label><input class="form-control" name="phone2" value="<?= h($sel['phone2'] ?? '') ?>"></div>
          <div class="ua-users-field"><label>المسمى الوظيفي</label><input class="form-control" name="job_title" value="<?= h($sel['job_title'] ?? '') ?>"></div>
          <div class="ua-users-field"><label>رقم الهوية</label><input class="form-control" name="identity_no" value="<?= h($sel['identity_no'] ?? '') ?>"></div>
          <div class="ua-users-field ua-u-grid-full"><label>العنوان</label><input class="form-control" name="address" value="<?= h($sel['address'] ?? '') ?>"></div>
          <div class="ua-users-field ua-u-grid-full"><label>ملاحظات</label><textarea class="form-control" name="profile_notes"><?= h($sel['profile_notes'] ?? '') ?></textarea></div>
          <div class="ua-users-field ua-u-grid-full"><label>كلمة مرور جديدة</label><input type="password" class="form-control" name="new_password" autocomplete="new-password" placeholder="اتركها فارغة بدون تغيير"></div>
          <div class="ua-users-field"><label>صورة الهوية - الوجه الأمامي</label><input type="file" class="form-control" name="identity_front_image" accept="image/jpeg,image/png,image/webp"><?php if($idfront): ?><label class="ua-muted mt-1 d-inline-flex align-items-center gap-1"><input type="checkbox" name="remove_identity_front_image" value="1"> حذف الأمامية</label><?php endif; ?></div>
          <div class="ua-users-field"><label>صورة الهوية - الوجه الخلفي</label><input type="file" class="form-control" name="identity_back_image" accept="image/jpeg,image/png,image/webp"><?php if($idback): ?><label class="ua-muted mt-1 d-inline-flex align-items-center gap-1"><input type="checkbox" name="remove_identity_back_image" value="1"> حذف الخلفية</label><?php endif; ?></div>
          <?php if($idfront || $idback): ?>
            <div class="ua-users-field ua-u-grid-full">
              <label>معاينة صور الهوية</label>
              <div class="ua-users-id-preview-grid">
                <?php if($idfront): ?><div class="ua-users-id-preview-card"><strong>الوجه الأمامي</strong><img class="ua-users-id-preview" src="<?= h($idfront) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$idfront) ?>" alt=""></div><?php endif; ?>
                <?php if($idback): ?><div class="ua-users-id-preview-card"><strong>الوجه الخلفي</strong><img class="ua-users-id-preview" src="<?= h($idback) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$idback) ?>" alt=""></div><?php endif; ?>
              </div>
            </div>
          <?php endif; ?>
        </div>
      </section>

      <section class="ua-users-perm-card">
        <h5 class="mb-3 ua-u-accent-title"><i class="fa fa-shield"></i> الصلاحيات وخيارات الوصول</h5>
        <label class="ua-perm-item mb-2 ua-u-accent-soft-bg">
          <input type="checkbox" id="perm_all" name="perm_all" value="1" <?= ua_up_checked($selPerms,'all') ?>>
          <span>كل الصلاحيات / SUPER</span>
        </label>
        <div class="ua-permission-groups">
          <?php foreach($PERMISSION_GROUPS as $group): ?>
            <fieldset class="ua-permission-group">
              <legend><?= h($group['label'] ?? '') ?></legend>
              <div class="ua-perms-list">
                <?php foreach((array)($group['permissions'] ?? []) as $key=>$label): ?>
                  <label class="ua-perm-item">
                    <input type="checkbox" class="perm-item" name="perm_<?= h($key) ?>" value="1" <?= ua_up_checked($selPerms,$key) ?>>
                    <span><?= h($label) ?></span>
                  </label>
                <?php endforeach; ?>
              </div>
            </fieldset>
          <?php endforeach; ?>
        </div>
        <div class="alert alert-info mt-3 mb-0">
          كل مستخدم يملك صلاحياته الخاصة. الصفحات القديمة تم تحويلها لهذه الصفحة حتى لا يحصل تكرار أو تضارب.
        </div>
      </section>
    </div>

    <div class="ua-users-actions">
      <button class="btn btn-warning" name="save_user"><i class="fa fa-save"></i> حفظ المستخدم والصلاحيات</button>
      <?php if(!empty($sel['id'])): ?><button class="btn btn-danger" name="delete_user" formnovalidate onclick="return confirm('حذف المستخدم نهائياً؟');"><i class="fa fa-trash"></i> حذف</button><?php endif; ?>
    </div>
  </form>

  <section class="ua-users-perm-card ua-super-card mt-4">
    <h5 class="mb-2 ua-u-accent-title"><i class="fa fa-lock"></i> حماية الأوامر اليدوية / سوبر أدمن</h5>
    <p class="ua-muted mb-3">تُستخدم هذه الكلمة لحماية الأوامر اليدوية الحساسة مثل قطع/استعادة PPPoE، ولا تؤثر على الأوامر التلقائية.</p>
    <form method="post" class="row g-2">
      <div class="col-md-4"><label class="form-label fw-bold">كلمة المرور</label><input type="password" name="sa_pass1" class="form-control" autocomplete="new-password"></div>
      <div class="col-md-4"><label class="form-label fw-bold">تأكيد كلمة المرور</label><input type="password" name="sa_pass2" class="form-control" autocomplete="new-password"></div>
      <div class="col-md-4 d-flex align-items-end"><button class="btn btn-outline-warning w-100" name="set_super_admin_password"><i class="fa fa-lock"></i> حفظ كلمة المرور</button></div>
    </form>
  </section>
</div>

<script>
(function(){
  var all = document.getElementById('perm_all');
  if(!all) return;
  all.addEventListener('change', function(){
    document.querySelectorAll('.perm-item').forEach(function(x){ x.checked = all.checked; });
  });
})();
</script>

    </div>
  </section>
</div>

<?php include __DIR__ . '/footer.php'; ?>
