<!-- فونت وزیر -->
<link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@v30.1.0/dist/font-face.css" rel="stylesheet" type="text/css" />

<h1 style="text-align:center; font-family:Vazir, Tahoma; color:#333;font-weight:600;">مستندات اعتبار بخشی</h1>

<!-- ردیف جستجو و فیلترها -->
<div id="search-filters" style="display:flex; justify-content:center; flex-wrap:wrap; gap:10px; margin:30px 0;">
  <input type="text" id="search" placeholder="جستجو بر اساس عنوان"
         style="flex:1 1 300px; max-width:400px; padding:10px 15px; border:none; background:#f3f3f3; border-radius:30px; font-size:14px; outline:none; text-align:right; font-family:Vazir, Tahoma; min-width:150px;">

  <select id="filter-mahvar"
          style="flex:0 1 150px; padding:10px 15px; border-radius:25px; border:1px solid #ccc; font-family:Vazir, Tahoma; font-size:14px; background:#fff; cursor:pointer;">
    <option value="">انتخاب محور</option>
  </select>

  <select id="filter-zirmohvar"
          style="flex:0 1 150px; padding:10px 15px; border-radius:25px; border:1px solid #ccc; font-family:Vazir, Tahoma; font-size:14px; background:#fff; cursor:pointer;">
    <option value="">انتخاب زیرمحور</option>
  </select>
</div>

<!-- کانتینر سه بخش -->
<div id="sections-container" style="padding:0 40px 60px; direction:rtl;"></div>

<!-- پیام وقتی چیزی پیدا نشد -->
<div id="no-result" style="display:none; text-align:center; color:#00A9C3; font-weight:600; font-size:16px; margin-top:20px;">
  هیچ سندی پیدا نشد.
</div>

