<?php
declare(strict_types=1);

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

require_login();

$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);

$branchId = (int)current_branch_id();
$userId   = (int)current_user_id();

$role = strtoupper(trim((string)current_role()));

$isOwner = in_array($role, ['OWNER', 'SUPER_ADMIN'], true);
$isAdmin = in_array($role, ['ADMIN', 'OWNER', 'SUPER_ADMIN'], true);

if (!$isAdmin) {
    http_response_code(403);
    die('غير مصرح');
}

$empId = (int)($_GET['id'] ?? 0);
if ($empId <= 0) {
    http_response_code(400);
    die('bad request');
}

/*
  OWNER / SUPER_ADMIN:
  يرى أي موظف من أي فرع.

  ADMIN:
  يرى فقط موظفي الفرع الحالي.
*/
try {
    if ($isOwner) {
        $st = $pdo->prepare("
            SELECT id, full_name, branch_id
            FROM employees
            WHERE id = ?
            LIMIT 1
        ");
        $st->execute([$empId]);
    } else {
        $st = $pdo->prepare("
            SELECT id, full_name, branch_id
            FROM employees
            WHERE id = ?
              AND branch_id = ?
            LIMIT 1
        ");
        $st->execute([$empId, $branchId]);
    }

    $emp = $st->fetch();
} catch (Throwable $e) {
    http_response_code(500);
    die('تعذر جلب بيانات الموظف');
}

if (!$emp) {
    http_response_code(404);
    die('Not found');
}

/* مهم: استخدم فرع الموظف نفسه في المستندات */
$empBranchId = (int)($emp['branch_id'] ?? $branchId);

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

$uploadDir = __DIR__ . '/uploads/hr_docs';
if (!is_dir($uploadDir)) {
    @mkdir($uploadDir, 0755, true);
}

function safe_ext(string $name): string
{
    $name = strtolower($name);
    $ext = pathinfo($name, PATHINFO_EXTENSION);
    return preg_replace('/[^a-z0-9]/', '', $ext);
}

function random_name(string $ext): string
{
    $b = bin2hex(random_bytes(10));
    return $b . ($ext ? ('.' . $ext) : '');
}

/* حذف ملف */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'delete_doc') {
    $docId = (int)($_POST['doc_id'] ?? 0);

    if ($docId > 0) {
        try {
            $st = $pdo->prepare("
                SELECT file_path
                FROM employee_documents
                WHERE id = ?
                  AND employee_id = ?
                  AND branch_id = ?
                LIMIT 1
            ");
            $st->execute([$docId, $empId, $empBranchId]);
            $d = $st->fetch();

            if ($d) {
                $st = $pdo->prepare("
                    DELETE FROM employee_documents
                    WHERE id = ?
                      AND employee_id = ?
                      AND branch_id = ?
                    LIMIT 1
                ");
                $st->execute([$docId, $empId, $empBranchId]);

                $path = (string)($d['file_path'] ?? '');
                $full = __DIR__ . '/' . ltrim($path, '/');

                if ($path !== '' && is_file($full)) {
                    @unlink($full);
                }

                $msg = 'تم حذف المستند';
            } else {
                $err = 'المستند غير موجود';
            }
        } catch (Throwable $e) {
            $err = 'تعذر حذف المستند';
        }
    }
}

/* رفع ملف */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'upload') {
    $doc_type   = trim((string)($_POST['doc_type'] ?? 'OTHER'));
    $expires_at = trim((string)($_POST['expires_at'] ?? ''));

    $allowedTypes = ['EID', 'VISA', 'PASSPORT', 'CONTRACT', 'OTHER'];
    if (!in_array($doc_type, $allowedTypes, true)) {
        $doc_type = 'OTHER';
    }

    if (!isset($_FILES['file']) || (int)$_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $err = 'فشل رفع الملف';
    } else {
        $tmp  = (string)$_FILES['file']['tmp_name'];
        $orig = (string)$_FILES['file']['name'];
        $size = (int)$_FILES['file']['size'];

        if ($size <= 0 || $size > 10 * 1024 * 1024) {
            $err = 'حجم الملف غير مسموح (حد أقصى 10MB)';
        }

        $ext = safe_ext($orig);
        $allowedExt = ['pdf', 'png', 'jpg', 'jpeg', 'webp'];

        if (!$err && !in_array($ext, $allowedExt, true)) {
            $err = 'نوع الملف غير مسموح';
        }

        if (!$err && !is_uploaded_file($tmp)) {
            $err = 'ملف غير صالح';
        }

        if (!$err) {
            try {
                $new  = random_name($ext);
                $dest = $uploadDir . '/' . $new;

                if (!move_uploaded_file($tmp, $dest)) {
                    $err = 'تعذر حفظ الملف';
                } else {
                    $relPath = 'uploads/hr_docs/' . $new;
                    $expDb   = ($expires_at !== '') ? $expires_at : null;

                    $st = $pdo->prepare("
                        INSERT INTO employee_documents
                            (employee_id, branch_id, doc_type, file_name, file_path, expires_at, uploaded_by)
                        VALUES
                            (?, ?, ?, ?, ?, ?, ?)
                    ");

                    $st->execute([
                        $empId,
                        $empBranchId,
                        $doc_type,
                        $orig,
                        $relPath,
                        $expDb,
                        $userId
                    ]);

                    $msg = 'تم رفع المستند';
                }
            } catch (Throwable $e) {
                $err = 'تعذر رفع المستند';
            }
        }
    }
}

/* جلب المستندات */
try {
    $st = $pdo->prepare("
        SELECT id, doc_type, file_name, file_path, expires_at, created_at
        FROM employee_documents
        WHERE employee_id = ?
          AND branch_id = ?
        ORDER BY id DESC
    ");
    $st->execute([$empId, $empBranchId]);
    $docs = $st->fetchAll();
} catch (Throwable $e) {
    $docs = [];
    $err = $err ?: 'تعذر جلب المستندات';
}

render_layout_start('مستندات الموظف');
?>

<style>
.doc-upload-form{
  display:flex;
  gap:12px;
  align-items:flex-end;
  flex-wrap:wrap;
  margin-bottom:14px;
}

.doc-field{
  display:flex;
  flex-direction:column;
}

.doc-field label{
  margin-bottom:8px;
  font-weight:800;
  color:#cfe7ee;
}

/* القائمة */
.select-wrap{
  position:relative;
}

.select-ui{
  width:100%;
  min-width:190px;
  height:52px;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.10);
  background:
    linear-gradient(180deg, rgba(255,255,255,.03), rgba(255,255,255,.015)),
    linear-gradient(90deg, rgba(2,24,34,.98), rgba(6,36,49,.98));
  color:#f4fbff;
  padding:0 16px 0 44px;
  font-size:15px;
  font-weight:800;
  outline:none;
  appearance:none;
  -webkit-appearance:none;
  -moz-appearance:none;
  box-shadow:inset 0 1px 0 rgba(255,255,255,.04), 0 8px 20px rgba(0,0,0,.16);
  transition:.18s ease;
  cursor:pointer;
}

.select-ui:hover{
  border-color:rgba(66,192,220,.38);
}

.select-ui:focus{
  border-color:#19b7d3;
  box-shadow:0 0 0 4px rgba(25,183,211,.14), 0 10px 24px rgba(0,0,0,.22);
}

.select-wrap::after{
  content:"⌄";
  position:absolute;
  left:15px;
  top:50%;
  transform:translateY(-52%);
  color:#90d9e7;
  font-size:20px;
  font-weight:900;
  pointer-events:none;
}

.select-ui option{
  background:#0b1f2a;
  color:#fff;
}

/* التاريخ */
.date-ui{
  width:220px;
  max-width:100%;
  height:52px;
  direction:ltr;
  text-align:center;
  font-weight:800;
  letter-spacing:.5px;
}

/* اختيار الملف */
.file-upload{
  min-width:280px;
}

.file-box{
  position:relative;
  display:flex;
  align-items:center;
  gap:10px;
  min-height:52px;
  padding:8px 10px;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.10);
  background:
    linear-gradient(180deg, rgba(255,255,255,.03), rgba(255,255,255,.015)),
    linear-gradient(90deg, rgba(2,24,34,.98), rgba(6,36,49,.98));
  box-shadow:inset 0 1px 0 rgba(255,255,255,.04), 0 8px 20px rgba(0,0,0,.16);
}

.file-box input[type="file"]{
  position:absolute;
  inset:0;
  opacity:0;
  cursor:pointer;
  width:100%;
  height:100%;
}

.file-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:120px;
  height:38px;
  padding:0 16px;
  border-radius:12px;
  border:1px solid rgba(68,197,224,.28);
  background:linear-gradient(180deg, rgba(11,93,114,.9), rgba(7,70,88,.95));
  color:#fff;
  font-weight:800;
  font-size:14px;
  white-space:nowrap;
}

.file-name{
  color:#b9c8cf;
  font-size:14px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  flex:1;
}

/* زر الرفع */
.upload-btn{
  height:52px;
  min-width:110px;
}

/* جدول */
.table-wrap{
  overflow:auto;
}

.table-clean{
  width:100%;
  border-collapse:separate;
  border-spacing:0;
}

.table-clean th,
.table-clean td{
  padding:14px 12px;
  border-bottom:1px solid rgba(255,255,255,.06);
  text-align:right;
  vertical-align:middle;
}

.table-clean thead th{
  color:#d9edf2;
  font-weight:900;
  background:rgba(255,255,255,.02);
}

.file-link-row{
  display:flex;
  align-items:center;
  gap:8px;
  flex-wrap:wrap;
}

/* موبايل */
@media (max-width: 900px){
  .doc-upload-form{
    flex-direction:column;
    align-items:stretch;
  }

  .doc-field,
  .file-upload{
    width:100%;
    min-width:100%;
  }

  .select-ui,
  .date-ui{
    width:100%;
  }

  .upload-btn{
    width:100%;
  }
}
</style>

<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">
    <div class="cardHead">
      <div>
        <div style="font-weight:900">مستندات الموظف</div>
        <div class="muted" style="font-size:13px"><?=h($emp['full_name'])?></div>
      </div>
      <div class="row">
        <a class="btn ghost" href="hr_employee_form.php?id=<?=$empId?>">تعديل البيانات</a>
        <a class="btn ghost" href="hr_employees.php">رجوع</a>
      </div>
    </div>

    <form method="post" enctype="multipart/form-data" class="doc-upload-form" novalidate>
      <input type="hidden" name="action" value="upload">

      <div class="doc-field" style="width:190px;min-width:170px">
        <label>نوع المستند</label>
        <div class="select-wrap">
          <select name="doc_type" class="select-ui">
            <option value="EID">الهوية</option>
            <option value="VISA">الإقامة</option>
            <option value="PASSPORT">الجواز</option>
            <option value="CONTRACT">عقد</option>
            <option value="OTHER">أخرى</option>
          </select>
        </div>
      </div>

      <div class="doc-field" style="width:220px;min-width:200px">
        <label>تاريخ انتهاء الوثيقة</label>
        <input
          class="input date-ui"
          id="expires_at_ui"
          inputmode="numeric"
          maxlength="10"
          placeholder="dd/mm/yyyy"
          autocomplete="off"
        >
        <input type="hidden" name="expires_at" id="expires_at">
      </div>

      <div class="doc-field file-upload" style="flex:1;min-width:260px">
        <label>الملف</label>
        <div class="file-box">
          <input type="file" name="file" id="file_input" accept=".pdf,.png,.jpg,.jpeg,.webp" required>
          <span class="file-btn">اختيار ملف</span>
          <span class="file-name" id="file_name_text">لم يتم اختيار ملف</span>
        </div>
      </div>

      <button class="btn upload-btn" type="submit">رفع</button>
    </form>

    <div class="table-wrap">
      <table class="table-clean">
        <thead>
          <tr>
            <th>النوع</th>
            <th>الملف</th>
            <th>الانتهاء</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($docs as $d): ?>
            <tr>
              <td><?=h($d['doc_type'])?></td>
              <td>
                <div class="file-link-row">
                  <a class="btn ghost" target="_blank" href="<?=h($d['file_path'])?>">فتح</a>
                  <span class="muted" style="font-size:13px"><?=h($d['file_name'])?></span>
                </div>
              </td>
              <td><?= !empty($d['expires_at']) ? h(date('d/m/Y', strtotime((string)$d['expires_at']))) : '' ?></td>
              <td>
                <form method="post" onsubmit="return confirm('حذف المستند؟');" style="display:inline">
                  <input type="hidden" name="action" value="delete_doc">
                  <input type="hidden" name="doc_id" value="<?= (int)$d['id'] ?>">
                  <button class="btn danger" type="submit">حذف</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>

          <?php if (!$docs): ?>
            <tr>
              <td colspan="4" class="muted">لا توجد مستندات</td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
(function () {
  const uiDate = document.getElementById('expires_at_ui');
  const realDate = document.getElementById('expires_at');
  const fileInput = document.getElementById('file_input');
  const fileNameText = document.getElementById('file_name_text');

  function normalizeDate(value) {
    let v = String(value || '').replace(/[^\d]/g, '').slice(0, 8);

    if (v.length > 4) return v.slice(0,2) + '/' + v.slice(2,4) + '/' + v.slice(4);
    if (v.length > 2) return v.slice(0,2) + '/' + v.slice(2);
    return v;
  }

  function uiToIso(value) {
    const m = String(value || '').match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
    if (!m) return '';

    const dd = m[1];
    const mm = m[2];
    const yyyy = m[3];

    const d = new Date(`${yyyy}-${mm}-${dd}T00:00:00`);
    if (
      d.getFullYear() !== Number(yyyy) ||
      d.getMonth() + 1 !== Number(mm) ||
      d.getDate() !== Number(dd)
    ) {
      return '';
    }

    return `${yyyy}-${mm}-${dd}`;
  }

  if (uiDate && realDate) {
    uiDate.addEventListener('input', function () {
      this.value = normalizeDate(this.value);
      realDate.value = uiToIso(this.value);
    });

    uiDate.addEventListener('blur', function () {
      realDate.value = uiToIso(this.value);
    });
  }

  if (fileInput && fileNameText) {
    fileInput.addEventListener('change', function () {
      if (this.files && this.files.length > 0) {
        fileNameText.textContent = this.files[0].name;
      } else {
        fileNameText.textContent = 'لم يتم اختيار ملف';
      }
    });
  }
})();
</script>

<?php render_layout_end(); ?>