<?php
declare(strict_types=1);

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

require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';

require_login();

/* Debug اختياري: hr_employees.php?debug=1 */
$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
if ($debug) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
}

$pdo = dbx();
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);

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

$branchId = current_branch_id();
$role     = current_role();
$isOwner  = ($role === 'OWNER');
$isAdmin  = in_array($role, ['ADMIN', 'OWNER', 'SUPER_ADMIN'], true);
/* =========================
   أعمدة employees
========================= */
$cols = [];
try {
    $stc = $pdo->query("SHOW COLUMNS FROM employees");
    $cols = $stc->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (Throwable $e) {
    $cols = [];
}

$hasFullName = in_array('full_name', $cols, true);
$hasName     = in_array('name', $cols, true);
$hasPhone    = in_array('phone', $cols, true);
$hasQR2      = in_array('qr_token2', $cols, true);
$hasQR1      = in_array('qr_token', $cols, true);
$hasBranch   = in_array('branch_id', $cols, true);
$hasUserId   = in_array('user_id', $cols, true);
$hasEmpIdCol = in_array('employee_id', $cols, true);

/* =========================
   تحديد الموظف المسجل دخول
========================= */
$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentEmpId  = (int)($_SESSION['employee_id'] ?? 0);

if ($currentEmpId <= 0 && $currentUserId > 0) {
    try {
        if ($hasUserId) {
            $sqlMe = "SELECT id FROM employees WHERE user_id = ?";
            $paramsMe = [$currentUserId];

            if ($hasBranch && !$isOwner) {
    $sqlMe .= " AND branch_id = ?";
    $paramsMe[] = $branchId;
}
            $sqlMe .= " LIMIT 1";
            $stMe = $pdo->prepare($sqlMe);
            $stMe->execute($paramsMe);
            $currentEmpId = (int)($stMe->fetchColumn() ?: 0);
        } elseif ($hasEmpIdCol) {
            $sqlMe = "SELECT id FROM employees WHERE employee_id = ?";
            $paramsMe = [$currentUserId];

        if ($hasBranch && !$isOwner) {
    $sqlMe .= " AND branch_id = ?";
    $paramsMe[] = $branchId;
}
            $sqlMe .= " LIMIT 1";
            $stMe = $pdo->prepare($sqlMe);
            $stMe->execute($paramsMe);
            $currentEmpId = (int)($stMe->fetchColumn() ?: 0);
        }
    } catch (Throwable $e) {
        $currentEmpId = 0;
    }
}

/* حذف (Admin + Owner) */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'delete') {
    if (!$isAdmin) {
        $err = 'غير مصرح';
    } else {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            try {
                $sqlDel = "DELETE FROM employees WHERE id = ?";
                $paramsDel = [$id];

                $st = $pdo->prepare($sqlDel);
                $st->execute($paramsDel);
                $msg = 'تم حذف الموظف بنجاح';
            } catch (Throwable $e) {
                $err = $debug ? $e->getMessage() : 'تعذر حذف الموظف';
            }
        }
    }
}

/* =========================
   بحث
========================= */
$q = trim((string)($_GET['q'] ?? ''));

$nameExpr = $hasFullName
    ? "e.full_name"
    : ($hasName ? "e.name" : "CONCAT('EMP#', e.id)");

$select = [];
$select[] = "e.id";
$select[] = "{$nameExpr} AS full_name";
$select[] = $hasPhone ? "e.phone" : "'' AS phone";
$select[] = $hasQR2 ? "e.qr_token2" : "'' AS qr_token2";
$select[] = $hasQR1 ? "e.qr_token" : "'' AS qr_token";

$sql = "SELECT " . implode(', ', $select) . " FROM employees e WHERE 1=1";
$params = [];

/* غير الأدمن يشوف فرعه فقط */
if ($hasBranch && !$isOwner) {
    $sql .= " AND e.branch_id = :b";
    $params[':b'] = $branchId;
}
if ($q !== '') {
    $like = "%{$q}%";
    $parts = [];

    $parts[] = "{$nameExpr} LIKE :q1";
    $params[':q1'] = $like;

    $i = 2;

    if ($hasPhone) {
        $parts[] = "e.phone LIKE :q{$i}";
        $params[":q{$i}"] = $like;
        $i++;
    }

    if ($isAdmin) {
        if ($hasQR2) {
            $parts[] = "e.qr_token2 LIKE :q{$i}";
            $params[":q{$i}"] = $like;
            $i++;
        }

        if ($hasQR1) {
            $parts[] = "e.qr_token LIKE :q{$i}";
            $params[":q{$i}"] = $like;
            $i++;
        }
    }

    if ($parts) {
        $sql .= " AND (" . implode(' OR ', $parts) . ")";
    }
}

$sql .= " ORDER BY e.id DESC";

/* جلب البيانات */
$rows = [];
try {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $err = $debug ? $e->getMessage() : 'حدث خطأ أثناء جلب البيانات';
    $rows = [];
}

