<?php
declare(strict_types=1);

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

/* ===== DEBUG ===== */
$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

set_exception_handler(function (Throwable $e) use ($debug) {
    http_response_code(500);
    if (!$debug) {
        echo 'HTTP ERROR 500';
        exit;
    }

    echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
    echo "UNCAUGHT EXCEPTION\n";
    echo "Message: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n\n";
    echo $e->getTraceAsString();
    echo "</pre>";
    exit;
});

/* ===== Includes ===== */
require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';
if (file_exists(__DIR__ . '/inc/app_url.php')) {
    require_once __DIR__ . '/inc/app_url.php';
}

/* ===== Auth ===== */
require_login();

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

/* ===== DB ===== */
$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);

$branchId = (int)($_SESSION['branch_id'] ?? 1);

/* ===== CSRF ===== */
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
$csrf = (string)$_SESSION['csrf'];

/* ===== Discover employees columns ===== */
$empCols = [];
try {
    $st = $pdo->query("SHOW COLUMNS FROM `employees`");
    $empCols = $st->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (Throwable $e) {
    $empCols = [];
}

$nameCol   = '';
$emailCol  = in_array('email', $empCols, true) ? 'email' : '';
$userIdCol = in_array('user_id', $empCols, true) ? 'user_id' : '';
$branchCol = in_array('branch_id', $empCols, true) ? 'branch_id' : '';
$statusCol = in_array('status', $empCols, true) ? 'status' : '';

foreach (['full_name', 'name', 'employee_name', 'emp_name', 'first_name'] as $c) {
    if (in_array($c, $empCols, true)) {
        $nameCol = $c;
        break;
    }
}
$popupOk  = '';
$popupErr = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['form_type'] ?? '') === 'popup_message') {
    $token = (string)($_POST['csrf'] ?? '');
    if ($token === '' || !hash_equals($csrf, $token)) {
        $popupErr = 'رمز الحماية غير صالح.';
    } else {
        $popupTitle   = trim((string)($_POST['popup_title'] ?? ''));
        $popupBody    = trim((string)($_POST['popup_body'] ?? ''));
        $popupTarget  = strtoupper(trim((string)($_POST['popup_target'] ?? 'BRANCH')));
        $popupEmpId   = (int)($_POST['popup_employee_id'] ?? 0);
        $popupBranch  = (int)($_POST['popup_branch_id'] ?? $branchId);

        if ($popupTitle === '' || $popupBody === '') {
            $popupErr = 'يرجى إدخال عنوان الرسالة ونصها.';
        } else {
            $targetType       = 'single_branch';
            $targetBranchId   = null;
            $targetEmployeeId = null;

            if ($popupTarget === 'ALL_BRANCHES') {
                $targetType = 'all_branches';
            } elseif ($popupTarget === 'EMPLOYEE') {
                if ($popupEmpId <= 0) {
                    $popupErr = 'يرجى اختيار موظف صحيح.';
                } else {
                    $targetType       = 'employee';
                    $targetEmployeeId = $popupEmpId;
                }
            } else {
                $targetType     = 'single_branch';
                $targetBranchId = $popupBranch > 0 ? $popupBranch : $branchId;
            }

            if ($popupErr === '') {
                try {
                    $st = $pdo->prepare("
                        INSERT INTO owner_popup_messages
                        (title, message, target_type, target_branch_id, target_employee_id, is_active, created_by, created_at)
                        VALUES
                        (:title, :message, :target_type, :target_branch_id, :target_employee_id, 1, :created_by, NOW())
                    ");

                    $st->execute([
                        ':title'              => $popupTitle,
                        ':message'            => $popupBody,
                        ':target_type'        => $targetType,
                        ':target_branch_id'   => $targetBranchId,
                        ':target_employee_id' => $targetEmployeeId,
                        ':created_by'         => (int)($_SESSION['user_id'] ?? 0),
                    ]);

                    $popupOk = 'تم حفظ الرسالة المنبثقة بنجاح.';
                } catch (Throwable $e) {
                    if ($debug) {
                        throw $e;
                    }
                    $popupErr = 'تعذر حفظ الرسالة المنبثقة.';
                }
            }
        }
    }
}
/*
  ===== Scope logic =====
*/
$scope = (string)($_POST['scope'] ?? $_GET['scope'] ?? 'BRANCH');
$scope = strtoupper(trim($scope));
if (!in_array($scope, ['BRANCH', 'ALL_BRANCHES'], true)) {
    $scope = 'BRANCH';
}

/* ===== Load employees ===== */
$employees = [];
$loadError = '';

try {
    if ($nameCol === '') {
        $loadError = 'لم يتم العثور على عمود الاسم داخل employees.';
        $employees = [];
    } else {
        $nameExpr = "COALESCE(NULLIF(e.`$nameCol`,''), CONCAT('موظف #', e.id))";
        $emailExpr = "COALESCE(NULLIF(u.email,''), " . ($emailCol !== '' ? "NULLIF(e.`$emailCol`,'')," : "") . " '')";

        $sql = "SELECT
                  e.id AS emp_id,
                  $nameExpr AS emp_name,
                  $emailExpr AS email,
                  " . ($statusCol !== '' ? "e.`$statusCol` AS status," : "NULL AS status,") . "
                  " . ($branchCol !== '' ? "e.`$branchCol` AS branch_id," : "NULL AS branch_id,") . "
                  " . ($userIdCol !== '' ? "e.`$userIdCol` AS user_id," : "NULL AS user_id,") . "
                  COALESCE(NULLIF(u.role,''),'') AS role
                FROM employees e
                " . ($userIdCol !== '' ? "LEFT JOIN users u ON u.id = e.`$userIdCol`" : "LEFT JOIN users u ON 1=0") . "
                WHERE 1=1";

        $params = [];

        if ($statusCol !== '') {
            $sql .= " AND e.`$statusCol` = 'ACTIVE'";
        }

        if ($branchCol !== '' && $scope === 'BRANCH') {
            $sql .= " AND e.`$branchCol` = :bid";
            $params[':bid'] = $branchId;
        }

        $sql .= " AND ($emailExpr IS NOT NULL AND $emailExpr <> '')";
        $sql .= " ORDER BY emp_name ASC";

        $st = $pdo->prepare($sql);
        $st->execute($params);
        $employees = $st->fetchAll();
    }
} catch (Throwable $e) {
    if ($debug) {
        throw $e;
    }
    $loadError = 'تعذر تحميل الموظفين. جرّب debug=1 لمعرفة السبب.';
    $employees = [];
}

render_layout_start('التواصل مع الموظفين');
?>

<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --gold-soft:rgba(212,175,55,.14);
    --danger:#f87171;
    --danger-soft:rgba(248,113,113,.12);
    --success:#34d399;
    --success-soft:rgba(52,211,153,.12);
    --warning:#fbbf24;
    --warning-soft:rgba(251,191,36,.12);
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .hr-comms-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

  .hr-comms-page *{
    box-sizing:border-box;
  }

  .hr-comms-page .topbar-local{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    backdrop-filter:blur(12px);
    flex-wrap:wrap;
  }

  .hr-comms-page .owner-badge{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 12px;
    font-weight:900;
    color:#fff;
    box-shadow:0 8px 18px rgba(0,0,0,.10);
    backdrop-filter:blur(8px);
  }

  .hr-comms-page .owner-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .hr-comms-page .btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    height:40px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    font-weight:900;
    cursor:pointer;
    text-decoration:none;
    font-family:inherit;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .hr-comms-page .btn:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .hr-comms-page .page-head{
    margin:18px 6px 14px;
  }

  .hr-comms-page .pageTitle{
    margin:0;
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    line-height:1.1;
  }

  .hr-comms-page .pageSub{
    margin-top:6px;
    color:rgba(255,255,255,.72);
    font-size:14px;
    line-height:1.8;
  }

  .hr-comms-page .card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    padding:16px;
    max-width:980px;
    backdrop-filter:blur(12px);
  }

  .hr-comms-page .row{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:12px;
  }

  @media(max-width:820px){
    .hr-comms-page .row{
      grid-template-columns:1fr;
    }
  }

  .hr-comms-page label{
    display:block;
    margin:0 0 6px;
    color:#ffffff;
    font-size:14px;
    font-weight:700;
  }

  .hr-comms-page .input,
  .hr-comms-page textarea,
  .hr-comms-page select{
    width:100%;
    box-sizing:border-box;
    padding:12px 12px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    outline:none;
    font-family:inherit;
  }

  .hr-comms-page textarea{
    min-height:160px;
    resize:vertical;
  }

  .hr-comms-page .input::placeholder,
  .hr-comms-page textarea::placeholder{
    color:rgba(255,255,255,.45);
  }

  .hr-comms-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .hr-comms-page .input:focus,
  .hr-comms-page textarea:focus,
  .hr-comms-page select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 3px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .hr-comms-page .tabs{
    display:flex;
    gap:10px;
    margin:12px 0;
    flex-wrap:wrap;
  }

  .hr-comms-page .tab{
    padding:10px 12px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    cursor:pointer;
    color:#fff;
    font-family:inherit;
    transition:.18s ease;
  }

  .hr-comms-page .tab:hover{
    background:rgba(255,255,255,.08);
  }

  .hr-comms-page .tab.active{
    background:rgba(212,175,55,.12);
    border-color:rgba(212,175,55,.35);
    color:#ffd76a;
    font-weight:900;
    box-shadow:0 0 0 4px rgba(212,175,55,.08);
  }

  .hr-comms-page .box{
    margin-top:12px;
    padding:12px;
    border-radius:14px;
    border:1px dashed rgba(255,255,255,.16);
    background:rgba(255,255,255,.03);
  }

  .hr-comms-page .btns{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:12px;
  }

  .hr-comms-page .btn.secondary{
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
    box-shadow:none;
  }

  .hr-comms-page .btn.secondary:hover{
    background:rgba(255,255,255,.08);
  }

  .hr-comms-page .btn.primary{
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    border-color:rgba(212,175,55,.25);
  }

  .hr-comms-page .msg{
    margin-top:12px;
    display:none;
    padding:12px;
    border-radius:12px;
  }

  .hr-comms-page .msg.ok{
    background:rgba(6,95,70,.18);
    border:1px solid rgba(52,211,153,.24);
    color:#d1fae5;
  }

  .hr-comms-page .msg.err{
    background:rgba(127,29,29,.18);
    border:1px solid rgba(248,113,113,.24);
    color:#fecaca;
  }

  .hr-comms-page .small{
    font-size:12px;
    color:var(--muted);
    margin-top:6px;
    line-height:1.7;
  }

  .hr-comms-page .list{
    max-height:260px;
    overflow:auto;
    padding:8px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.04);
  }

  .hr-comms-page .item{
    display:flex;
    align-items:center;
    gap:10px;
    padding:8px;
    border-radius:10px;
    transition:.18s ease;
  }

  .hr-comms-page .item:hover{
    background:rgba(255,255,255,.05);
  }

  .hr-comms-page .pill{
    font-size:12px;
    padding:4px 8px;
    border-radius:999px;
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
  }

  .hr-comms-page .warn{
    margin-top:12px;
    background:rgba(251,191,36,.12);
    border:1px solid rgba(251,191,36,.26);
    padding:10px;
    border-radius:12px;
    color:#fcd34d;
  }

  .hr-comms-page .footerNote{
    margin-top:18px;
    padding:14px 18px;
    border-radius:16px;
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    backdrop-filter:blur(8px);
    color:rgba(255,255,255,.75);
    font-size:13px;
    max-width:980px;
  }

  .hr-comms-page .footer-inner{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:10px;
  }

  .hr-comms-page .footer-copy{
    color:#ffd76a !important;
    font-weight:700;
    letter-spacing:.3px;
  }

  .hr-comms-page .footer-system{
    font-weight:800;
    color:#d4af37;
    letter-spacing:.5px;
  }

  @media (max-width:700px){
    .hr-comms-page .pageTitle{
      font-size:24px;
    }

    .hr-comms-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }
  }
  .hr-comms-page select option{
  background:#0f2a33;
  color:#fff;
  padding:6px;
  font-weight:700;
}
/* =========================
   FIX SMALL BUTTON
========================= */

