<?php
// ============================================================
// admin/create_clerk.php — إنشاء حساب أمين ضبط (مدير النظام)
// ============================================================
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

define('BASE', '../');
requireRole('admin', '../index.php');

$user  = currentUser();
$error = '';
$success = '';
$created = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email     = trim($_POST['email']     ?? '');
    $phone     = trim($_POST['phone']     ?? '');
    $court     = trim($_POST['court']     ?? '');
    $password  = $_POST['password']        ?? '';
    $password2 = $_POST['password2']       ?? '';
    $status    = $_POST['status']          ?? 'active';
    $notes     = trim($_POST['notes']     ?? '');

    if (!$full_name || !$email || !$password) {
        $error = 'يرجى ملء جميع الحقول الإلزامية (الاسم، البريد، كلمة المرور)';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'البريد الإلكتروني غير صالح';
    } elseif (strlen($password) < 8) {
        $error = 'كلمة المرور يجب أن تكون 8 أحرف على الأقل';
    } elseif ($password !== $password2) {
        $error = 'كلمتا المرور غير متطابقتين';
    } else {
        $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $check->execute([$email]);
        if ($check->fetch()) {
            $error = 'هذا البريد الإلكتروني مستخدم بالفعل';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare(
                "INSERT INTO users (full_name, email, phone, password, role, status, created_at)
                 VALUES (?, ?, ?, ?, 'clerk', ?, NOW())"
            );
            $stmt->execute([$full_name, $email, $phone, $hash, $status]);
            $newId = $pdo->lastInsertId();

            // Audit log if function exists
            if (function_exists('auditLog')) {
                auditLog($user['id'], 'create_clerk', 'user', $newId,
                    "إنشاء حساب أمين ضبط: $full_name ($email)" . ($notes ? " | ملاحظات: $notes" : ''));
            }

            $success = "تم إنشاء حساب أمين الضبط بنجاح!";
            $created = [
                'name'     => $full_name,
                'email'    => $email,
                'password' => $password,
                'court'    => $court,
                'status'   => $status,
            ];
        }
    }
}