render_layout_start('شؤون الموظفين - الموظفين');
?>

<style>
.hr-employees-page .btn.is-locked,
.hr-employees-page a.is-locked{
  opacity:.45;
  filter:grayscale(1);
  cursor:not-allowed;
  pointer-events:none;
}

.hr-employees-page .hr-employees-card{
  width:100%;
  max-width:100%;
}

.hr-employees-page .hr-employees-head{
  display:flex;
  align-items:flex-start;
  justify-content:space-between;
  gap:14px;
  flex-wrap:wrap;
}

.hr-employees-page .hr-employees-head-text{
  min-width:0;
}

.hr-employees-page .hr-employees-title{
  font-weight:900;
  font-size:28px;
  line-height:1.2;
}

.hr-employees-page .hr-employees-subtitle{
  font-size:13px;
  margin-top:6px;
}

.hr-employees-page .hr-employees-head-actions{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
}

.hr-employees-page .hr-employees-search{
  display:grid;
  grid-template-columns:1fr auto;
  gap:10px;
  align-items:center;
  margin-bottom:14px;
}

.hr-employees-page .hr-employees-search-input{
  min-width:0;
}

.hr-employees-page .hr-employees-search .input{
  width:100%;
}

.hr-employees-page .table-wrap{
  width:100%;
  overflow-x:auto;
  overflow-y:hidden;
  border:1px solid rgba(255,255,255,.08);
  border-radius:22px;
  background:rgba(255,255,255,.03);
  box-shadow:0 10px 30px rgba(0,0,0,.16);
}

.hr-employees-page .emp-table{
  width:100%;
  min-width:980px;
  border-collapse:separate;
  border-spacing:0;
  table-layout:fixed;
}

.hr-employees-page .emp-table thead th{
  position:sticky;
  top:0;
  z-index:2;
  padding:18px 16px;
  text-align:right;
  font-size:14px;
  font-weight:900;
  color:#ffffff;
  background:linear-gradient(180deg, rgba(0,106,122,.30), rgba(0,66,79,.18));
  border-bottom:1px solid rgba(255,255,255,.10);
  letter-spacing:.2px;
}

.hr-employees-page .emp-table tbody td{
  padding:18px 16px;
  text-align:right;
  vertical-align:middle;
  white-space:nowrap;
  border-bottom:1px solid rgba(255,255,255,.06);
  color:#eef7f8;
  background:transparent;
}

.hr-employees-page .emp-table tbody tr{
  transition:background .18s ease;
}

.hr-employees-page .emp-table tbody tr:hover td{
  background:rgba(255,255,255,.035);
}

.hr-employees-page .emp-table tbody tr:last-child td{
  border-bottom:none;
}

.hr-employees-page .col-name{
  width:34%;
}

.hr-employees-page .col-phone{
  width:20%;
}

.hr-employees-page .col-code{
  width:16%;
}

.hr-employees-page .actions-col{
  width:30%;
  min-width:290px;
}

.hr-employees-page .employee-info{
  min-width:0;
  display:flex;
  flex-direction:column;
  gap:4px;
}

.hr-employees-page .employee-name{
  font-size:16px;
  font-weight:800;
  color:#fff;
  overflow:hidden;
  text-overflow:ellipsis;
}

.hr-employees-page .employee-meta{
  font-size:12px;
  color:rgba(255,255,255,.62);
}

.hr-employees-page .phone-pill,
.hr-employees-page .code-hidden{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:40px;
  padding:0 14px;
  border-radius:999px;
  font-size:13px;
  font-weight:800;
}

.hr-employees-page .phone-pill{
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.05);
  color:#f4fbfc;
}

.hr-employees-page .code-hidden{
  min-width:88px;
  border:1px dashed rgba(255,255,255,.20);
  background:rgba(255,255,255,.04);
  color:rgba(255,255,255,.78);
}

.hr-employees-page .code-me{
  border-style:solid;
  border-color:rgba(0,106,122,.45);
  background:rgba(0,106,122,.16);
  color:#dff7fb;
  box-shadow:inset 0 0 0 1px rgba(255,255,255,.03);
}

.hr-employees-page .actions-wrap{
  display:flex;
  align-items:center;
  gap:8px;
  flex-wrap:wrap;
}

.hr-employees-page .actions-wrap .btn{
  min-width:82px;
  justify-content:center;
}

.hr-employees-page .inline-form{
  display:inline-block;
  margin:0;
}

.hr-employees-page .empty-row{
  text-align:center !important;
  padding:26px 16px !important;
  color:rgba(255,255,255,.68) !important;
}

@media (max-width: 900px){
  .hr-employees-page .hr-employees-search{
    grid-template-columns:1fr;
  }

  .hr-employees-page .emp-table{
    min-width:920px;
  }

  .hr-employees-page .col-name{
    width:32%;
  }

  .hr-employees-page .col-phone{
    width:20%;
  }

  .hr-employees-page .col-code{
    width:16%;
  }

  .hr-employees-page .actions-col{
    width:32%;
    min-width:260px;
  }
}
</style>

