<?php
// users_add.php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

if (strtoupper((string)($_SESSION['role'] ?? '')) !== 'OWNER') {
    http_response_code(403);
    exit('غير مصرح');
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function h($s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

$name     = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$logo     = "https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png";
$branchId = (int)($_SESSION['branch_id'] ?? 1);

$currentBranchName = 'أبوظبي';
try {
    $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
    $st->execute([$branchId]);
    $currentBranchName = (string)($st->fetchColumn() ?: 'أبوظبي');
} catch (Throwable $e) {
    $currentBranchName = 'أبوظبي';
}

$msg = '';
$err = '';

$branches = [];
try {
    $st = $pdo->query("SELECT id, name_ar FROM branches ORDER BY id ASC");
    $branches = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $branches = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $emp_name = trim((string)($_POST['name'] ?? ''));
    $username = trim((string)($_POST['username'] ?? ''));
    $phone    = trim((string)($_POST['phone'] ?? ''));
    $email    = trim((string)($_POST['email'] ?? ''));
    $pass     = (string)($_POST['password'] ?? '');

    $uRole    = strtoupper(trim((string)($_POST['role'] ?? 'STAFF')));
    $status   = strtolower(trim((string)($_POST['status'] ?? 'active')));
    $branchIn = trim((string)($_POST['branch_id'] ?? 'NULL'));

    if ($emp_name === '' || $username === '' || $pass === '' || $phone === '') {
        $err = 'الاسم + اسم المستخدم + كلمة المرور + رقم الهاتف مطلوبة';
    } else {
        $allowedRoles = ['ADMIN', 'STAFF', 'CLIENT'];
        if (!in_array($uRole, $allowedRoles, true)) {
            $uRole = 'STAFF';
        }

        $allowedStatus = ['active', 'inactive'];
        if (!in_array($status, $allowedStatus, true)) {
            $status = 'active';
        }

        $branchVal = null;
        if ($branchIn !== '' && strtoupper($branchIn) !== 'NULL') {
            $branchVal = (int)$branchIn;
        }

        if ($branchVal === null || $branchVal <= 0) {
            $branchVal = 1;
        }

        $hash = password_hash($pass, PASSWORD_DEFAULT);
        $jobTitle = ($uRole === 'ADMIN') ? 'مدير' : (($uRole === 'CLIENT') ? 'عميل' : 'موظف');
        $empStatus = ($status === 'active') ? 'ACTIVE' : 'INACTIVE';

        try {
            $pdo->beginTransaction();

            /* تحقق من تكرار users */
            $sqlUserCheck = "SELECT id FROM users WHERE username = ?";
            $userCheckArgs = [$username];

            if ($email !== '') {
                $sqlUserCheck .= " OR email = ?";
                $userCheckArgs[] = $email;
            }

            $sqlUserCheck .= " LIMIT 1";

            $stCheckUser = $pdo->prepare($sqlUserCheck);
            $stCheckUser->execute($userCheckArgs);

            if ($stCheckUser->fetch()) {
                throw new RuntimeException('اسم المستخدم أو الإيميل مستخدم مسبقًا');
            }

            /* تحقق من تكرار الهاتف في employees */
            $stCheckPhone = $pdo->prepare("SELECT id FROM employees WHERE phone = ? LIMIT 1");
            $stCheckPhone->execute([$phone]);

            if ($stCheckPhone->fetch()) {
                throw new RuntimeException('رقم الهاتف مستخدم مسبقًا');
            }

            /* 1) إضافة المستخدم إلى users */
            $stUser = $pdo->prepare("
                INSERT INTO users (username, name, email, password, role, status, branch_id)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stUser->execute([
                $username,
                $emp_name,
                ($email !== '' ? $email : null),
                $hash,
                $uRole,
                $status,
                $branchVal
            ]);

            $newUserId = (int)$pdo->lastInsertId();
            if ($newUserId <= 0) {
                throw new RuntimeException('تعذر إنشاء المستخدم');
            }

            /* 2) إضافة الموظف إلى employees حسب بنية جدولك الحالية */
            $stEmp = $pdo->prepare("
                INSERT INTO employees (
                    branch_id,
                    full_name,
                    name,
                    phone,
                    email,
                    job_title,
                    status,
                    hired_at,
                    user_id
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $stEmp->execute([
                $branchVal,
                $emp_name,
                $emp_name,
                $phone,
                ($email !== '' ? $email : null),
                $jobTitle,
                $empStatus,
                date('Y-m-d'),
                $newUserId
            ]);

            $pdo->commit();
            $msg = 'تم إضافة الموظف بنجاح وظهر في users و employees';

        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $err = 'تعذر الإضافة: ' . $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>إضافة موظف</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --hlg-dark:#0f2a33;
    --hlg-dark2:#0b2230;
    --hlg-teal:#006a7a;
    --hlg-gold:#d4af37;
    --bg:#f4f7f8;
    --card:#ffffff;
    --muted:#6b7a7f;
    --border:#e6edef;
    --radius:18px;
    --sidebar-w:280px;
    --topbar-h:68px;
  }

  *{box-sizing:border-box}
  body{
    margin:0;
    font-family:"Tajawal",system-ui,-apple-system,Segoe UI,Arial;
    background: linear-gradient(180deg, #ffffff, var(--bg));
    color:#0b1b1f;
  }
  a{color:inherit;text-decoration:none}

  .app{min-height:100vh;display:grid;grid-template-columns: var(--sidebar-w) 1fr;}

  .sidebar{
    background: linear-gradient(180deg, #0b2230, #0a1d28);
    color:#eaf5f7;
    padding:18px 16px;
    position:sticky;top:0;height:100vh;overflow:auto;
  }
  .brand{
    display:flex;align-items:center;justify-content:space-between;gap:12px;
    padding:10px 10px 16px;border-bottom:1px solid rgba(255,255,255,.08);
    margin-bottom:14px;
  }
  .brand-left{display:flex;align-items:center;gap:12px;min-width:0;}
  .brand-logo{
    width:46px;height:46px;border-radius:14px;
    background: rgba(255,255,255,.10);
    border:1px solid rgba(255,255,255,.14);
    display:flex;align-items:center;justify-content:center;overflow:hidden;
  }
  .brand-logo img{width:100%;height:100%;object-fit:contain;padding:8px}
  .brand-title{display:flex;flex-direction:column;gap:2px;min-width:0;}
  .brand-title .name{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
  .brand-title .sub{font-size:12.5px;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}

  .nav{margin-top:10px;display:grid;gap:6px;}
  .nav a{
    display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:11px 12px;border-radius:14px;color:#eaf5f7;border:1px solid transparent;
    transition:.15s ease;
  }
  .nav a:hover{background: rgba(255,255,255,.06);border-color: rgba(255,255,255,.08);}
  .nav a.active{background: rgba(255,255,255,.08);border-color: rgba(255,255,255,.10);}
  .nav .label{font-weight:700;opacity:.95;}
  .pill{
    font-size:12px;color:#d7f3f7;background: rgba(255,255,255,.08);
    border:1px solid rgba(255,255,255,.10);padding:4px 8px;border-radius:999px;opacity:.9;
  }

  .logout{
    margin-top:16px;padding-top:14px;border-top:1px solid rgba(255,255,255,.08);
    display:flex;gap:10px;align-items:center;justify-content:space-between;opacity:.95;
  }
  .logout a{
    display:inline-flex;align-items:center;gap:8px;padding:10px 12px;border-radius:14px;
    background: rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.10);
  }

  .main{min-width:0;padding:18px 22px 26px;}

  .topbar{
    height: var(--topbar-h);
    display:flex;align-items:center;justify-content:space-between;gap:14px;
    padding:10px 12px;background:#fff;border:1px solid var(--border);
    border-radius: var(--radius);box-shadow: 0 10px 25px rgba(0,0,0,.05);
    position:sticky;top:12px;z-index:10;
  }
  .top-left{display:flex;align-items:center;gap:10px;}

  .branch-switch{ position:relative; display:inline-flex; align-items:center; }
  .branch-btn{
    display:flex; align-items:center; gap:8px;
    background:#fff;border:1px solid var(--border);border-radius:999px;padding:10px 12px;
    cursor:pointer;font-family:inherit;box-shadow:0 8px 18px rgba(0,0,0,.06);
  }
  .branch-dot{ width:8px;height:8px;border-radius:50%;background: var(--hlg-teal);box-shadow:0 0 0 4px rgba(0,106,122,.12); }
  .branch-name{ font-weight:600; color:#0b1b1f; }
  .branch-caret{ opacity:.7; font-size:14px; }

  .branch-menu{
    position:absolute;top: calc(100% + 8px);right:0;min-width:170px;
    background:#fff;border:1px solid var(--border);border-radius:14px;box-shadow:0 18px 40px rgba(0,0,0,.12);
    padding:8px;display:none;z-index:999;
  }
  .branch-choice{
    width:100%;text-align:right;background:transparent;border:0;padding:10px;border-radius:10px;
    cursor:pointer;font-family:inherit;font-weight:800;
  }
  .branch-choice:hover{ background:#f4f7f8; }

  .page-head{
    margin:18px 6px 14px;
    display:flex;align-items:flex-end;justify-content:space-between;gap:12px;flex-wrap:wrap;
  }
  .titleWrap{display:flex;flex-direction:column;gap:2px;}
  .pageTitle{font-size:30px;font-weight:900;color:#0f2a33;margin:0;}
  .pageSub{color: var(--muted);font-size:14px;}

  .card{
    margin-top:12px;
    background:#fff;border:1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: 0 10px 25px rgba(0,0,0,.05);
    overflow:hidden;
  }
  .head{
    padding:14px 16px;border-bottom:1px solid var(--border);
    display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;
  }
  .sub{color:var(--muted);font-size:13px}

  form.main-form{padding:14px 16px;display:grid;gap:12px}
  .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
  @media(max-width:680px){.row{grid-template-columns:1fr}}

  label{display:block;font-weight:800;margin-bottom:6px}
  input,select{
    width:100%;height:44px;border-radius:14px;border:1px solid var(--border);
    padding:0 12px;background:#fbfeff;outline:none
  }
  input:focus,select:focus{border-color:rgba(0,106,122,.45);box-shadow:0 0 0 4px rgba(0,106,122,.12);background:#fff}

  .actions{display:flex;gap:10px;align-items:center;justify-content:flex-start;flex-wrap:wrap;margin-top:6px}
  button{
    height:44px;border-radius:14px;border:0;padding:0 14px;cursor:pointer;font-weight:900;
    background:linear-gradient(90deg,var(--hlg-gold),#caa52f);color:#1d1600
  }
  a.btn{
    height:44px;display:inline-flex;align-items:center;justify-content:center;
    border-radius:14px;border:1px solid var(--border);padding:0 14px;background:#fff
  }
  .msg{padding:10px 16px;border-bottom:1px solid var(--border);font-weight:800}
  .ok{background:#ecfdf5;color:#065f46}
  .bad{background:#fef2f2;color:#991b1b}

  @media (max-width: 980px){
    .app{grid-template-columns: 1fr;}
    .sidebar{position:relative;height:auto;}
  }
</style>
</head>

<body>
<div class="app">
  <aside class="sidebar">
    <div class="brand">
      <div class="brand-left">
        <div class="brand-logo"><img src="<?=h($logo)?>" alt="HLG"></div>
        <div class="brand-title">
          <div class="name">مجموعة حمدان القانونية</div>
          <div class="sub">بوابة إدارة الأعمال القانونية</div>
        </div>
      </div>
    </div>

    <nav class="nav">
      <a class="<?= basename($_SERVER['PHP_SELF'])==='dashboard.php'?'active':''; ?>" href="dashboard.php">
        <span class="left"><span class="label">الرئيسية</span></span>
        <span class="pill">لوحة التحكم</span>
      </a>
      <a class="<?= basename($_SERVER['PHP_SELF'])==='cases.php'?'active':''; ?>" href="cases.php">
        <span class="left"><span class="label">القضايا</span></span>
        <span class="pill">إدارة</span>
      </a>
      <a class="<?= basename($_SERVER['PHP_SELF'])==='tasks.php'?'active':''; ?>" href="tasks.php">
        <span class="left"><span class="label">المهام</span></span>
        <span class="pill">متابعة</span>
      </a>
      <a href="hr_employee_form.php">
        <span class="left"><span class="label">شؤون الموظفين</span></span>
        <span class="pill">HR</span>
      </a>

      <?php if (in_array($role, ['OWNER','ADMIN'], true)): ?>
        <a class="<?= basename($_SERVER['PHP_SELF'])==='permissions_manage.php'?'active':''; ?>" href="permissions_manage.php">
          <span class="left"><span class="label">الصلاحيات</span></span>
          <span class="pill">تحكم</span>
        </a>
      <?php endif; ?>
    </nav>

    <div class="logout">
      <div style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?=h($name)?></div>
      <a href="logout.php" title="تسجيل الخروج"><span>خروج</span></a>
    </div>
  </aside>

  <main class="main">
    <div class="topbar">
      <div class="top-left">
        <div class="branch-switch">
          <button class="branch-btn" type="button" id="branchBtn" aria-haspopup="true" aria-expanded="false">
            <span class="branch-dot"></span>
            <span class="branch-name"><?=h($currentBranchName)?></span>
            <span class="branch-caret">▾</span>
          </button>

          <div class="branch-menu" id="branchMenu" role="menu" aria-label="Branch menu">
            <form action="branch_switch.php" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="1">
              <button type="submit" class="branch-choice">أبوظبي</button>
            </form>
            <form action="branch_switch.php" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="2">
              <button type="submit" class="branch-choice">دبي</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="page-head">
      <div class="titleWrap">
        <h1 class="pageTitle">إضافة موظف/مستخدم</h1>
        <div class="pageSub">بعد الإضافة سيظهر مباشرة في صفحة الموظفين والحضور والصلاحيات.</div>
      </div>

      <div class="actions">
        <a class="btn" href="permissions_manage.php">إدارة الصلاحيات</a>
      </div>
    </div>

    <section class="card">
      <div class="head">
        <div class="sub">الفرع الحالي (للعرض فقط): <?=h($currentBranchName)?></div>
      </div>

      <?php if($msg!==''): ?><div class="msg ok"><?=h($msg)?></div><?php endif; ?>
      <?php if($err!==''): ?><div class="msg bad"><?=h($err)?></div><?php endif; ?>

      <form method="post" autocomplete="off" class="main-form">
        <div class="row">
          <div>
            <label>الاسم</label>
            <input name="name" required />
          </div>
          <div>
            <label>اسم المستخدم (Username)</label>
            <input name="username" required />
          </div>
        </div>

        <div class="row">
          <div>
            <label>رقم الهاتف</label>
            <input name="phone" required />
          </div>
          <div>
            <label>الإيميل (اختياري)</label>
            <input name="email" type="email" />
          </div>
        </div>

        <div class="row">
          <div>
            <label>كلمة المرور</label>
            <input name="password" type="password" required />
          </div>
          <div></div>
        </div>

        <div class="row">
          <div>
            <label>الدور</label>
            <select name="role">
              <option value="STAFF">STAFF (موظف)</option>
              <option value="ADMIN">ADMIN (مدير)</option>
              <option value="CLIENT">CLIENT (عميل)</option>
            </select>
          </div>

          <div>
            <label>الحالة</label>
            <select name="status">
              <option value="active">active</option>
              <option value="inactive">inactive</option>
            </select>
          </div>
        </div>

        <div class="row">
          <div>
            <label>الفرع</label>
            <select name="branch_id">
              <option value="1">أبوظبي (1)</option>
              <?php foreach($branches as $b): ?>
                <option value="<?= (int)$b['id'] ?>" <?= ((int)$b['id'] === 1 ? 'selected' : '') ?>>
                  <?=h($b['name_ar'])?> (<?= (int)$b['id'] ?>)
                </option>
              <?php endforeach; ?>
            </select>
            <div class="sub" style="margin-top:6px">اختر الفرع الذي سيتبع له الموظف.</div>
          </div>
          <div></div>
        </div>

        <div class="actions">
          <button type="submit">إضافة</button>
          <a class="btn" href="dashboard.php">رجوع للوحة التحكم</a>
        </div>
      </form>
    </section>

  </main>
</div>

<script>
  const branchBtn  = document.getElementById('branchBtn');
  const branchMenu = document.getElementById('branchMenu');

  function closeMenu(){
    if (!branchMenu) return;
    branchMenu.style.display = 'none';
    branchBtn && branchBtn.setAttribute('aria-expanded','false');
  }

  function toggleMenu(){
    if (!branchMenu || !branchBtn) return;
    const isOpen = branchMenu.style.display === 'block';
    branchMenu.style.display = isOpen ? 'none' : 'block';
    branchBtn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
  }

  if (branchBtn && branchMenu){
    branchBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      toggleMenu();
    });

    document.addEventListener('click', closeMenu);
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') closeMenu();
    });
  }
</script>
</body>
</html>