<!doctype html>
<html lang="ar" dir="rtl" data-theme="dim">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>إدارة المستخدمين</title>

  <style>
    /* =========================
       Theme Variables (Default = DIM)
       ========================= */
    :root{ /* default = dim */
      --bg:#121826;
      --surface:#101827;
      --card:#151e30;
      --card2:#0f1a33;

      --text:#e5e7eb;
      --muted:#9ca3af;

      --border:rgba(255,255,255,.10);
      --border2:rgba(255,255,255,.14);
      --shadow:0 18px 40px rgba(0,0,0,.22);

      --primary:#6366f1;
      --primary2:#4f46e5;
      --success:#22c55e;
      --warning:#f59e0b;
      --danger:#ef4444;

      --input:#0b1327;
      --inputBorder:rgba(255,255,255,.12);
      --inputFocus:rgba(99,102,241,.35);

      --tableHead:rgba(255,255,255,.05);
      --rowHover:rgba(99,102,241,.08);
    }

    /* ✅ Dark (أغمق) */
    html[data-theme="dark"]{
      --bg:#070b14;
      --surface:#0b1220;
      --card:#0f172a;
      --card2:#0b1327;
    }

    /* ✅ Light (أبيض صافي مثل التصميم القديم) */
    html[data-theme="light"]{
      --bg:#ffffff;
      --surface:#ffffff;
      --card:#ffffff;
      --card2:#ffffff;

      --text:#111827;
      --muted:#6b7280;

      --border:rgba(17,24,39,.10);
      --border2:rgba(17,24,39,.14);
      --shadow:0 12px 28px rgba(0,0,0,.10);

      --primary:#111827;
      --primary2:#111827;

      --success:#16a34a;
      --warning:#d97706;
      --danger:#dc2626;

      --input:#ffffff;
      --inputBorder:rgba(17,24,39,.14);
      --inputFocus:rgba(17,24,39,.12);

      --tableHead:rgba(17,24,39,.03);
      --rowHover:rgba(17,24,39,.03);
    }

    *{box-sizing:border-box}

    body{
      font-family:Arial, sans-serif;
      margin:0;
      background:var(--bg);
      color:var(--text);
      padding:22px;
    }
    html[data-theme="dim"] body,
    html[data-theme="dark"] body{
      background:linear-gradient(180deg, var(--bg), var(--bg));
    }

    .container{max-width:1280px;margin:0 auto}

    /* =========================
       Header / Bars
       ========================= */
    .pageHeader{
      background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02));
      border:1px solid var(--border);
      border-radius:18px;
      box-shadow:var(--shadow);
      padding:16px 16px 12px;
      margin-bottom:14px;
    }
    html[data-theme="light"] .pageHeader{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
      box-shadow:0 12px 28px rgba(0,0,0,.08);
    }

    .headerTop{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
    .title{font-weight:900;font-size:18px;letter-spacing:.2px}
    .subtitle{color:var(--muted);font-size:13px;margin-top:6px;line-height:1.6}

    .navRow{
      display:flex;gap:8px;flex-wrap:nowrap;overflow:auto;max-width:100%;
      padding-top:10px;padding-bottom:6px;-webkit-overflow-scrolling:touch;align-items:center
    }
    .navRow > *{flex:0 0 auto; white-space:nowrap;}

    /* Buttons */
    .btn{
      padding:10px 12px;border-radius:12px;border:1px solid transparent;
      cursor:pointer;font-weight:900;font-size:13px;line-height:1;
      display:inline-flex;align-items:center;gap:8px;text-decoration:none;
      transition:transform .05s ease, opacity .15s ease, border-color .15s ease;
      user-select:none;
      background:rgba(255,255,255,.03);
      color:var(--text);
      border-color:var(--border2);
    }
    html[data-theme="light"] .btn{
      background:#ffffff;border-color:rgba(17,24,39,.12);
    }
    .btn:active{transform:translateY(1px)}
    .btn:hover{border-color:rgba(255,255,255,.18)}
    html[data-theme="light"] .btn:hover{border-color:rgba(17,24,39,.20)}

    .btnPrimary{
      background:linear-gradient(180deg, var(--primary), var(--primary2));
      color:#fff;border-color:rgba(255,255,255,.10);
    }
    html[data-theme="light"] .btnPrimary{
      background:#111827;color:#fff;border-color:rgba(17,24,39,.12);
    }

    .btnDanger{
      background:rgba(239,68,68,.14);
      color:#fff;border-color:rgba(239,68,68,.35);
    }
    html[data-theme="light"] .btnDanger{
      background:#ffffff;color:#dc2626;border-color:rgba(220,38,38,.25);
    }

    /* Cards */
    .card{
      background:linear-gradient(180deg, rgba(255,255,255,.035), rgba(255,255,255,.02));
      border:1px solid var(--border);
      border-radius:18px;
      box-shadow:var(--shadow);
      padding:16px;
      margin-bottom:14px;
    }
    html[data-theme="light"] .card{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
      box-shadow:0 12px 28px rgba(0,0,0,.08);
    }

    .cardTitle{
      display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;
      margin-bottom:10px;
    }
    .cardTitle h3{margin:0;font-size:15px;font-weight:900}
    .cardHint{color:var(--muted);font-size:12px;font-weight:900}

    /* Alerts */
    .alert{padding:12px;border-radius:14px;border:1px solid;font-weight:900;margin-bottom:14px}
    .alert.err{background:rgba(239,68,68,.14);border-color:rgba(239,68,68,.35);color:#fff}
    .alert.ok{background:rgba(34,197,94,.14);border-color:rgba(34,197,94,.35);color:#fff}
    html[data-theme="light"] .alert.err{color:#991b1b;background:#fef2f2;border-color:#fecaca}
    html[data-theme="light"] .alert.ok{color:#166534;background:#ecfdf3;border-color:#bbf7d0}

    /* Forms */
    label{display:block;font-size:12px;color:var(--muted);font-weight:900;margin-bottom:6px}
    input, select{
      width:100%;
      padding:11px 12px;
      border:1px solid var(--inputBorder);
      border-radius:12px;
      outline:none;
      font-size:13px;
      background:var(--input);
      color:var(--text);
    }
    input:focus, select:focus{
      border-color:rgba(99,102,241,.55);
      box-shadow:0 0 0 3px var(--inputFocus);
    }
    html[data-theme="light"] input:focus,
    html[data-theme="light"] select:focus{
      border-color:rgba(17,24,39,.22);
      box-shadow:0 0 0 3px rgba(17,24,39,.08);
    }

    .grid{
      display:grid;
      grid-template-columns: 1fr 1fr 0.6fr 0.8fr auto;
      gap:10px;
      align-items:end;
    }
    @media (max-width: 980px){
      body{padding:16px}
      .grid{grid-template-columns:1fr 1fr}
    }

    .small{color:var(--muted);font-size:12px;margin-top:8px;font-weight:900}

    /* Table */
    .tableWrap{
      overflow:auto;
      border-radius:14px;
      border:1px solid var(--border);
      background:rgba(0,0,0,.10);
      margin-top:10px;
    }
    html[data-theme="light"] .tableWrap{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
    }

    table{
      width:100%;
      border-collapse:separate;
      border-spacing:0;
      min-width:1180px;
    }
    thead th{
      position:sticky;top:0;z-index:2;
      background:var(--tableHead);
      border-bottom:1px solid var(--border);
      padding:12px 12px;
      font-weight:900;
      font-size:14px;
      white-space:nowrap;
      text-align:right;
    }
    tbody td{
      padding:12px 12px;
      border-bottom:1px solid rgba(255,255,255,.06);
      font-size:13px;
      vertical-align:middle;
    }
    html[data-theme="light"] tbody td{
      border-bottom:1px solid rgba(17,24,39,.08);
    }
    tbody tr:hover td{background:var(--rowHover)}

    .num{font-weight:900}

    .tag{
      display:inline-flex;align-items:center;
      padding:6px 10px;border-radius:999px;border:1px solid var(--border);
      font-weight:900;font-size:12px;background:rgba(255,255,255,.03)
    }
    html[data-theme="light"] .tag{
      background:#ffffff;border-color:rgba(17,24,39,.12)
    }

    .rowActions{
      display:flex;
      gap:8px;
      align-items:center;
      flex-wrap:nowrap;
      white-space:nowrap;
      justify-content:flex-start;
    }
    .pwInput{width:180px}
    .roleSelect{width:150px}

    .btnSm{
      padding:8px 10px;border-radius:12px;
      cursor:pointer;font-weight:900;font-size:12px;
      border:1px solid transparent;
      background:linear-gradient(180deg, var(--primary), var(--primary2));
      color:#fff;
    }
    html[data-theme="light"] .btnSm{
      background:#111827;color:#fff;border-color:rgba(17,24,39,.12);
    }
    .btnSm:hover{opacity:.95}
  </style>

  <!-- ✅ Apply saved theme ASAP (avoid flash) -->
  <script>
    (function(){
      const themes = ["light","dim","dark"];
      const key = "ui_theme";
      const saved = localStorage.getItem(key);
      const t = (saved && themes.includes(saved)) ? saved : "dim";
      document.documentElement.setAttribute("data-theme", t);
    })();
  </script>
</head>

<body>
<div class="container">

  @php
    $role    = auth()->check() ? (auth()->user()->role ?? 'user') : 'user';
    $isAdmin = ($role === 'admin');
    $isSuper = ($role === 'super');
  @endphp

  <!-- ✅ Top Bar -->
  <div class="pageHeader">
    <div class="headerTop">
      <div>
        <div class="title">إدارة المستخدمين</div>
        <div class="subtitle">Admin: إضافة/تعديل/Reset/حذف + تفعيل/إيقاف — Super: تفعيل/إيقاف المستخدم العادي فقط</div>
      </div>

      <div class="navRow">
        <a class="btn btnPrimary" href="{{ route('dashboard.sales') }}">الرئيسية</a>
        <a class="btn" href="{{ route('dashboard.sales') }}">مبيعات الفروع</a>
        <a class="btn" href="{{ route('branches.index') }}">إدارة الفروع</a>

        <button class="btn" type="button" id="themeBtn">🎨 المظهر</button>

        <form method="POST" action="{{ route('logout') }}" style="display:inline">
          @csrf
          <button class="btn btnDanger" type="submit">خروج</button>
        </form>
      </div>
    </div>
  </div>

  @if(session('ok'))
    <div class="alert ok">{{ session('ok') }}</div>
  @endif

  @if($errors->any())
    <div class="alert err">{{ $errors->first() }}</div>
  @endif

  <!-- ✅ Sub Bar (Info Card) -->
  <div class="card">
    <div class="cardTitle">
      <h3>ملاحظات</h3>
      <div class="cardHint">تنبيه مهم</div>
    </div>
    <div class="small" style="margin-top:0">
      
      - كلمة المرور الجديدة لازم تكون 8 أحرف أو أكثر.
    </div>
  </div>

  {{-- ✅ إضافة مستخدم --}}
  @if($isAdmin)
  <div class="card">
    <div class="cardTitle">
      <h3>إضافة مستخدم جديد</h3>
      <div class="cardHint">إنشاء مستخدم جديد</div>
    </div>

    <form method="POST" action="{{ route('users.store') }}">
      @csrf

      <div class="grid">
        <div>
          <label>الاسم</label>
          <input type="text" name="name" value="{{ old('name') }}" required>
        </div>

        <div>
          <label>الإيميل</label>
          <input type="email" name="email" value="{{ old('email') }}" required>
        </div>

        <div>
          <label>الصلاحية</label>
          <select name="role" required>
            @foreach($rolesForCreate as $k => $label)
              <option value="{{ $k }}" @selected(old('role','user') === $k)>{{ $label }}</option>
            @endforeach
          </select>
        </div>

        <div>
          <label>كلمة المرور</label>
          <input type="text" name="password" value="{{ old('password') }}" required placeholder="8 أحرف أو أكثر">
        </div>

        <div style="display:flex;justify-content:flex-end">
          <button class="btnSm" type="submit">إضافة</button>
        </div>
      </div>
    </form>
  </div>
  @endif

  {{-- ✅ القائمة --}}
  <div class="card">
    <div class="cardTitle">
      <h3>قائمة المستخدمين</h3>
      <div class="cardHint">إدارة الصلاحيات وكلمات المرور</div>
    </div>

    <div class="tableWrap">
      <table>
        <thead>
          <tr>
            <th style="width:60px">ID</th>
            <th style="width:180px">الاسم</th>
            <th>الإيميل</th>
            <th style="width:140px">الصلاحية</th>
            <th style="width:120px">الحالة</th>
            <th style="width:260px">تعديل الصلاحية</th>
            <th style="width:320px">اعادة كلمة المرور</th>
            <th style="width:240px">إجراءات</th>
          </tr>
        </thead>
        <tbody>
          @foreach($users as $u)
            <tr>
              <td class="num">{{ $u->id }}</td>
              <td style="font-weight:900">{{ $u->name }}</td>
              <td>{{ $u->email }}</td>
              <td class="num">
                <span class="tag">{{ $roleLabels[$u->role ?? 'user'] ?? ($u->role ?? 'user') }}</span>
              </td>

              {{-- ✅ الحالة --}}
              <td class="num">
                @if(($u->is_active ?? 1) == 1)
                  <span class="tag" style="border-color:rgba(34,197,94,.35)">✅ فعال</span>
                @else
                  <span class="tag" style="border-color:rgba(239,68,68,.35)">⛔ موقوف</span>
                @endif
              </td>

              <td>
                @if(!$isAdmin)
                  <span class="small">—</span>
                @else
                  @if(auth()->id() && (int)auth()->id() === (int)$u->id)
                    <span class="small">لا يمكن تعديل صلاحيتك</span>
                  @elseif(($u->role ?? 'user') === 'admin')
                    <span class="small">Admin (ثابت)</span>
                  @else
                    <form method="POST" action="{{ route('users.updateRole', ['userId' => $u->id]) }}" class="rowActions">
                      @csrf
                      <select name="role" class="roleSelect" required>
                        @foreach($rolesForUpdate as $k => $label)
                          <option value="{{ $k }}" @selected(($u->role ?? 'user') === $k)>{{ $label }}</option>
                        @endforeach
                      </select>
                      <button class="btnSm" type="submit">حفظ</button>
                    </form>
                  @endif
                @endif
              </td>

              <td>
                @if(!$isAdmin)
                  <span class="small">—</span>
                @else
                  <form method="POST" action="{{ route('users.resetPassword', ['userId' => $u->id]) }}" class="rowActions">
                    @csrf
                    <input class="pwInput" type="text" name="new_password" placeholder="كلمة مرور جديدة" required>
                    <button class="btnSm" type="submit">تغيير</button>
                  </form>
                @endif
              </td>

              {{-- ✅ إجراءات: تفعيل/إيقاف + حذف --}}
              <td>
                @php
                  $targetRole = $u->role ?? 'user';
                  $isSelf     = auth()->id() && ((int)auth()->id() === (int)$u->id);

                  $canToggle = false;
                  if(!$isSelf && $targetRole !== 'admin'){
                    if($isAdmin) $canToggle = true;
                    if($isSuper && $targetRole === 'user') $canToggle = true;
                  }

                  $canDelete = ($isAdmin && !$isSelf && $targetRole !== 'admin');
                @endphp

                <div class="rowActions">
                  @if($canToggle)
                   
                   
                    <form method="POST" action="{{ route('users.toggleActive', ['userId' => $u->id]) }}" style="display:inline">
                      @csrf
                     @php $active = ((int)($u->is_active ?? 1) === 1); @endphp

<button type="submit"
  class="btn"
  style="padding:8px 10px;font-size:12px;
         background: {{ $active ? 'rgba(239,68,68,.14)' : 'rgba(34,197,94,.14)' }};
         border-color: {{ $active ? 'rgba(239,68,68,.35)' : 'rgba(34,197,94,.35)' }};
         color:#fff;">
  {{ $active ? 'إيقاف' : 'تفعيل' }}
</button>
                    </form>
                    
                    
                  @else
                    <span class="small">—</span>
                  @endif

                  @if($canDelete)
                    <form method="POST" action="{{ route('users.destroy', ['userId' => $u->id]) }}" style="display:inline"
                          onsubmit="return confirm('تأكيد حذف المستخدم؟');">
                      @csrf
                      <button class="btn btnDanger" type="submit" style="padding:8px 10px;font-size:12px">حذف</button>
                    </form>
                  @endif
                </div>
              </td>
            </tr>
          @endforeach

          @if(count($users) === 0)
            <tr>
              <td colspan="8" style="text-align:center;color:var(--muted);font-weight:900;padding:16px">لا يوجد مستخدمين</td>
            </tr>
          @endif
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
(function(){
  const themes = ["light","dim","dark"];
  const key = "ui_theme";
  const html = document.documentElement;
  const btn = document.getElementById("themeBtn");

  function label(t){
    if(t === "light") return "☀️ فاتح";
    if(t === "dark") return "🌙 داكن";
    return "🌗 مريح";
  }
  function apply(t){
    html.setAttribute("data-theme", t);
    localStorage.setItem(key, t);
    if(btn) btn.textContent = "🎨 " + label(t);
  }

  const saved = localStorage.getItem(key);
  const t = (saved && themes.includes(saved)) ? saved : (html.getAttribute("data-theme") || "dim");
  apply(t);

  if(btn){
    btn.addEventListener("click", function(){
      const cur = html.getAttribute("data-theme") || "dim";
      const idx = themes.indexOf(cur);
      const next = themes[(idx + 1) % themes.length];
      apply(next);
    });
  }
})();
</script>

</body>
</html>