.hr-comms-page .btn{
  position:relative;
  overflow:hidden;

  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:10px;

  height:50px;          /* كان 40 */
  padding:0 22px;       /* كان 14 */

  border-radius:999px;
  border:1px solid rgba(212,175,55,.55);

  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1d1600;

  font-weight:900;
  font-size:14px;
  letter-spacing:.3px;

  box-shadow:
    0 15px 30px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);

  transition:.25s ease;
}
/* حل الانكماش */
.hr-comms-page .card{
  width:100% !important;
  max-width:1000px !important;  /* 👈 أكبر من قبل */
}

.hr-comms-page .topbar-local{
  width:100% !important;
}

.hr-comms-page .row{
  width:100%;
}

/* أهم نقطة */
.hr-comms-page .card,
.hr-comms-page .topbar-local{
  overflow:visible !important;  /* 👈 يمنع الانكماش */
}
/* إصلاح الانكماش النهائي */
.hr-comms-page{
  width:100% !important;
  max-width:none !important;
  padding:0 24px 30px !important;
}

.hr-comms-page .card,
.hr-comms-page .popup-card{
  width:100% !important;
  max-width:none !important;
  margin-inline:0 !important;
}

.hr-comms-page .topbar-local{
  width:100% !important;
  max-width:none !important;
}

