


function openAttachment(attachmentUrl) {
  if (!attachmentUrl) return;

  attachmentUrl = attachmentUrl.trim();

  // لو الرابط نسبي، ضيفه على أصل الموقع الحالي
  if (!attachmentUrl.startsWith("http") && !attachmentUrl.startsWith("/")) {
    const baseUrl = window.location.origin + "/MMM/";
    attachmentUrl = baseUrl + attachmentUrl;
  }

  console.log("📎 فتح المرفق:", attachmentUrl);
  window.open(attachmentUrl, '_blank');
}


// دالة عرض الرسالة داخل الصفحة
function showMessage(msg, type = "success", duration = 5000) {
    let box = document.getElementById("message-box");
    if (!box) {
        box = document.createElement("div");
        box.id = "message-box";
        box.style.position = "fixed";
        box.style.bottom = "20px";
        box.style.left = "50%"; 
        box.style.transform = "translateX(-50%)";
        box.style.padding = "10px 20px";
        box.style.borderRadius = "5px";
        box.style.boxShadow = "0 2px 6px rgba(0,0,0,0.2)";
        box.style.color = "#fff";
        box.style.zIndex = "9999";
        document.body.appendChild(box);
    }
    box.style.background = type === "success" ? "#4caf50" : "#f44336";
    box.innerText = msg;
    box.style.opacity = "1";

    setTimeout(() => {
        box.style.opacity = "0";
    }, duration);
}


//Find


let editingBalanceId = null;

