async function enterAdmin() {
  const username = document.getElementById("adminUsername").value;
  const password = document.getElementById("adminPassword").value;

  const response = await fetch("/admin-login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ username, password })
  });

  if (!response.ok) {
    alert("بيانات الدخول غير صحيحة");
    return;
  }

  document.getElementById("loginCard").classList.add("hidden");
  document.getElementById("dashboard").classList.remove("hidden");

  loadAdminOffers();
  loadSliders();
  loadEvents();
  loadSettings();
}
function showPanel(id, btn) {
  document
    .querySelectorAll(".panel")
    .forEach((p) => p.classList.remove("active"));
  document.getElementById(id).classList.add("active");
  document
    .querySelectorAll(".admin-tabs button")
    .forEach((b) => b.classList.remove("active"));
  btn.classList.add("active");
}
function openOfferForm() {
  resetOfferForm();
  offerForm.classList.add("show");
}
function closeOfferForm() {
  offerForm.classList.remove("show");
  resetOfferForm();
}
function resetOfferForm() {
  formTitle.textContent = "إضافة عرض سريع";
  offerId.value = "";
  offerTitle.value = "";
  oldPrice.value = "";
  newPrice.value = "";
  isActive.checked = true;
  isFeatured.checked = false;
  document.getElementById('imageUrl').value = '';
  document.getElementById('imageText').textContent = 'اضغط لاختيار صورة المنتج';
}

let allAdminOffers = [];

async function loadAdminOffers() {
  const response = await fetch("/offers");
  const offers = await response.json();

  allAdminOffers = offers;

  renderAdminOffers(offers);
}

function renderAdminOffers(offers) {
  document.getElementById("activeCount").textContent =
    offers.filter(o => o.is_active).length;

  document.getElementById("featuredAdminCount").textContent =
    offers.filter(o => o.is_featured).length;

  const offersList = document.getElementById("offersList");
  offersList.innerHTML = "";

  offers.forEach((o) => {
    offersList.innerHTML += `
      <article class="admin-offer-card ${o.is_active ? "" : "inactive"}">
        <div class="thumb">
          ${o.image_url ? `<img src="${o.image_url}" alt="${o.title}">` : "🛒"}
        </div>

        <div class="info">
          <h3>${o.title}</h3>
          <p>${o.old_price ?? ""} ← ${o.new_price ?? ""} ريال</p>

          ${o.is_featured ? '<span class="pill">مميز</span>' : ""}
          ${
            o.is_active
              ? '<span class="pill green">نشط</span>'
              : '<span class="pill gray">مخفي</span>'
          }
        </div>

        <div class="actions">
          <button type="button" onclick="editOffer(${o.id})">تعديل</button>
          <button type="button" onclick="toggleOffer(${o.id}, ${o.is_active})">
            ${o.is_active ? "إخفاء" : "إظهار"}
          </button>
          <button type="button" class="delete" onclick="deleteOffer(${o.id})">
            حذف
          </button>
        </div>
      </article>
    `;
  });
}