// Stats
try {
    $totalClerks  = $pdo->query("SELECT COUNT(*) FROM users WHERE role='clerk'")->fetchColumn();
    $activeClerks = $pdo->query("SELECT COUNT(*) FROM users WHERE role='clerk' AND status='active'")->fetchColumn();
    $monthClerks  = $pdo->query("SELECT COUNT(*) FROM users WHERE role='clerk' AND MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())")->fetchColumn();
} catch (Exception $e) {
    $totalClerks = $activeClerks = $monthClerks = '—';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إنشاء حساب أمين ضبط</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Amiri:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/style.css">
<script>const BASE_URL = '../';</script>
<style>
/* ── Page-specific styles ── */
.cc-page { max-width: 820px; margin: 0 auto; }

.cc-stats { display: grid; grid-template-columns: repeat(3,1fr); gap: 16px; margin-bottom: 24px; }
.cc-stat  { background: var(--white); border: 1px solid var(--slate-200); border-radius: var(--radius-md);
            padding: 16px 20px; display: flex; align-items: center; gap: 14px; }
.cc-stat-ico { width: 44px; height: 44px; border-radius: var(--radius-md);
               display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.ico-gold  { background: var(--gold-100); color: #92400E; }
.ico-green { background: var(--green-100); color: #15803D; }
.ico-blue  { background: var(--blue-100); color: #1D4ED8; }
.cc-stat-num { font-size: 1.6rem; font-weight: 800; color: var(--navy-800); line-height: 1; }
.cc-stat-lbl { font-size: .75rem; color: var(--slate-500); margin-top: 2px; }

.cc-info { background: var(--gold-100); border: 1px solid var(--gold-300); border-radius: var(--radius-md);
           padding: 14px 18px; margin-bottom: 20px; }
.cc-info-row { display: flex; align-items: flex-start; gap: 8px; font-size: .82rem;
               color: #78350F; padding: 3px 0; line-height: 1.5; }
.cc-info-row svg { flex-shrink: 0; margin-top: 2px; }

/* Form sections */
.f-section-title { display: flex; align-items: center; gap: 8px; font-size: .78rem; font-weight: 700;
                   color: var(--slate-500); text-transform: uppercase; letter-spacing: .6px;
                   padding-bottom: 10px; border-bottom: 1px solid var(--slate-200); margin-bottom: 18px; }
.f-section-title:not(:first-child) { margin-top: 28px; }
.f-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.f-grid-1 { display: grid; grid-template-columns: 1fr; gap: 16px; }

/* Password strength */
.pw-strength { display: flex; gap: 4px; margin-top: 6px; height: 3px; }
.pw-bar { flex: 1; border-radius: 2px; background: var(--slate-200); transition: background .3s; }
.pw-bar.weak   { background: var(--red-500); }
.pw-bar.fair   { background: var(--amber-500); }
.pw-bar.strong { background: var(--green-500); }

/* Success banner */
.cc-success { background: var(--green-100); border: 1px solid #86EFAC; border-radius: var(--radius-lg);
              padding: 28px; text-align: center; margin-bottom: 24px; }
.cc-success-ico { font-size: 3rem; margin-bottom: 10px; }
.cc-success-title { font-family: var(--font-serif); font-size: 1.35rem; font-weight: 700;
                    color: #14532D; margin-bottom: 6px; }
.cc-success-sub { font-size: .85rem; color: #166534; margin-bottom: 18px; }
.cc-cred { background: white; border: 1px solid #86EFAC; border-radius: var(--radius-md);
           padding: 14px 18px; font-size: .82rem; color: var(--navy-800); text-align: right;
           max-width: 340px; margin: 0 auto; }
.cc-cred-row { display: flex; justify-content: space-between; padding: 4px 0;
               border-bottom: 1px solid #DCFCE7; }
.cc-cred-row:last-child { border: none; }
.cc-cred-lbl { color: var(--slate-500); }
.cc-cred-val { font-weight: 700; font-family: monospace; letter-spacing: .3px; }

/* Error alert */
.cc-error { background: var(--red-100); border: 1px solid #FCA5A5; border-radius: var(--radius-md);
            padding: 14px 16px; display: flex; align-items: flex-start; gap: 10px;
            font-size: .85rem; color: #7F1D1D; margin-bottom: 20px; }

/* Gen button */
.btn-gen { background: var(--slate-100); border: 1px solid var(--slate-200); border-radius: var(--radius-sm);
           padding: 8px 14px; font-size: .8rem; font-family: var(--font-main); color: var(--navy-700);
           cursor: pointer; display: flex; align-items: center; gap: 6px; transition: var(--transition);
           width: 100%; justify-content: center; }
.btn-gen:hover { background: var(--gold-100); border-color: var(--gold-300); color: #78350F; }

/* pw toggle */
.pw-wrap { position: relative; }
.pw-toggle { position: absolute; left: 10px; top: 50%; transform: translateY(-50%);
             background: none; border: none; cursor: pointer; color: var(--slate-500);
             font-size: .85rem; padding: 2px; }
.pw-toggle:hover { color: var(--navy-700); }
.pw-inp { padding-left: 34px !important; }

@media(max-width:640px){
  .cc-stats { grid-template-columns: 1fr; }
  .f-grid-2 { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<?php require_once __DIR__ . '/../includes/sidebar.php'; ?>

<div class="main-content">
  <div class="page-header">
    <div>
      <div class="breadcrumb">
        <a href="index.php">الرئيسية</a>
        <span>›</span>
        <a href="users.php">المستخدمون</a>
        <span>›</span>
        <span>إنشاء أمين ضبط</span>
      </div>
      <div class="page-title">
        <div class="title-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <line x1="19" y1="8" x2="19" y2="14"/>
            <line x1="22" y1="11" x2="16" y2="11"/>
          </svg>
        </div>
        إنشاء حساب أمين ضبط جديد
      </div>
    </div>
    <a href="users.php" class="btn btn-outline">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
        <line x1="19" y1="12" x2="5" y2="12"/>
        <polyline points="12 19 5 12 12 5"/>
      </svg>
      العودة للمستخدمين
    </a>
  </div>

  <div class="page-body fade-in cc-page">

    <!-- STATS -->
    <div class="cc-stats">
      <div class="cc-stat">
        <div class="cc-stat-ico ico-gold">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20">
            <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
          </svg>
        </div>
        <div>
          <div class="cc-stat-num"><?= $totalClerks ?></div>
          <div class="cc-stat-lbl">إجمالي أمناء الضبط</div>
        </div>
      </div>
      <div class="cc-stat">
        <div class="cc-stat-ico ico-green">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20">
            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
          </svg>
        </div>
        <div>
          <div class="cc-stat-num"><?= $activeClerks ?></div>
          <div class="cc-stat-lbl">الحسابات النشطة</div>
        </div>
      </div>
      <div class="cc-stat">
        <div class="cc-stat-ico ico-blue">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20">
            <rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/>
            <line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
          </svg>
        </div>
        <div>
          <div class="cc-stat-num"><?= $monthClerks ?></div>
          <div class="cc-stat-lbl">أُضيفوا هذا الشهر</div>
        </div>
      </div>
    </div>

    <!-- INFO BOX -->
    <div class="cc-info">
      <div class="cc-info-row">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        أمناء الضبط لا يملكون رابط تسجيل ذاتي — يجب إنشاء حساباتهم يدوياً من هنا
      </div>
      <div class="cc-info-row">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        احتفظ ببيانات الدخول وسلّمها لأمين الضبط مباشرة بعد الإنشاء
      </div>
    </div>

    <!-- SUCCESS BANNER -->
    <?php if ($success): ?>
    <div class="cc-success">
      <div class="cc-success-ico">✅</div>
      <div class="cc-success-title"><?= $success ?></div>
      <div class="cc-success-sub">احتفظ ببيانات الدخول أدناه وسلّمها لأمين الضبط</div>
      <div class="cc-cred">
        <div class="cc-cred-row">
          <span class="cc-cred-lbl">الاسم</span>
          <span class="cc-cred-val"><?= htmlspecialchars($created['name']) ?></span>
        </div>
        <div class="cc-cred-row">
          <span class="cc-cred-lbl">البريد</span>
          <span class="cc-cred-val"><?= htmlspecialchars($created['email']) ?></span>
        </div>
        <div class="cc-cred-row">
          <span class="cc-cred-lbl">كلمة المرور</span>
          <span class="cc-cred-val"><?= htmlspecialchars($created['password']) ?></span>
        </div>
        <?php if ($created['court']): ?>
        <div class="cc-cred-row">
          <span class="cc-cred-lbl">المحكمة</span>
          <span class="cc-cred-val"><?= htmlspecialchars($created['court']) ?></span>
        </div>
        <?php endif; ?>
        <div class="cc-cred-row">
          <span class="cc-cred-lbl">الحالة</span>
          <span class="cc-cred-val"><?= $created['status'] === 'active' ? 'نشط ✓' : 'معلق' ?></span>
        </div>
      </div>
      <div style="display:flex;gap:10px;justify-content:center;margin-top:18px;flex-wrap:wrap;">
        <a href="create_clerk.php" class="btn btn-primary">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          إنشاء حساب آخر
        </a>
        <a href="users.php" class="btn btn-outline">عرض المستخدمين</a>
      </div>
    </div>
    <?php endif; ?>

    <!-- FORM CARD -->
    <div class="card">
      <div class="card-header">
        <div class="card-title">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <line x1="19" y1="8" x2="19" y2="14"/>
            <line x1="22" y1="11" x2="16" y2="11"/>
          </svg>
          بيانات الحساب الجديد
        </div>
        <span class="text-muted" style="font-size:.78rem">الحقول المميزة بـ * إلزامية</span>
      </div>
      <div class="card-body">

        <?php if ($error): ?>
        <div class="cc-error">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
          <span><?= htmlspecialchars($error) ?></span>
        </div>
        <?php endif; ?>

        <form method="POST" id="clerkForm" novalidate>

          <!-- ── SECTION 1: Personal ── -->
          <div class="f-section-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
            البيانات الشخصية
          </div>
          <div class="f-grid-2">
            <div class="form-group">
              <label class="form-label">الاسم الكامل <span class="required">*</span></label>
              <input type="text" name="full_name" class="form-control"
                     value="<?= htmlspecialchars($_POST['full_name'] ?? '') ?>"
                     placeholder="أحمد بن يوسف" required>
            </div>
            <div class="form-group">
              <label class="form-label">رقم الهاتف</label>
              <input type="tel" name="phone" class="form-control"
                     value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>"
                     placeholder="0661234567">
            </div>
            <div class="form-group">
              <label class="form-label">البريد الإلكتروني <span class="required">*</span></label>
              <input type="email" name="email" class="form-control"
                     value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                     placeholder="clerk@court.dz" required>
            </div>
            <div class="form-group">
              <label class="form-label">المحكمة</label>
              <select name="court" class="form-control">
                <option value="">— اختر المحكمة (اختياري) —</option>
                <?php
                $courts = [
                  'محكمة الجزائر المدنية','محكمة الجزائر الجنائية','محكمة بابا حسن',
                  'محكمة الحراش','محكمة وهران','محكمة قسنطينة','محكمة عنابة',
                  'محكمة تيزي وزو','محكمة البليدة','محكمة سطيف','محكمة باتنة',
                  'محكمة بجاية','محكمة المدية','محكمة تلمسان','محكمة سكيكدة',
                ];
                $selectedCourt = $_POST['court'] ?? '';
                foreach ($courts as $c): ?>
                <option value="<?= $c ?>" <?= $selectedCourt === $c ? 'selected' : '' ?>><?= $c ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <!-- ── SECTION 2: Account ── -->
          <div class="f-section-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
            بيانات الحساب
          </div>
          <div class="f-grid-2">
            <div class="form-group">
              <label class="form-label">كلمة المرور <span class="required">*</span></label>
              <div class="pw-wrap">
                <input type="password" name="password" id="pw1" class="form-control pw-inp"
                       placeholder="••••••••" required oninput="checkStrength(this.value)">
                <button type="button" class="pw-toggle" onclick="togglePw('pw1',this)">👁</button>
              </div>
              <div class="pw-strength">
                <div class="pw-bar" id="bar1"></div>
                <div class="pw-bar" id="bar2"></div>
                <div class="pw-bar" id="bar3"></div>
                <div class="pw-bar" id="bar4"></div>
              </div>
              <div class="form-hint">8 أحرف على الأقل، مع أرقام وأحرف كبيرة</div>
            </div>
            <div class="form-group">
              <label class="form-label">تأكيد كلمة المرور <span class="required">*</span></label>
              <div class="pw-wrap">
                <input type="password" name="password2" id="pw2" class="form-control pw-inp"
                       placeholder="••••••••" required>
                <button type="button" class="pw-toggle" onclick="togglePw('pw2',this)">👁</button>
              </div>
              <div class="form-hint">أعد كتابة كلمة المرور للتأكيد</div>
            </div>
            <div class="form-group">
              <label class="form-label">توليد تلقائي</label>
              <button type="button" class="btn-gen" onclick="generatePw()">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 014-4h14M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 01-4 4H3"/></svg>
                توليد كلمة مرور آمنة
              </button>
              <div class="form-hint">يملأ كلا الحقلين تلقائياً</div>
            </div>
            <div class="form-group">
              <label class="form-label">الحالة الأولية</label>
              <select name="status" class="form-control">
                <option value="active" <?= ($_POST['status'] ?? 'active') === 'active' ? 'selected' : '' ?>>نشط — يمكنه الدخول فوراً</option>
                <option value="inactive" <?= ($_POST['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>معلق — بانتظار التفعيل</option>
              </select>
            </div>
          </div>

          <!-- ── SECTION 3: Notes ── -->
          <div class="f-section-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
            ملاحظات (اختياري)
          </div>
          <div class="f-grid-1">
            <div class="form-group">
              <textarea name="notes" class="form-control" rows="3" style="resize:vertical"
                        placeholder="ملاحظات خاصة بهذا الحساب..."><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
              <div class="form-hint">تُحفظ في سجل التدقيق</div>
            </div>
          </div>

          <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-top:8px;padding-top:20px;border-top:1px solid var(--slate-200);">
            <span style="font-size:.78rem;color:var(--slate-500);display:flex;align-items:center;gap:5px;">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
              كلمات المرور مُشفَّرة بـ bcrypt
            </span>
            <div style="display:flex;gap:10px;">
              <a href="users.php" class="btn btn-outline">إلغاء</a>
              <button type="submit" class="btn btn-primary" id="submitBtn">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
                إنشاء الحساب
              </button>
            </div>
          </div>

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

  </div><!-- /page-body -->
</div><!-- /main-content -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.29.1/feather.min.js"></script>
<script src="../assets/js/app.js"></script>
<script src="../public/assets/js/i18n.js"></script>
<script>
// Lang switcher for admin pages
(function(){
  var lang = localStorage.getItem('kadiyati_lang') || 'ar';
  // Add lang buttons to topbar if present
  var topbar = document.querySelector('.topbar-actions, .page-header');
  if (topbar) {
    var btnGroup = document.createElement('div');
    btnGroup.style = 'display:flex;gap:4px;margin-right:8px;';
    ['ar','fr','en'].forEach(function(l){
      var b = document.createElement('button');
      b.textContent = l === 'ar' ? 'ع' : l.toUpperCase();
      b.style = 'font-size:11px;padding:4px 10px;border-radius:6px;border:1px solid #ccc;background:'+(lang===l?'rgba(201,168,76,.2)':'#fff')+';cursor:pointer;font-family:Cairo,sans-serif;font-weight:600';
      b.onclick = function(){ applyLang(l); };
      btnGroup.appendChild(b);
    });
    topbar.insertBefore(btnGroup, topbar.firstChild);
  }
  if(typeof initI18n==='function') initI18n();
})();

function togglePw(id, btn) {
  const inp = document.getElementById(id);
  const visible = inp.type === 'password';
  inp.type = visible ? 'text' : 'password';
  btn.textContent = visible ? '🙈' : '👁';
}

function checkStrength(v) {
  const bars = ['bar1','bar2','bar3','bar4'].map(id => document.getElementById(id));
  bars.forEach(b => b.className = 'pw-bar');
  if (!v.length) return;
  let score = 0;
  if (v.length >= 8)  score++;
  if (/[A-Z]/.test(v)) score++;
  if (/[0-9]/.test(v)) score++;
  if (/[^A-Za-z0-9]/.test(v)) score++;
  const cls = score <= 1 ? 'weak' : score === 2 ? 'fair' : 'strong';
  bars.slice(0, score).forEach(b => b.classList.add(cls));
}

function generatePw() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789@#$!';
  let pw = '';
  for (let i = 0; i < 12; i++) pw += chars[Math.floor(Math.random() * chars.length)];
  document.getElementById('pw1').value = pw;
  document.getElementById('pw2').value = pw;
  document.getElementById('pw1').type = 'text';
  document.getElementById('pw2').type = 'text';
  checkStrength(pw);
}

// Prevent double-submit
document.getElementById('clerkForm').addEventListener('submit', function() {
  const btn = document.getElementById('submitBtn');
  btn.disabled = true;
  btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg> جاري الإنشاء...';
});
</script>
</body>
</html>