<?php
// hr_comms_email.php - OWNER ONLY
declare(strict_types=1);
session_start();
$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;
});
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/app_url.php';
require_once __DIR__ . '/inc/auth.php';
require_login();

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

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

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

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

// اجلب الموظفين (عدّل لو أعمدتك مختلفة)
$employees = [];
$sql = "SELECT e.id AS emp_id,
               COALESCE(NULLIF(e.full_name,''), NULLIF(e.name,''), CONCAT('موظف #', e.id)) AS emp_name,
               u.email AS email
        FROM employees e
        LEFT JOIN users u ON u.id = e.user_id
        WHERE (u.email IS NOT NULL AND u.email <> '')
        ORDER BY emp_name ASC";
$employees = $pdo->query($sql)->fetchAll();

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
$csrf = (string)$_SESSION['csrf'];
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>HR - التواصل مع الموظفين</title>
  <style>
    body{margin:0;font-family:Tajawal,system-ui,Segoe UI,Arial;background:#071a22;color:#eaf6f7}
    .wrap{display:flex;min-height:100vh}
    .main{flex:1;padding:18px 16px 40px}
    .card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.10);border-radius:16px;padding:16px;max-width:980px}
    .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
    @media(max-width:820px){.row{grid-template-columns:1fr}}
    label{display:block;margin:0 0 6px;color:#cfe8ea;font-size:14px}
    .input,textarea,select{width:100%;box-sizing:border-box;padding:12px 12px;border-radius:12px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.22);color:#fff;outline:none}
    textarea{min-height:160px;resize:vertical}
    .tabs{display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap}
    .tab{padding:10px 12px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.18);cursor:pointer;color:#fff}
    .tab.active{background:rgba(0,106,122,.35);border-color:rgba(0,106,122,.65)}
    .box{margin-top:12px;padding:12px;border-radius:14px;border:1px dashed rgba(255,255,255,.16);background:rgba(0,0,0,.14)}
    .btns{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}
    .btn{padding:12px 14px;border-radius:12px;border:0;cursor:pointer;background:#0b6a7a;color:#fff}
    .btn.secondary{background:rgba(255,255,255,.10)}
    .msg{margin-top:12px;display:none;padding:12px;border-radius:12px}
    .msg.ok{background:rgba(46,204,113,.15);border:1px solid rgba(46,204,113,.35)}
    .msg.err{background:rgba(231,76,60,.12);border:1px solid rgba(231,76,60,.35)}
    .small{font-size:12px;color:rgba(255,255,255,.75);margin-top:6px}
    .list{max-height:260px;overflow:auto;padding:8px;border-radius:12px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.18)}
    .item{display:flex;align-items:center;gap:10px;padding:8px;border-radius:10px}
    .item:hover{background:rgba(255,255,255,.06)}
    .pill{font-size:12px;padding:4px 8px;border-radius:999px;background:rgba(255,255,255,.10)}
  </style>
</head>
<body>
<div class="wrap">
  <?php /* include __DIR__.'/inc/hr_sidebar.php'; */ ?>
  <main class="main">
    <div class="card">
      <h2 style="margin:0 0 10px">التواصل مع الموظفين (OWNER فقط)</h2>
      <div class="small">إرسال بريد دفعة واحدة أو اختيار موظفين محددين.</div>

      <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>
          </div>
          <div>
            <label>نطاق الإرسال</label>
            <select class="input" name="scope">
              <option value="BRANCH" selected>هذا الفرع فقط</option>
              <option value="ALL_BRANCHES">كل الفروع</option>
            </select>
          </div>
        </div>

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

        <div class="box" id="selectedBox" style="display:none">
          <label>اختر الموظفين</label>
          <div class="list">
            <?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; ?>
          </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">إرسال الآن</button>
          <button type="button" class="btn secondary" onclick="location.href='hr_dashboard.php'">رجوع</button>
        </div>

        <div class="msg ok" id="okBox"></div>
        <div class="msg err" id="errBox"></div>
      </form>
    </div>
  </main>
</div>

<script>
  const tabs = document.querySelectorAll('.tab');
  const modeInput = document.getElementById('mode');
  const selectedBox = document.getElementById('selectedBox');

  tabs.forEach(t=>{
    t.addEventListener('click', ()=>{
      tabs.forEach(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', ()=>{
    document.querySelectorAll('input[name="emp_ids[]"]').forEach(ch=>ch.checked=true);
  });
  document.getElementById('clearAll')?.addEventListener('click', ()=>{
    document.querySelectorAll('input[name="emp_ids[]"]').forEach(ch=>ch.checked=false);
  });

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

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

    const fd = new FormData(form);

    const res = await fetch('hr_comms_email_send.php', { method:'POST', body: fd });
    const data = await res.json().catch(()=>null);

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

    okBox.textContent = data.msg || 'تم الإرسال';
    okBox.style.display = 'block';
    form.reset();
    document.querySelector('.tab[data-mode="ALL"]').click();
  });
</script>
</body>
</html>