document.addEventListener("DOMContentLoaded", () => {
    const tbody = document.getElementById("transactions-table-body"); 
    const deleteBtn = document.getElementById("BTNDelete");
    const saveBtn = document.getElementById("BTNSaveEdit");
    const pdfBtn = document.getElementById("selectPdfBtn");
    if (!tbody) return;
    if (deleteBtn) deleteBtn.style.display = "none";

    const countLabel = document.createElement('div');
    countLabel.id = 'transactions-count';
    countLabel.style.fontWeight = 'bold';
    countLabel.style.width = "100%";


    const totalLabel = document.createElement('div');
    totalLabel.id = 'transactions-total';
    totalLabel.style.fontWeight = 'bold';

    const countIcon = '<i class="fas fa-hashtag dropdown-arrow icon-secondary"></i> ';
    const totalIcon = '<i class="fas fa-calculator dropdown-arrow icon-secondary"></i> ';

    tbody.parentNode.insertBefore(countLabel, tbody.nextSibling);
    tbody.parentNode.insertBefore(totalLabel, countLabel.nextSibling);

    let currentType = "all";
    let currentMethod = "all";

    function loadTransactions() {
        const section = document.getElementById("add-balance-section");
        if (!section || !tbody) return;

        fetch("get_transactions.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            }
        })
        .then(res => res.json())
        .then(result => {
            if (!result.success || !Array.isArray(result.data)) {
                tbody.innerHTML = `<tr><td colspan="8" class="no-items">❌ ${result.message || "فشل تحميل البيانات"}</td></tr>`;
                updateTransactionsSummary([]);
                return;
            }

            const data = result.data;
            if (data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="8" class="no-items">لا توجد معاملات مضافة بعد</td></tr>`;
                updateTransactionsSummary([]);
                return;
            }

            tbody.innerHTML = "";

            data.forEach(tx => {
                const safeAttachment = encodeURIComponent(tx.AttachmentPath || "");
                const row = document.createElement("tr");

                row.setAttribute("data-method", (tx.method || '').toLowerCase());
                row.setAttribute("data-type", (tx.type || '').toLowerCase());
                row.setAttribute("data-user", (tx.user_name || '').toLowerCase());

                const attachmentCell = tx.AttachmentPath ? `
                    <div class="navS-icon" id="TransactionPdfBtn_${tx.id}" tabindex="0" role="button"
                         style="width: 50px; cursor: pointer;" aria-label="المرفق PDF"
                         onclick="openAttachment(decodeURIComponent('${safeAttachment.replace(/^,/, '')}'))">
                        <i class="fas fa-file-pdf"></i>
                        <span class="tooltip" role="tooltip">المرفق PDF</span>
                    </div>
                ` : "—";

                row.innerHTML = `
                    <td>${tx.method}</td>
                    <td>${tx.date}</td>
                    <td>${parseFloat(tx.value).toFixed(2)}</td>
                    <td>${tx.type}</td>
                    <td>${tx.RefranNUM || ''}</td>
                    <td>${tx.user_name || '—'}</td>
                    <td>${attachmentCell}</td>
                    <td>${tx.notes || ''}</td>
                `;

                row.addEventListener("click", () => {
                    document.getElementById("add-balance-section").style.display = "block";
                    document.getElementById("transactions-section").style.display = "none";

                    if (deleteBtn) deleteBtn.style.display = "inline-block";

                    fillTransactionForm(tx);
                });

                tbody.appendChild(row);
            });

            applyFilters();
            updateTransactionsSummary(data);
        })
        .catch(err => {
            console.error("❌ خطأ في تحميل المعاملات:", err);
            tbody.innerHTML = `<tr><td colspan="8" class="no-items">❌ حدث خطأ أثناء تحميل البيانات</td></tr>`;
            updateTransactionsSummary([]);
        });
    }

    function fillTransactionForm(tx) {
        const form = document.getElementById("add-balance-form");
        if (!form) return;

        form.querySelector('[name="payment_method"]').value = tx.method || "";
        form.querySelector('[name="deposit_date"]').value = tx.date || "";
        form.querySelector('[name="balance_value"]').value = tx.value || "";
        form.querySelector('[name="ActionType"]').value = tx.type || "";
        form.querySelector('[name="reference_number"]').value = tx.RefranNUM || "";
        form.querySelector('[name="notes"]').value = tx.notes || "";
        form.querySelector('[name="AttachmentPath"]').value = tx.AttachmentPath || "";

        editingBalanceId = tx.id;

        const sectionTitle = document.querySelector("#add-balance-section h2");
        if (sectionTitle) {
            sectionTitle.innerHTML = `<i class="fas fa-exchange-alt"></i> تعديل الرصيد`;
        }

        const section = document.getElementById("add-balance-section");
        if (section) section.setAttribute("aria-label", "تعديل");

        if (saveBtn) {
            const icon = saveBtn.querySelector("i");
            const tooltip = saveBtn.querySelector(".tooltip");

            saveBtn.setAttribute("aria-label", "تعديل");
            if (icon) icon.className = "fas fa-edit";
            if (tooltip) tooltip.textContent = "تعديل";
        }

        // ✅ زرار PDF يظهر دايمًا في التعديل
        if (pdfBtn) {
            pdfBtn.style.display = "inline-block";
        }

        applyPermissions();
    }

    function updateTransactionsSummary() {
        const rows = Array.from(tbody.querySelectorAll('tr'))
            .filter(r => r.style.display !== "none" && !r.classList.contains('no-items'));
        const totalRows = rows.length;

        let totalAdd = 0;
        let totalDeduct = 0;

        rows.forEach(row => {
            const valueCell = row.cells[2];
            const typeCell = row.cells[3];
            if (valueCell && typeCell) {
                const cellValue = parseFloat(valueCell.textContent.trim().replace(/,/g, '')) || 0;
                const typeText = typeCell.textContent.trim();

                if (typeText === "مدخل") totalAdd += cellValue;
                else if (typeText === "مخرج") totalDeduct += cellValue;
            }
        });

        const netTotal = totalAdd - totalDeduct;

        countLabel.innerHTML = `<br>${countIcon}العدد: ${totalRows}<br>`;
       totalLabel.innerHTML = `
  <br>${totalIcon} المدخل: ${totalAdd.toFixed(2)} ريال<br>
  ${totalIcon}المخرج: ${totalDeduct.toFixed(2)} ريال<br>
  ${totalIcon}الصافي : ${netTotal.toFixed(2)} ريال
`;

        
        countLabel.style.marginTop = "10px";
        countLabel.style.marginBottom = "10px";
        totalLabel.style.marginTop = "10px";
        totalLabel.style.marginBottom = "10px";
    }

    function filterByType(type) {
        currentType = type;
        applyFilters();
    }

    function filterByMethod(method) {
        currentMethod = method;
        applyFilters();
    }

    function filterByUser() {
        applyFilters();
    }

    function applyFilters() {
        const userInput = document.getElementById("userFilter").value.toLowerCase();
        const rows = document.querySelectorAll("#transactions-table-body tr");

        rows.forEach(row => {
            const type = row.getAttribute("data-type");
            const method = row.getAttribute("data-method");
            const user = row.getAttribute("data-user") || "";

            let show = true;
            if (currentType !== "all" && type !== currentType.toLowerCase()) show = false;
            if (currentMethod !== "all" && method !== currentMethod.toLowerCase()) show = false;
            if (userInput && !user.includes(userInput)) show = false;

            row.style.display = show ? "" : "none";
        });

        updateTransactionsSummary();
    }

    loadTransactions();
    setInterval(loadTransactions, 5000);

    const observer = new MutationObserver(() => {
        updateTransactionsSummary();
    });
    observer.observe(tbody, { childList: true, subtree: true });

    const userFilterInput = document.getElementById("userFilter");
    if (userFilterInput) userFilterInput.addEventListener("input", filterByUser);

    window.filterByType = filterByType;
    window.filterByMethod = filterByMethod;
});



//PDF
document.addEventListener("DOMContentLoaded", () => {
  const selectPdfBtn = document.getElementById("selectPdfBtn");
  const fileInput = document.getElementById("pdfFileInput");
  const attachmentField = document.getElementById("AttachmentPath");
  const msg = document.getElementById("projectMsg");

  // عند الضغط على زر اختيار الملف
  selectPdfBtn.addEventListener("click", () => {
    fileInput.click();
  });

  // عند اختيار ملف PDF
  fileInput.addEventListener("change", () => {
    const file = fileInput.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("pdfFile", file);

    fetch("upload_pdf.php", {
      method: "POST",
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if (data.status === "success") {
        const fullPath = data.path; // مثال: DocumentPDF/contract123.pdf
        attachmentField.value = fullPath;

        msg.textContent = `✅ تم رفع الملف: ${file.name}`;
        msg.style.color = "green";
        msg.style.display = "block";

        setTimeout(() => {
          msg.style.display = "none";
        }, 5000);
      } else {
        msg.textContent = `❌ فشل رفع الملف: ${data.message}`;
        msg.style.color = "red";
        msg.style.display = "block";
      }
    })
    .catch(err => {
      console.error("❌ خطأ في رفع الملف:", err);
      alert("❌ فشل الاتصال بالسيرفر");
    });
  });
});



function openPdfFromInput() {
  const input = document.getElementById("AttachmentPath_fullDe");
  const fileName = input.value.trim();

  if (!fileName) {
    alert("⚠️ لازم تدخل اسم الملف");
    return;
  }

  const currentPath = window.location.pathname;
  const folderPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
  const fullURL = `${window.location.origin}${folderPath}/${fileName}`;

  console.log("📂 الرابط النهائي:", fullURL);
  window.open(fullURL, "_blank");
}




//add & update
// تعريف المتغير بشكل عام في أعلى الملف
async function saveBalanceUnified() {
  const form = document.getElementById("add-balance-form");
  if (!form) return;

  const formData = new FormData(form);
  const data = {};
  formData.forEach((val, key) => data[key] = val);

  // إضافة الحقول اليدوية
  data.type = document.getElementById("ActionType")?.value || "";
  data.AttachmentPath = document.getElementById("AttachmentPath")?.value.trim() || "";

  // التحقق من الحقول المطلوبة
  const required = ["payment_method", "deposit_date", "balance_value", "type"];
  for (const k of required) {
    if (!data[k]) {
      showMessage("⚠️ برجاء استكمال بيانات الرصيد.", "error");
      return;
    }
  }

  // تحديد هل تعديل أم إضافة بناءً على tooltip الزر
  const saveBtn = document.getElementById("BTNSaveEdit");
  const tooltip = saveBtn?.querySelector(".tooltip");
  const icon = saveBtn?.querySelector("i");
  const tooltipText = tooltip?.textContent?.trim();
  const isEditMode = tooltipText === "تعديل";

  // ✅ إضافة ID في حالة التعديل
  if (isEditMode && editingBalanceId !== null) {
    data.id = editingBalanceId;

    // ✅ إظهار زر الحذف في وضع التعديل
    const deleteBtn = document.getElementById("BTNDelete");
    if (deleteBtn) deleteBtn.style.display = "inline-block";
  }

  const targetURL = isEditMode ? "update_transaction.php" : "save_balance.php";

  try {
    const res = await fetch(targetURL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data)
    });

    const text = await res.text();
    let json;

    try {
      json = JSON.parse(text);
    } catch {
      console.error("❌ الرد من السيرفر ليس بصيغة JSON:", text);
      showMessage("⚠️ الرد غير صالح من السيرفر", "error");
      return;
    }

    showMessage(json.message || '', json.status === "success" ? "success" : "error");

    if (json.status === "success") {
      form.reset();

      // ✅ إعادة تعيين ID بعد نجاح العملية
      editingBalanceId = null;

      // ✅ إعادة ضبط الواجهة
      document.getElementById("add-balance-section").style.display = "none";
      document.getElementById("transactions-section").style.display = "block";

      // ✅ إخفاء زر الحذف بعد التعديل
      const deleteBtn = document.getElementById("BTNDelete");
      if (deleteBtn) deleteBtn.style.display = "none";

      // ✅ تغيير التولتيب إلى "حفظ"
      if (tooltip) tooltip.textContent = "حفظ";

      // ✅ تغيير الأيقونة إلى شكل الحفظ
      if (icon) {
        icon.classList.remove("fa-edit");
        icon.classList.add("fa-save");
      }
    }

  } catch (err) {
    console.error("❌ خطأ في الاتصال:", err);
    showMessage("⚠️ فشل الاتصال بالسيرفر", "error");
  }
}



function deleteBalance() {
  if (!editingBalanceId) {
    alert("⚠️ لا يوجد رصيد محدد للحذف");
    return;
  }

  if (!confirm("هل أنت متأكد أنك تريد حذف هذا الرصيد؟")) return;

  fetch("delete_transaction.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    body: JSON.stringify({ id: editingBalanceId })
  })
  .then(res => res.json())
  .then(result => {
    alert(result.message);
    if (result.status === "success") {
      // ✅ إعادة ضبط النموذج
      const form = document.getElementById("add-balance-form");
      if (form) form.reset();

      editingBalanceId = null;

      // ✅ إخفاء النموذج وإظهار القائمة
      document.getElementById("add-balance-section").style.display = "none";
      document.getElementById("transactions-section").style.display = "block";

      // ✅ إخفاء زر الحذف
      const deleteBtn = document.getElementById("BTNDelete");
      if (deleteBtn) deleteBtn.style.display = "none";

      // ✅ إعادة زر الحفظ لحالته الطبيعية
      const saveBtn = document.getElementById("BTNSaveEdit");
      const tooltip = saveBtn?.querySelector(".tooltip");
      const icon = saveBtn?.querySelector("i");

      if (tooltip) tooltip.textContent = "حفظ";
      if (icon) {
        icon.classList.remove("fa-edit");
        icon.classList.add("fa-save");
      }

      // ✅ إعادة تحميل المعاملات لو عندك دالة زي loadTransactions()
      if (typeof loadTransactions === "function") {
        loadTransactions();
      }
    }
  })
  .catch(err => {
    console.error("❌ خطأ أثناء حذف الرصيد:", err);
    alert("❌ حدث خطأ أثناء عملية الحذف");
  });
}