<style>
.card {
  background:#fff; border-radius:18px; box-shadow:0 4px 10px rgba(0,0,0,0.1);
  padding:20px; display:flex; align-items:center; justify-content:space-between;
  flex-direction:row-reverse; font-family:Vazir, Tahoma; transition:all 0.3s ease;
}
.card-content { flex:1; text-align:right; padding-right:15px; }
.card-content h3 { margin:0 0 8px; font-weight:600; font-size:14px; color:#333; }
.card-content ul { margin:0; padding-right:15px; list-style:disc; font-size:13px; color:#555; }
.open-btn {
  display:inline-block; background:#00A9C3; color:#fff; border:none; border-radius:25px;
  padding:6px 18px; font-size:13px; text-decoration:none; margin-top:12px; cursor:pointer;
  font-family:Vazir, Tahoma;
}
.open-btn:hover { background:#0090a8; }
.card-icon { background:#f7f7f7; border-radius:16px; padding:12px; display:flex; align-items:center; justify-content:center; }
.card-icon img { width:2cm; height:2cm; }
.card:hover { transform:scale(1.03); background:#fdfdfd; }

@media(max-width:900px){
  .section-grid{grid-template-columns:1fr !important;}
  #search-filters { flex-direction:column; align-items:center; }
  #search-filters input, #search-filters select { flex:1 1 auto; max-width:300px; }
}
</style>

<script>
const pageId = "85045112";
const fileName = "form-data.json";
let docs = [];

const sections = [
  { title: "رهبری و مدیریت", value: "رهبری و مدیریت" },
  { title: "مراقبت و درمان", value: "مراقبت و درمان" },
  { title: "حمایت از گیرنده خدمت", value: "حمایت از گیرنده خدمت" }
];

// زیرمحورها
const zirmohvarOptions = {
  "رهبری و مدیریت": [
    "رهبری و مدیریت کیفیت",
    "مدیریت خطر، حوادث و بلایا",
    "مدیریت منابع انسانی و سلامت حرفه‌ای",
    "مدیریت خدمات پرستاری",
    "فناوری و مدیریت اطلاعات سلامت",
    "بهداشت محیط",
    "مدیریت تجهیزات پزشکی"
  ],
  "مراقبت و درمان": [
    "مراقبت‌های عمومی بالینی",
    "مراقبت‌های حاد و اورژانس",
    "مراقبت‌های جراحی و بیهوشی",
    "مراقبت‌های مادر و نوزاد",
    "پیشگیری و کنترل عفونت",
    "مدیریت دارویی",
    "خدمات تصویربرداری",
    "خدمات آزمایشگاه",
    "طب انتقال خون",
    "خدمات سرپایی"
  ],
  "حمایت از گیرنده خدمت": [
    "تأمین تسهیلات برای گیرنده خدمت",
    "احترام به حقوق گیرنده خدمت"
  ]
};

// آیکن‌ها
const sanadIcons = {
  "آیین نامه": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%A7%DB%8C%DB%8C%D9%86%20%D9%86%D8%A7%D9%85%D9%87.png?api=v2&nonce=1765664452835",
  "پروتکل": "https://kb.h-soft.ir/download/thumbnails/85045112/%D9%BE%D8%B1%D9%88%D8%AA%DA%A9%D9%84.png?api=v2&nonce=1765664452833",
  "خط‌مشی و روش": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%AE%D8%B7%20%D9%85%D8%B4%DB%8C.png?api=v2&nonce=1765664452830",
  "دستورالعمل": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%AF%D8%B3%D8%AA%D9%88%D8%B1%D8%A7%D9%84%D8%B9%D9%85%D9%84.png?api=v2&nonce=1765664452829",
  "راهنما": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%B1%D8%A7%D9%87%D9%86%D9%85%D8%A7.png?api=v2&nonce=1765664452826",
  "روش اجرایی": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%B1%D9%88%D8%B4%20%D8%A7%D8%AC%D8%B1%D8%A7%DB%8C%DB%8C.png?api=v2&nonce=1765664452825",
  "سند": "https://kb.h-soft.ir/download/thumbnails/85045112/%D8%B3%D9%86%D8%AF.png?api=v2&nonce=1765664452823",
  "فلوچارت": "https://kb.h-soft.ir/download/thumbnails/85045112/%D9%81%D9%84%D9%88%DA%86%D8%A7%D8%B1%D8%AA.png?api=v2&nonce=1765664452822",
  "کتابچه": "https://kb.h-soft.ir/download/thumbnails/85045112/%DA%A9%D8%AA%D8%A7%D8%A8%DA%86%D9%87.png?api=v2&nonce=1765664452819"
};

function normalizeSanadType(type){
  if (!type) return "";
  return type.trim().replace(/\u200c/g, " ").replace(/\s+/g, " ").toLowerCase();
}

function detectSanadIcon(type){
  const t = normalizeSanadType(type);
  if (t.includes("آیین")) return sanadIcons["آیین نامه"];
  if (t.includes("پروتکل")) return sanadIcons["پروتکل"];
  if (t.includes("خط مشی")) return sanadIcons["خط‌مشی و روش"];
  if (t.includes("دستورالعمل")) return sanadIcons["دستورالعمل"];
  if (t.includes("راهنما")) return sanadIcons["راهنما"];
  if (t.includes("روش اجرایی")) return sanadIcons["روش اجرایی"];
  if (t.includes("فلوچارت")) return sanadIcons["فلوچارت"];
  if (t.includes("کتابچه")) return sanadIcons["کتابچه"];
  return sanadIcons["سند"];
}

// دریافت JSON از Attachment
async function loadJSON(){
  const attRes = await fetch(`/rest/api/content/${pageId}/child/attachment`, { credentials: "include" });
  const attData = await attRes.json();
  const file = attData.results.find(a => a.title === fileName);
  if (!file) return;

  const downloadUrl = new URL(file._links.download, window.location.origin).href;
  const jsonText = await fetch(downloadUrl, { credentials:"include" }).then(r => r.text());
  docs = JSON.parse(jsonText);

  populateMahvarFilter();
  renderSections();
}

function populateMahvarFilter(){
  const sel = document.getElementById("filter-mahvar");
  if (sel.options.length > 1) return;
  sections.forEach(s => {
    const o = document.createElement("option");
    o.value = s.value;
    o.textContent = s.title;
    sel.appendChild(o);
  });
}

function updateZirmohvarFilter(){
  const mahvar = document.getElementById("filter-mahvar").value;
  const sel = document.getElementById("filter-zirmohvar");
  sel.innerHTML = '<option value="">انتخاب زیرمحور</option>';
  (zirmohvarOptions[mahvar] || []).forEach(z => {
    const o = document.createElement("option");
    o.value = z;
    o.textContent = z;
    sel.appendChild(o);
  });
}

// لینک فایل از Confluence
function getAttachmentUrl(fileName) {
  if (!fileName) return null;
  return `/download/attachments/${pageId}/${encodeURIComponent(fileName)}?api=v2`;
}

/* =========================
   مشاهده در تب جدید
   + دکمه دانلود داخل تب
   ========================= */
async function openViewer(url, fileName) {
  // برای جلوگیری از بلاک شدن پاپ‌آپ، تب رو همین لحظه باز می‌کنیم
  const viewerWin = window.open("", "_blank");
  if (!viewerWin) {
    alert("Pop-up توسط مرورگر بلاک شد. اجازه‌ی Pop-up را برای این سایت فعال کنید.");
    return;
  }

  viewerWin.document.open();
  viewerWin.document.write(`
    <!doctype html>
    <html lang="fa" dir="rtl">
      <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@v30.1.0/dist/font-face.css" rel="stylesheet" />
        <title>نمایش فایل</title>
        <style>
          body{margin:0;font-family:Vazir,Tahoma;background:#f7f7f7}
          .bar{
            position:sticky;top:0;z-index:10;
            display:flex;gap:10px;align-items:center;justify-content:space-between;
            padding:12px 16px;background:#fff;box-shadow:0 2px 10px rgba(0,0,0,.08)
          }
          .btn{
            background:#00A9C3;color:#fff;border:none;border-radius:10px;
            padding:8px 14px;cursor:pointer;font-family:Vazir,Tahoma
          }
          .btn:hover{background:#0090a8}
          .btn[disabled]{opacity:.6;cursor:not-allowed}
          .name{color:#333;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:65vw}
          .wrap{height:calc(100vh - 58px)}
          iframe{width:100%;height:100%;border:0;background:#fff}
          .msg{padding:20px;color:#555}
        </style>
      </head>
      <body>
        <div class="bar">
          <div class="name">در حال بارگذاری فایل...</div>
          <button class="btn" id="dlBtn" disabled>دانلود</button>
        </div>
        <div class="wrap" id="wrap">
          <div class="msg">لطفاً صبر کنید...</div>
        </div>
      </body>
    </html>
  `);
  viewerWin.document.close();

  try {
    const res = await fetch(url, { credentials: "include" });
    if (!res.ok) throw new Error("Fetch failed: " + res.status);

    const blob = await res.blob();
    const blobUrl = viewerWin.URL.createObjectURL(blob);

    const nameEl = viewerWin.document.querySelector(".name");
    const dlBtn = viewerWin.document.getElementById("dlBtn");
    const wrap = viewerWin.document.getElementById("wrap");

    if (nameEl) nameEl.textContent = fileName ? `نمایش: ${fileName}` : "نمایش فایل";

    // دکمه دانلود داخل تب جدید
    if (dlBtn) {
      dlBtn.disabled = false;
      dlBtn.addEventListener("click", () => {
        const a = viewerWin.document.createElement("a");
        a.href = blobUrl;
        a.download = fileName || "file";
        viewerWin.document.body.appendChild(a);
        a.click();
        a.remove();
      });
    }

    // نمایش فایل داخل تب جدید
    if (wrap) {
      wrap.innerHTML = `<iframe src="${blobUrl}" title="viewer"></iframe>`;
    }

    // پاکسازی URL وقتی تب بسته شد
    viewerWin.addEventListener("beforeunload", () => {
      try { viewerWin.URL.revokeObjectURL(blobUrl); } catch (e) {}
    });

  } catch (e) {
    console.error(e);
    try {
      const wrap = viewerWin.document.getElementById("wrap");
      if (wrap) wrap.innerHTML = `<div class="msg">خطا در دریافت/نمایش فایل</div>`;
    } catch (_) {}
  }
}

// کارت (فقط یک دکمه مشاهده)
function createCard(doc){
  const card = document.createElement("div");
  card.className = "card";

  const fileUrl = getAttachmentUrl(doc.document_file_name);
  const iconUrl = detectSanadIcon(doc.noe_sanad);

  const content = document.createElement("div");
  content.className = "card-content";

  const h3 = document.createElement("h3");
  h3.innerHTML = `<b>${doc.document_name || doc.title || ""}</b>`;

  const ul = document.createElement("ul");
  ul.innerHTML = `
    <li>زیرمحور: ${doc.zirmohvar || "-"}</li>
    <li>نوع سند: ${doc.noe_sanad || "-"}</li>
    <li>شماره استاندارد: ${doc.standard_no || "-"}</li>
    <li>تاریخ آخرین بازنگری: ${doc.date || "-"}</li>
  `;

  content.appendChild(h3);
  content.appendChild(ul);

  if (fileUrl) {
    const btn = document.createElement("button");
    btn.className = "open-btn";
    btn.type = "button";
    btn.textContent = "مشاهده";
    btn.addEventListener("click", () => openViewer(fileUrl, doc.document_file_name || ""));
    content.appendChild(btn);
  } else {
    const span = document.createElement("span");
    span.className = "open-btn";
    span.style.background = "#ccc";
    span.style.cursor = "not-allowed";
    span.textContent = "فایل ندارد";
    content.appendChild(span);
  }

  const icon = document.createElement("div");
  icon.className = "card-icon";
  icon.innerHTML = `<img src="${iconUrl}" alt="سند">`;

  card.appendChild(content);
  card.appendChild(icon);

  return card;
}

// رندر کل بخش‌ها
function renderSections(){
  const searchText = (document.getElementById("search").value || "").toLowerCase();
  const m = document.getElementById("filter-mahvar").value;
  const z = document.getElementById("filter-zirmohvar").value;

  const container = document.getElementById("sections-container");
  container.innerHTML = "";
  let found = false;

  sections.forEach(sec => {
    const list = docs.filter(d =>
      d.mahvar === sec.value &&
      (!searchText || ((d.document_name || d.title || "").toLowerCase().includes(searchText))) &&
      (!m || d.mahvar === m) &&
      (!z || d.zirmohvar === z)
    );

    if(!list.length) return;
    found = true;

    const grid = document.createElement("div");
    grid.className = "section-grid";
    grid.style.display = "grid";
    grid.style.gridTemplateColumns = "repeat(2,1fr)";
    grid.style.gap = "20px";

    [...list].reverse().forEach(d => grid.appendChild(createCard(d)));

    const h2 = document.createElement("h2");
    h2.style.textAlign = "center";
    h2.textContent = sec.title;

    const hr = document.createElement("hr");
    hr.style.border = "3px solid #00A9C3";
    hr.style.width = "80px";
    hr.style.margin = "0 auto 20px";

    container.append(h2, hr, grid);
  });

  document.getElementById("no-result").style.display = found ? "none" : "block";
}

// رویدادها
document.getElementById("search").addEventListener("input", renderSections);
document.getElementById("filter-mahvar").addEventListener("change", () => {
  updateZirmohvarFilter();
  renderSections();
});
document.getElementById("filter-zirmohvar").addEventListener("change", renderSections);

loadJSON();
</script>