function searchOffers() {
  const word = document.getElementById("offerSearch").value.trim().toLowerCase();

  const filtered = allAdminOffers.filter((o) =>
    (o.title || "").toLowerCase().includes(word)
  );

  renderAdminOffers(filtered);
}
async function saveOffer() {
  const id = offerId.value;
  const payload = {
    title: offerTitle.value,
    image_url: document.getElementById('imageUrl').value,
    old_price: Number(oldPrice.value),
    new_price: Number(newPrice.value),
    is_featured: isFeatured.checked,
    is_active: isActive.checked,
  };
  if (!payload.title || !payload.new_price) {
    alert("اكتب اسم المنتج والسعر الجديد");
    return;
  }
  await fetch(id ? `/offers/${id}` : "/offers", {
    method: id ? "PUT" : "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  closeOfferForm();
  loadAdminOffers();
}
async function editOffer(id) {
  const offer = allAdminOffers.find((o) => o.id === id);

  if (!offer) {
    alert("العرض غير موجود");
    return;
  }

  document.getElementById("formTitle").textContent = "تعديل العرض";
  document.getElementById("offerId").value = offer.id;
  document.getElementById("offerTitle").value = offer.title;
  document.getElementById("oldPrice").value = offer.old_price ?? "";
  document.getElementById("newPrice").value = offer.new_price ?? "";
  document.getElementById("isActive").checked = offer.is_active;
  document.getElementById("isFeatured").checked = offer.is_featured;
  document.getElementById("imageUrl").value = offer.image_url || "";

  document.getElementById("imageText").textContent = offer.image_url
    ? "الصورة الحالية موجودة ✅"
    : "اضغط لاختيار صورة المنتج";

  document.getElementById("offerForm").classList.add("show");
  document.getElementById("offerForm").scrollIntoView({
  behavior: "smooth",
  block: "start"
});
}
async function toggleOffer(id, current) {
  const r = await fetch("/offers");
  const offers = await r.json();
  const o = offers.find((x) => x.id === id);
  if (!o) return;
  await fetch(`/offers/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      title: o.title,
      image_url: o.image_url || "",
      old_price: Number(o.old_price),
      new_price: Number(o.new_price),
      is_featured: o.is_featured,
      is_active: !current,
    }),
  });
  loadAdminOffers();
}
async function deleteOffer(id) {
  if (!confirm("متأكد تريد حذف العرض؟")) return;
  await fetch(`/offers/${id}`, { method: "DELETE" });
  loadAdminOffers();
}

async function uploadOfferImage() {
    const fileInput = document.getElementById('offerImage');
    const file = fileInput.files[0];
  
    if (!file) return;
  
    const formData = new FormData();
    formData.append('image', file);
  
    const response = await fetch('/upload-image', {
      method: 'POST',
      body: formData
    });
  
    const data = await response.json();
  
    document.getElementById('imageUrl').value = data.imageUrl;
    document.getElementById('imageText').textContent = 'تم اختيار الصورة ✅';
  }

  async function uploadSliderMedia() {
    const fileInput = document.getElementById('sliderMedia');
    const file = fileInput.files[0];
  
    if (!file) return;
  
    const formData = new FormData();
    formData.append('media', file);
  
    await fetch('/sliders', {
      method: 'POST',
      body: formData
    });
  
    fileInput.value = '';
  
    loadSliders();
  }
  
  async function loadSliders() {
    const response = await fetch('/sliders');
  
    const sliders = await response.json();
    document.getElementById("sliderCount").textContent =
  sliders.filter(s => s.is_active).length;
  
    const list = document.getElementById('sliderList');
  
    list.innerHTML = '';
  
    if (!sliders.length) {
      list.innerHTML = `
        <div class="empty-admin">
          لا توجد صور أو فيديوهات في السلايدر حتى الآن
        </div>
      `;
      return;
    }
  
    sliders.forEach(item => {
        list.innerHTML += `
        <div class="media-item">
      
          <div style="display:flex;gap:10px;align-items:center;">
      
            ${
              item.media_type === 'video'
                ? `
                  <video
                    src="${item.media_url}"
                    width="80"
                    height="60"
                    muted
                  ></video>
                `
                : `
                  <img
                    src="${item.media_url}"
                    width="80"
                    height="60"
                    style="
                      object-fit:cover;
                      border-radius:8px;
                    "
                  >
                `
            }
      
            <span>
              ${
                item.is_active
                  ? '🟢 نشط'
                  : '🔴 مخفي'
              }
            </span>
      
          </div>
      
          <div>
      
            <button
              onclick="toggleSlider(${item.id})">
      
              ${
                item.is_active
                  ? 'إخفاء'
                  : 'إظهار'
              }
      
            </button>
      
            <button
              onclick="deleteSlider(${item.id})">
      
              حذف
      
            </button>
      
          </div>
      
        </div>
      `;
    });
  }


  async function toggleSlider(id) {

    await fetch(
      `/sliders/${id}/toggle`,
      {
        method: 'PUT'
      }
    );
  
    loadSliders();
  
  }

  async function deleteSlider(id) {

    const ok =
      confirm(
        'متأكد تريد حذف هذا العنصر؟'
      );
  
    if (!ok) return;
  
    await fetch(
      `/sliders/${id}`,
      {
        method: 'DELETE'
      }
    );
  
    loadSliders();
  
  }

  function openEventForm() {
    document.getElementById("eventForm").classList.add("show");
  }
  
  function closeEventForm() {
    document.getElementById("eventForm").classList.remove("show");
    document.getElementById("eventId").value = "";
  
    document.getElementById("eventTitle").value = "";
    document.getElementById("eventStart").value = "";
    document.getElementById("eventEnd").value = "";
    document.getElementById("eventImageUrl").value = "";
    document.getElementById("eventImageText").textContent =
      "اضغط لاختيار صورة الفعالية";
    document.getElementById("eventActive").checked = true;
  }
  
  async function uploadEventImage() {
    const fileInput = document.getElementById("eventImage");
    const file = fileInput.files[0];
  
    if (!file) return;
  
    const formData = new FormData();
    formData.append("image", file);
  
    const response = await fetch("/upload-image", {
      method: "POST",
      body: formData,
    });
  
    const data = await response.json();
  
    document.getElementById("eventImageUrl").value = data.imageUrl;
    document.getElementById("eventImageText").textContent =
      "تم اختيار الصورة ✅";
  }
  
  async function saveEvent() {
    const id = document.getElementById("eventId").value;
  
    const payload = {
      title: document.getElementById("eventTitle").value,
      image_url: document.getElementById("eventImageUrl").value,
      start_date: document.getElementById("eventStart").value || null,
      end_date: document.getElementById("eventEnd").value || null,
      is_active: document.getElementById("eventActive").checked,
    };
  
    if (id) {
      await fetch(`/events/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });
    } else {
      await fetch("/events", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });
    }
  
    closeEventForm();
    loadEvents();
  }
  
  async function loadEvents() {
    const response = await fetch("/events");
    const events = await response.json();
  
    const list = document.getElementById("eventsList");
    list.innerHTML = "";
  
    if (!events.length) {
      list.innerHTML = `
        <div class="empty-admin">
          لا توجد فعاليات حتى الآن
        </div>
      `;
      return;
    }
  
    events.forEach((event) => {
      list.innerHTML += `
        <article class="admin-offer-card ${event.is_active ? "" : "inactive"}">
          <div class="thumb">
            ${
              event.image_url
                ? `<img src="${event.image_url}" alt="${event.title}">`
                : "🎉"
            }
          </div>
  
          <div class="info">
            <h3>${event.title}</h3>
            <p>
              ${event.start_date ?? ""}
              -
              ${event.end_date ?? ""}
            </p>
  
            ${
              event.is_active
                ? '<span class="pill green">نشط</span>'
                : '<span class="pill gray">مخفي</span>'
            }
          </div>
  
          <div class="actions">
          <button type="button" onclick="editEvent(${event.id})">تعديل</button>

          <button type="button" onclick="toggleEvent(${event.id})">
            ${event.is_active ? "إخفاء" : "إظهار"}
          </button>
          
          <button type="button" class="delete" onclick="deleteEvent(${event.id})">
            حذف
          </button>
          </div>
        </article>
      `;
    });
  }

  async function toggleEvent(id) {
    await fetch(`/events/${id}/toggle`, {
      method: "PUT",
    });
  
    loadEvents();
  }
  
  async function deleteEvent(id) {
    const ok = confirm("متأكد تريد حذف الفعالية؟");
  
    if (!ok) return;
  
    await fetch(`/events/${id}`, {
      method: "DELETE",
    });
  
    loadEvents();
  }

  async function editEvent(id) {
    const response = await fetch("/events");
    const events = await response.json();
  
    const event = events.find((e) => e.id === id);
  
    if (!event) return;
  
    document.getElementById("eventId").value = event.id;
    document.getElementById("eventTitle").value = event.title;
    document.getElementById("eventImageUrl").value = event.image_url || "";
    document.getElementById("eventStart").value = event.start_date
      ? event.start_date.split("T")[0]
      : "";
    document.getElementById("eventEnd").value = event.end_date
      ? event.end_date.split("T")[0]
      : "";
document.getElementById("eventActive").checked = event.is_active;  
    document.getElementById("eventImageText").textContent = event.image_url
      ? "الصورة الحالية موجودة ✅"
      : "اضغط لاختيار صورة الفعالية";
  
    document.getElementById("eventForm").classList.add("show");
  }

  async function loadSettings() {
    const response = await fetch("/settings");
    const settings = await response.json();
  
    document.getElementById("magazineTitle").value =
      settings.magazine_title || "";
  
    document.getElementById("websiteUrl").value =
      settings.website_url || "";
  
    document.getElementById("googleReviewUrl").value =
      settings.google_review_url || "";

      document.getElementById("backgroundColor").value =
  settings.background_color || "#f7faf6";

document.getElementById("headerColor").value =
  settings.header_color || "#ffffff";

document.getElementById("titleColor").value =
  settings.title_color || "#0b4b34";

document.getElementById("priceColor").value =
  settings.price_color || "#0b7a4d";

document.getElementById("discountColor").value =
  settings.discount_color || "#e92424";

  document.getElementById("installIconColor").value =
  settings.install_icon_color || "#0b6b46";

document.getElementById("shareIconColor").value =
  settings.share_icon_color || "#173d31";

document.getElementById("locationIconColor").value =
  settings.location_icon_color || "#214d85";

document.getElementById("productTitleColor").value =
  settings.product_title_color || "#222222";

  document.getElementById("oldPriceColor").value =
  settings.old_price_color || "#888888";

  document.getElementById("magazineTitleColor").value =
  settings.magazine_title_color || "#ffffff";

document.getElementById("showSlider").checked = settings.show_slider;
document.getElementById("showEvents").checked = settings.show_events;
document.getElementById("showFeatured").checked = settings.show_featured;
document.getElementById("showDaily").checked = settings.show_daily;
document.getElementById("showUpdateTime").checked = settings.show_update_time;
document.getElementById("featuredCardColor").value =settings.featured_card_color || "#ffffff";
document.getElementById("dailyCardColor").value =settings.daily_card_color || "#ffffff";


document.getElementById("sliderSeconds").value =
  settings.slider_image_seconds || 10;
  }
  
  async function saveSettings() {
    const response = await fetch("/settings", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        magazine_title: document.getElementById("magazineTitle").value,
        website_url: document.getElementById("websiteUrl").value,
        google_review_url: document.getElementById("googleReviewUrl").value,
              
        background_color: document.getElementById("backgroundColor").value,
        header_color: document.getElementById("headerColor").value,
        title_color: document.getElementById("titleColor").value,
        price_color: document.getElementById("priceColor").value,
        discount_color: document.getElementById("discountColor").value,
      
        show_slider: document.getElementById("showSlider").checked,
        show_events: document.getElementById("showEvents").checked,
        show_featured: document.getElementById("showFeatured").checked,
        show_daily: document.getElementById("showDaily").checked,
        show_update_time: document.getElementById("showUpdateTime").checked,
      
        slider_image_seconds: Number(document.getElementById("sliderSeconds").value),

        install_icon_color: document.getElementById("installIconColor").value,
        share_icon_color: document.getElementById("shareIconColor").value,
        location_icon_color: document.getElementById("locationIconColor").value,
        product_title_color: document.getElementById("productTitleColor").value,
        old_price_color: document.getElementById("oldPriceColor").value,
        magazine_title_color:document.getElementById("magazineTitleColor").value,
        featured_card_color: document.getElementById("featuredCardColor").value,
        daily_card_color: document.getElementById("dailyCardColor").value,
      })
    });
  const data = await response.json();

if (!response.ok) {
  alert("خطأ في الحفظ: " + data.error);
  console.log(data.error);
  return;
}
    alert("تم حفظ إعدادات المجلة");
  }


  function searchOffers() {
  const word = document.getElementById("offerSearch").value.trim();

  const filtered = allAdminOffers.filter((o) =>
    o.title.includes(word)
  );

  renderAdminOffers(filtered);
}