.hr-comms-page .row{
  grid-template-columns:repeat(2,minmax(0,1fr)) !important;
}

.hr-comms-page .input,
.hr-comms-page textarea,
.hr-comms-page select{
  width:100% !important;
}

@media(max-width:820px){
  .hr-comms-page{
    padding:0 12px 24px !important;
  }

  .hr-comms-page .row{
    grid-template-columns:1fr !important;
  }
}
.hr-comms-page .popup-save-btn{
  background:linear-gradient(135deg,#2563eb,#1e40af) !important;
  color:#fff !important;
  border:1px solid rgba(59,130,246,.4) !important;

  box-shadow:
    0 15px 30px rgba(37,99,235,.35),
    0 0 20px rgba(37,99,235,.25),
    inset 0 2px 6px rgba(255,255,255,.25);
}

.hr-comms-page .popup-save-btn:hover{
  transform:translateY(-2px);
  box-shadow:
    0 18px 35px rgba(37,99,235,.45),
    0 0 30px rgba(37,99,235,.35);
}
button.popup-save-btn,
.popup-card .popup-save-btn{
  background:linear-gradient(135deg,#2563eb,#1e40af) !important;
  color:#ffffff !important;
  border:1px solid rgba(59,130,246,.55) !important;
  box-shadow:
    0 15px 30px rgba(37,99,235,.35),
    0 0 22px rgba(37,99,235,.28) !important;
}

button.popup-save-btn:hover,
.popup-card .popup-save-btn:hover{
  background:linear-gradient(135deg,#1d4ed8,#1e3a8a) !important;
  color:#ffffff !important;
}

</style>
<div class="hr-comms-page">
  <div class="topbar-local">
    <div class="owner-badge">
      <span class="owner-dot"></span>
      <span>OWNER ONLY</span>
    </div>

    <a class="btn" href="<?= h(u('hr_employee_form.php')) ?>">رجوع إلى HR</a>
  </div>

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

  <div class="card">
    <?php if ($loadError !== ''): ?>
      <div class="warn"><?= h($loadError) ?></div>
    <?php endif; ?>

    <div class="tabs">
      <button type="button" class="tab active" data-mode="ALL">إرسال للكل</button>
      <button type="button" class="tab" data-mode="SELECTED">إرسال لموظفين محددين</button>
    </div>

    <form id="mailForm">
      <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
      <input type="hidden" name="mode" id="mode" value="ALL">

      <div class="row">
        <div>
          <label>عنوان الرسالة</label>
          <input class="input" name="subject" required placeholder="مثال: تعميم إداري / اجتماع / تنبيه">
        </div>

        <div>
          <label>نطاق الإرسال</label>
          <select class="input" name="scope" id="scopeSelect">
            <option value="BRANCH" <?= $scope === 'BRANCH' ? 'selected' : '' ?>>هذا الفرع فقط</option>
            <option value="ALL_BRANCHES" <?= $scope === 'ALL_BRANCHES' ? 'selected' : '' ?>>كل الفروع</option>
          </select>
          <div class="small">لتحديث قائمة الموظفين حسب النطاق، سيتم تحديث الصفحة تلقائيًا عند تغيير النطاق.</div>
        </div>
      </div>

      <div style="margin-top:12px">
        <label>نص الرسالة</label>
        <textarea name="body" required placeholder="اكتب الرسالة هنا..."></textarea>
      </div>

      <div class="box" id="selectedBox" style="display:none">
        <label>اختر الموظفين</label>
        <div class="list">
          <?php if (!empty($employees)): ?>
            <?php foreach ($employees as $e): ?>
              <label class="item">
                <input type="checkbox" name="emp_ids[]" value="<?= (int)$e['emp_id'] ?>">
                <span><?= h($e['emp_name'] ?? '') ?></span>
                <span class="pill"><?= h($e['email'] ?? '') ?></span>
              </label>
            <?php endforeach; ?>
          <?php else: ?>
            <div class="small">لا يوجد موظفون لديهم بريد صالح ضمن هذا النطاق.</div>
          <?php endif; ?>
        </div>

        <div class="btns">
          <button type="button" class="btn secondary" id="selectAll">تحديد الكل</button>
          <button type="button" class="btn secondary" id="clearAll">إلغاء التحديد</button>
        </div>
      </div>

      <div class="btns">
        <button type="submit" class="btn primary">إرسال الآن</button>
        <button type="button" class="btn secondary" onclick="location.href='<?= h(u('hr_employee_form.php')) ?>'">رجوع</button>
      </div>

      <div class="msg ok" id="okBox"></div>
      <div class="msg err" id="errBox"></div>
    </form>
  </div>
</div>
  <div class="card popup-card">
  <div class="page-head" style="margin:0 0 14px;">
    <h2 class="pageTitle" style="font-size:24px;">رسائل النظام المنبثقة</h2>
    <div class="pageSub">تظهر للموظف مرة واحدة عند تسجيل الدخول حسب الفرع أو الموظف المحدد.</div>
  </div>

  <?php if ($popupOk !== ''): ?>
    <div class="msg ok" style="display:block;"><?= h($popupOk) ?></div>
  <?php endif; ?>

  <?php if ($popupErr !== ''): ?>
    <div class="msg err" style="display:block;"><?= h($popupErr) ?></div>
  <?php endif; ?>

  <form method="post">
    <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
    <input type="hidden" name="form_type" value="popup_message">

    <div class="row">
      <div>
        <label>عنوان الرسالة المنبثقة</label>
        <input class="input" type="text" name="popup_title" required placeholder="مثال: تنبيه إداري">
      </div>

      <div>
        <label>نوع الاستهداف</label>
        <select class="input" name="popup_target" id="popupTarget">
          <option value="BRANCH">هذا الفرع فقط</option>
          <option value="ALL_BRANCHES">كل الفروع</option>
          <option value="EMPLOYEE">موظف محدد</option>
        </select>
      </div>
    </div>

    <div style="margin-top:12px">
      <label>نص الرسالة</label>
      <textarea name="popup_body" required placeholder="اكتب الرسالة التي ستظهر داخل النظام..."></textarea>
    </div>

    <div class="row" style="margin-top:12px">
      <div id="popupBranchWrap">
        <label>الفرع المستهدف</label>
        <select class="input" name="popup_branch_id">
          <option value="1" <?= $branchId === 1 ? 'selected' : '' ?>>أبوظبي</option>
          <option value="2" <?= $branchId === 2 ? 'selected' : '' ?>>دبي</option>
          <option value="3" <?= $branchId === 3 ? 'selected' : '' ?>>الشارقة</option>
          <option value="4" <?= $branchId === 4 ? 'selected' : '' ?>>العين</option>
        </select>
      </div>

      <div id="popupEmployeeWrap" style="display:none">
        <label>الموظف المستهدف</label>
        <select class="input" name="popup_employee_id">
          <option value="0">اختر الموظف</option>
          <?php foreach ($employees as $e): ?>
            <option value="<?= (int)$e['emp_id'] ?>">
              <?= h($e['emp_name'] ?? '') ?>
              <?php if (!empty($e['branch_id'])): ?>
                - <?= h(branch_name_ar((int)$e['branch_id'])) ?>
              <?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="btns">
      <button type="submit" class="btn popup-save-btn">حفظ الرسالة المنبثقة</button>
    </div>

    <div class="small">
      المرسل هنا هو الأونر فقط، والرسالة ستظهر مرة واحدة لكل موظف عند تسجيل الدخول.
    </div>
  </form>
</div>
<script>
(function(){
  const tabs = document.querySelectorAll('.tab');
  const modeInput = document.getElementById('mode');
  const selectedBox = document.getElementById('selectedBox');

  tabs.forEach(function(t){
    t.addEventListener('click', function(){
      tabs.forEach(function(x){ x.classList.remove('active'); });
      t.classList.add('active');
      const mode = t.dataset.mode;
      modeInput.value = mode;
      selectedBox.style.display = (mode === 'SELECTED') ? 'block' : 'none';
    });
  });

  document.getElementById('selectAll')?.addEventListener('click', function(){
    document.querySelectorAll('input[name="emp_ids[]"]').forEach(function(ch){ ch.checked = true; });
  });

  document.getElementById('clearAll')?.addEventListener('click', function(){
    document.querySelectorAll('input[name="emp_ids[]"]').forEach(function(ch){ ch.checked = false; });
  });

  document.getElementById('scopeSelect')?.addEventListener('change', function(e){
    const v = e.target.value;
    const url = new URL(window.location.href);
    url.searchParams.set('scope', v);
    window.location.href = url.toString();
  });

  const form = document.getElementById('mailForm');
  const okBox = document.getElementById('okBox');
  const errBox = document.getElementById('errBox');

  form.addEventListener('submit', async function(e){
    e.preventDefault();
    okBox.style.display = 'none';
    errBox.style.display = 'none';

    const fd = new FormData(form);

    try {
      const res = await fetch('hr_comms_email_send.php', { method:'POST', body: fd });
      const txt = await res.text();

      let data = null;
      try { data = JSON.parse(txt); } catch (e) {}

      if (!res.ok || !data || !data.ok) {
        errBox.textContent = (data && data.msg) ? data.msg : ('فشل الإرسال: ' + txt);
        errBox.style.display = 'block';
        return;
      }

      okBox.textContent = data.msg || 'تم الإرسال';
      okBox.style.display = 'block';
      form.reset();

      const defaultTab = document.querySelector('.tab[data-mode="ALL"]');
      if (defaultTab) defaultTab.click();
    } catch (err) {
      errBox.textContent = 'تعذر الاتصال بالخادم';
      errBox.style.display = 'block';
    }
  });
})();
const popupTarget = document.getElementById('popupTarget');
const popupBranchWrap = document.getElementById('popupBranchWrap');
const popupEmployeeWrap = document.getElementById('popupEmployeeWrap');

function syncPopupTargetUI() {
  if (!popupTarget) return;

  const val = popupTarget.value;

  if (val === 'EMPLOYEE') {
    if (popupEmployeeWrap) popupEmployeeWrap.style.display = 'block';
    if (popupBranchWrap) popupBranchWrap.style.display = 'none';
  } else if (val === 'ALL_BRANCHES') {
    if (popupEmployeeWrap) popupEmployeeWrap.style.display = 'none';
    if (popupBranchWrap) popupBranchWrap.style.display = 'none';
  } else {
    if (popupEmployeeWrap) popupEmployeeWrap.style.display = 'none';
    if (popupBranchWrap) popupBranchWrap.style.display = 'block';
  }
}

popupTarget?.addEventListener('change', syncPopupTargetUI);
syncPopupTargetUI();
</script>

<?php render_layout_end(); ?>