<div class="hr-employees-page">
  <div class="grid">
    <?php if ($msg): ?><div class="msg ok"><?= h($msg) ?></div><?php endif; ?>
    <?php if ($err): ?><div class="msg err"><?= h($err) ?></div><?php endif; ?>

    <div class="card hr-employees-card">
      <div class="cardHead hr-employees-head">
        <div class="hr-employees-head-text">
          <div class="hr-employees-title">الموظفين</div>
          <div class="muted hr-employees-subtitle">
            <?= $isAdmin ? 'يعرض جميع الموظفين' : 'يعرض فقط موظفي فرع: ' . h(branch_name_ar($branchId)) ?>
          </div>
        </div>

        <div class="hr-employees-head-actions">
          <?php if ($isAdmin): ?>
            <a class="btn" href="hr_employee_form.php">إضافة موظف</a>
          <?php else: ?>
            <a class="btn is-locked" href="#" title="صلاحية الأدمن فقط">إضافة موظف</a>
          <?php endif; ?>
        </div>
      </div>

      <form method="get" class="hr-employees-search">
        <div class="hr-employees-search-input">
          <input
            class="input"
            name="q"
            value="<?= h($q) ?>"
            placeholder="ابحث بالاسم أو الهاتف<?= $isAdmin ? ' أو QR' : '' ?>">
        </div>
        <button class="btn ghost" type="submit">بحث</button>
      </form>

      <div class="table-wrap">
        <table class="emp-table">
          <thead>
            <tr>
              <th class="col-name">الاسم</th>
              <th class="col-phone">الهاتف</th>
              <th class="col-code">كود الموظف</th>
              <th class="actions-col">إجراءات</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($rows as $r): ?>
<?php
$empIdRow = (int)($r['id'] ?? 0);

/* هل هذا المستخدم هو نفسه صاحب الصف */
$isMe = ($currentEmpId > 0 && $empIdRow === $currentEmpId);

/* صلاحية رؤية الكود */
$canSeeCode = $isOwner || $isMe;

/* جلب الكود */
$codeRaw = trim((string)($r['qr_token2'] ?? ''));
if ($codeRaw === '') {
    $codeRaw = trim((string)($r['qr_token'] ?? ''));
}

/* ما الذي سيظهر في الجدول */
$codeShown = $canSeeCode ? ($codeRaw !== '' ? $codeRaw : '-') : '••••';
$titleTxt  = $canSeeCode ? ($codeRaw !== '' ? $codeRaw : '-') : 'مخفي';

                $name2  = trim((string)($r['full_name'] ?? ''));
                $phone2 = trim((string)($r['phone'] ?? ''));
              ?>
              <tr>
                <td class="col-name">
                  <div class="employee-info">
                    <div class="employee-name"><?= h($name2 !== '' ? $name2 : 'بدون اسم') ?></div>
                    <div class="employee-meta">رقم الموظف: <?= (int)$r['id'] ?></div>
                  </div>
                </td>

                <td class="col-phone">
                  <span class="phone-pill"><?= h($phone2 !== '' ? $phone2 : '-') ?></span>
                </td>

                <td class="col-code" title="<?= h($titleTxt) ?>">
                  <span class="<?= $canSeeCode ? 'code-hidden code-me' : 'code-hidden' ?>">
                    <?= h($codeShown) ?>
                  </span>
                </td>

                <td class="actions-col">
                  <div class="actions-wrap">
                    <?php if ($isAdmin): ?>
                      <a class="btn ghost" href="hr_employee_form.php?id=<?= (int)$r['id'] ?>">تعديل</a>
                      <a class="btn ghost" href="hr_employee_docs.php?id=<?= (int)$r['id'] ?>">مستندات</a>

                      <form method="post" onsubmit="return confirm('تأكيد حذف الموظف؟');" class="inline-form">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <button class="btn danger" type="submit">حذف</button>
                      </form>
                    <?php else: ?>
                      <a class="btn ghost is-locked" href="#" title="صلاحية الأدمن فقط">تعديل</a>
                      <a class="btn ghost is-locked" href="#" title="صلاحية الأدمن فقط">مستندات</a>
                      <button class="btn danger is-locked" type="button" title="صلاحية الأدمن فقط">حذف</button>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>

            <?php if (!$rows): ?>
              <tr>
                <td colspan="4" class="empty-row">لا توجد بيانات</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>

        <?php if (!$isAdmin && $currentEmpId <= 0): ?>
          <div class="muted" style="margin-top:10px;font-size:12.5px;">
            ملاحظة: لم يتم العثور على الموظف المرتبط بالحساب الحالي، لذلك سيتم إخفاء الكود للجميع.
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php render_layout_end(); ?>