<?php
$page_title = 'إدارة أدوار المدراء والصلاحيات';
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';

require_login();
if(function_exists('require_perm')) require_perm('can_manage_roles');

// ضمان وجود الجداول المطلوبة (admin_roles/admin_users)
if (function_exists('ensure_auth_tables') && ($conn instanceof mysqli)) {
  ensure_auth_tables($conn);
}

$msg=""; $err="";

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

// ✅ تحديد اسم عمود الدور داخل admin_roles (name أو role_name)
function role_name_col(mysqli $conn): string {
  if(function_exists('col_exists') && col_exists($conn,'admin_roles','role_name')) return 'role_name';
  return 'name';
}

function fetch_roles($conn){
  $rows=[];
  $col = role_name_col($conn);
  $q=$conn->query("SELECT * FROM admin_roles ORDER BY $col ASC, id DESC");
  if($q && $q->num_rows){
    while($r=$q->fetch_assoc()) $rows[]=$r;
  }
  return $rows;
}

function role_perms($role){
  $p = $role['permissions'] ?? '';
  $arr = json_decode($p, true);
  return is_array($arr) ? $arr : [];
}

$roles = fetch_roles($conn);

// role للتعديل
$edit_id = intval($_GET['edit'] ?? 0);
$edit_role = null;
if($edit_id>0){
  $q=$conn->query("SELECT * FROM admin_roles WHERE id=$edit_id LIMIT 1");
  if($q && $q->num_rows) $edit_role=$q->fetch_assoc();
}

$edit_perms = $edit_role ? role_perms($edit_role) : [];

// حذف role
$delete_id = intval($_GET['delete'] ?? 0);
if($delete_id>0){

  // منع الحذف إذا مستخدم من admin_users
  if(function_exists('col_exists') && col_exists($conn,'admin_users','role_id')){
    $chk = $conn->query("SELECT COUNT(*) c FROM admin_users WHERE role_id=$delete_id");
    $c = ($chk)? (int)$chk->fetch_assoc()['c'] : 0;
    if($c>0){
      $err = "لا يمكن حذف هذا الدور لأنه مرتبط بـ ($c) مستخدم/مدير.";
    }
  }

  if(!$err){
    if(!$conn->query("DELETE FROM admin_roles WHERE id=$delete_id")){
      $err="DB Error: ".$conn->error;
    }else{
      header("Location: roles.php");
      exit;
    }
  }
}

// حفظ (إضافة/تعديل)
if(isset($_POST['save_role'])){
  $rid  = intval($_POST['rid'] ?? 0);
  $name = trim($_POST['name'] ?? '');
  $perms = $_POST['perms'] ?? [];

  if($name==='') $err="اسم الدور مطلوب";

  $perm_assoc = [];
  if(is_array($perms)){
    foreach($perms as $p){
      $p=trim($p);
      if($p!=='') $perm_assoc[$p]=true;
    }
  }
  $perm_assoc['dashboard_permissions_configured'] = true;

  $name_esc = $conn->real_escape_string($name);
  $perm_json = $conn->real_escape_string(json_encode($perm_assoc, JSON_UNESCAPED_UNICODE));

  if(!$err){
    $col = role_name_col($conn);
    if($rid>0){
      if(!$conn->query("UPDATE admin_roles SET $col='$name_esc', permissions='$perm_json' WHERE id=$rid")){
        $err="DB Error: ".$conn->error;
      }else{
        header("Location: roles.php?edit=".$rid);
        exit;
      }
    }else{
      if(!$conn->query("INSERT INTO admin_roles ($col, permissions) VALUES('$name_esc','$perm_json')")){
        $err="DB Error: ".$conn->error;
      }else{
        header("Location: roles.php");
        exit;
      }
    }
  }
}
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidRoles = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidRoles) $UA_PAGE_CSS = ['assets/css/android_roles.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

if ($uaAndroidRoles) { require __DIR__ . '/android_roles.php'; include __DIR__ . '/footer.php'; return; }

?>

<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center">
      <h1 class="mb-0">إدارة أدوار المدراء والصلاحيات</h1>
      <a href="roles.php" class="btn btn-secondary"><i class="fa fa-refresh"></i> تحديث</a>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">

      <?php if($err){ ?><div class="alert alert-danger"><?= h($err) ?></div><?php } ?>

      <div class="row">

        <div class="col-md-6">
          <div class="card compact">
            <div class="card-header"><b>كل الأدوار</b></div>
            <div class="card-body p-0">
              <table class="table table-bordered table-hover mb-0">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>اسم الدور</th>
                    <th class="ua-u-w-190">تحكم</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if(empty($roles)){ ?>
                    <tr><td colspan="3" class="text-center text-muted p-4">لا يوجد أدوار بعد</td></tr>
                  <?php } ?>
                  <?php foreach($roles as $r){ ?>
                    <tr>
                      <td><?= (int)$r['id'] ?></td>
                      <td><?php $col = role_name_col($conn); ?><?= h($r[$col] ?? '-') ?></td>
                      <td>
                        <a class="btn btn-sm btn-primary" href="roles.php?edit=<?= (int)$r['id'] ?>">
                          <i class="fa fa-edit"></i> تعديل
                        </a>
                        <a class="btn btn-sm btn-danger" href="roles.php?delete=<?= (int)$r['id'] ?>"
                           onclick="return confirm('تأكيد حذف الدور؟');">
                          <i class="fa fa-trash"></i> حذف
                        </a>
                      </td>
                    </tr>
                  <?php } ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="card">
            <div class="card-header"><b><?= $edit_role ? 'تعديل دور' : 'إضافة دور جديد' ?></b></div>
            <div class="card-body">
              <form method="post" class="form-compact labels-left">
                <input type="hidden" name="rid" value="<?= (int)($edit_role['id'] ?? 0) ?>">

                <div class="form-group">
                  <label>اسم الدور</label>
                  <input type="text" class="form-control" name="name"
                         value="<?= h($edit_role['name'] ?? '') ?>"
                         placeholder="مثال: مدير / محاسب / دعم فني">
                </div>

                <hr>
                <h6 class="mb-2"><b>الصلاحيات</b></h6>
                <div class="ua-permission-groups">
                  <?php foreach($PERMISSION_GROUPS as $group){ ?>
                    <fieldset class="ua-permission-group">
                      <legend><?= h($group['label'] ?? '') ?></legend>
                      <div class="row">
                        <?php foreach((array)($group['permissions'] ?? []) as $key=>$label){ ?>
                          <div class="col-md-6 mb-2">
                            <label class="d-flex align-items-center ua-u-gap-8 ua-cursor-pointer">
                              <input type="checkbox" name="perms[]" value="<?= h($key) ?>"
                                <?= function_exists('ua_permission_array_has') && ua_permission_array_has($edit_perms,$key) ? 'checked' : '' ?>>
                              <span><?= h($label) ?></span>
                            </label>
                          </div>
                        <?php } ?>
                      </div>
                    </fieldset>
                  <?php } ?>
                </div>

                <div class="mt-3">
                  <button class="btn btn-success" name="save_role">
                    <i class="fa fa-save"></i> حفظ
                  </button>
                  <?php if($edit_role){ ?>
                    <a class="btn btn-secondary" href="roles.php"><i class="fa fa-plus"></i> دور جديد</a>
                  <?php } ?>
                </div>

              </form>
            </div>
          </div>
        </div>

      </div>

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

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