/* ============================================================
   style.css — تم دو رنگ پویا
   متغیرهای --theme-color و --theme-color2 از PHP تزریق می‌شوند
   ============================================================ */
:root{
  /* رنگ‌های تم — مقدار پیش‌فرض تا PHP بازنویسی کند */
  --theme-color:#1f3a63;
  --theme-color2:#552ef0;

  /* مشتقات خودکار از رنگ اصلی */
  --theme-dark:color-mix(in srgb, var(--theme-color) 72%, #0a1222);
  --theme-mid:var(--theme-color);
  --theme-light:color-mix(in srgb, var(--theme-color) 78%, #ffffff);
  --theme-soft:color-mix(in srgb, var(--theme-color) 14%, #ffffff);
  --theme2-dark:color-mix(in srgb, var(--theme-color2) 78%, #5c3a00);

  --card-dark-grad:linear-gradient(160deg,var(--theme-dark) 0%,var(--theme-mid) 55%,var(--theme-light) 100%);
  --glass-bg:rgba(255,255,255,0.14);
  --glass-blur:blur(10px);

  --bg-page:#eef2f8;
  --panel-light:#f4f6fa;
  --field-bg:#e7ebf3;

  --green:#3ecf6b;
  --red:#e0556b;
  --text-dark:color-mix(in srgb, var(--theme-color) 72%, #101828);
  --text-muted:#8a93a6;
  --text-on-dark:#ffffff;
  --text-on-dark-muted:color-mix(in srgb, #ffffff 70%, var(--theme-color));

  --r-xl:28px;
  --r-lg:20px;
  --r-md:14px;
  --r-pill:999px;

  --shadow-card:0 20px 40px rgba(22,35,63,0.18);
  --shadow-soft:0 8px 20px rgba(22,35,63,0.10);
  --shadow-float:0 12px 32px rgba(22,35,63,0.28),0 2px 8px rgba(22,35,63,0.12);

  --sp-1:4px; --sp-2:8px; --sp-3:12px; --sp-4:16px; --sp-5:20px; --sp-6:28px;

  --container:520px;
  --nav-gap:86px;
}

*,*::before,*::after{box-sizing:border-box;}
html{-webkit-text-size-adjust:100%;}

body{
  margin:0;
  font-family:"Vazirmatn",sans-serif;
  background:linear-gradient(180deg,#f2f5fb 0%,var(--bg-page) 60%,#e3e9f3 100%);
  color:var(--text-dark);
  line-height:1.6;
  min-height:100vh;
}

img{max-width:100%;display:block;}
a{text-decoration:none;color:inherit;}
button{font-family:inherit;cursor:pointer;}
h1,h2,h3,h4{margin:0;font-weight:700;}

.page,
.admin-page{
  max-width:var(--container);
  margin:0 auto;
  padding:var(--sp-4) var(--sp-4) calc(var(--nav-gap) + var(--sp-6));
}

/* ===== HEADER / TOPBAR ===== */
.storefront-header,
.admin-topbar{
  background:var(--card-dark-grad);
  border-radius:var(--r-xl);
  padding:var(--sp-5);
  margin-bottom:var(--sp-5);
  box-shadow:var(--shadow-card);
  color:var(--text-on-dark);
  position:relative;
  overflow:hidden;
}

.header-inner{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:var(--sp-3);
}

.brand-box{display:flex;align-items:center;gap:var(--sp-3);}

.logo{
  width:56px;height:56px;
  border-radius:50%;
  object-fit:cover;
  box-shadow:0 0 0 3px var(--glass-bg);
}

.brand-meta h1,
.admin-topbar h2{
  font-size:17px;
  color:var(--text-on-dark);
  margin:0;
}

.admin-topbar .who{
  font-size:13px;
  color:var(--text-on-dark-muted);
  font-weight:400;
}

.call-chip,
.store-link{
  display:inline-flex;
  align-items:center;
  gap:6px;
  padding:10px 18px;
  border-radius:var(--r-pill);
  background:var(--glass-bg);
  -webkit-backdrop-filter:var(--glass-blur);
  backdrop-filter:var(--glass-blur);
  color:var(--text-on-dark);
  font-size:13px;
  font-weight:600;
  white-space:nowrap;
  transition:transform .18s ease, box-shadow .18s ease;
}
.call-chip:hover,
.store-link:hover{transform:translateY(-2px);}
.call-chip svg,
.store-link svg{
  width:15px;height:15px;
  fill:none;stroke:currentColor;stroke-width:1.8;
  stroke-linecap:round;stroke-linejoin:round;
}

/* ===== BOTTOM NAV — iOS 26 floating glass pill ===== */
.admin-nav{
  position:fixed;
  bottom:14px;
  left:50%;
  transform:translateX(-50%);
  width:calc(100% - 2 * var(--sp-5));
  max-width:calc(var(--container) - 2 * var(--sp-5));
  display:flex;
  align-items:center;
  justify-content:space-around;
  gap:var(--sp-2);
  padding:var(--sp-3) var(--sp-4);
  background:color-mix(in srgb, var(--theme-color) 78%, transparent);
  -webkit-backdrop-filter:blur(24px) saturate(180%);
  backdrop-filter:blur(24px) saturate(180%);
  border-radius:var(--r-pill);
  box-shadow:var(--shadow-float),inset 0 1px 0 rgba(255,255,255,0.22),inset 0 -1px 0 rgba(255,255,255,0.06);
  z-index:100;
}

.nav-pill{
  display:flex;
  flex-direction:column;
  align-items:center;
  gap:4px;
  color:var(--text-on-dark-muted);
  font-size:12px;
  font-weight:500;
  padding:6px 12px;
  border-radius:var(--r-pill);
  transition:background .2s ease,color .2s ease;
}
.nav-pill .ic svg{
  width:20px;height:20px;
  fill:none;stroke:currentColor;stroke-width:1.8;
  stroke-linecap:round;stroke-linejoin:round;
}
.nav-pill.active,
.nav-pill:hover{
  color:var(--text-on-dark);
  background:rgba(255,255,255,0.14);
}
.nav-pill.danger{color:#ffb9c4;}
.nav-pill:first-child{
  background:transparent;
  width:auto;height:auto;
  border-radius:var(--r-pill);
  box-shadow:none;
  position:static;
  top:auto;
  flex:1;
}

/* ===== FLASH MESSAGE ===== */
.admin-msg{
  background:var(--theme-soft);
  border-radius:var(--r-md);
  padding:14px 18px;
  font-size:13.5px;
  color:var(--theme-mid);
  text-align:center;
  box-shadow:var(--shadow-soft);
  margin-bottom:var(--sp-4);
}

/* ===== SECTION / CARD ===== */
.admin-section,
.section{
  background:var(--panel-light);
  border-radius:var(--r-xl);
  box-shadow:var(--shadow-card);
  margin-bottom:var(--sp-5);
  overflow:hidden;
}

.section-head{
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:var(--sp-4) var(--sp-5) 0;
}
.section-title{
  font-size:16px;
  font-weight:700;
  color:var(--text-dark);
}

/* ===== ACCORDION ===== */
.acc-btn{
  width:100%;
  display:flex;
  align-items:center;
  gap:var(--sp-3);
  padding:var(--sp-5);
  background:transparent;
  border:none;
  text-align:right;
  color:var(--text-dark);
}
.acc-ic{
  width:42px;height:42px;
  flex-shrink:0;
  border-radius:50%;
  background:var(--theme-mid);
  display:flex;align-items:center;justify-content:center;
}
.acc-ic svg{
  width:18px;height:18px;
  fill:none;stroke:var(--text-on-dark);stroke-width:1.8;
  stroke-linecap:round;stroke-linejoin:round;
}
.acc-label{
  flex:1;
  font-size:15px;
  font-weight:700;
  display:flex;
  flex-direction:column;
  gap:2px;
}
.acc-hint{font-size:12.5px;color:var(--text-muted);font-weight:400;}
.acc-chevron{
  font-size:16px;
  color:var(--text-muted);
  transition:transform .2s ease;
}
.acc-btn[aria-expanded="true"] .acc-chevron{transform:rotate(180deg);}

.acc-content{
  max-height:0;
  overflow:hidden;
  padding:0 var(--sp-5);
  transition:max-height .3s ease;
}
.acc-content.open{
  max-height:6000px;
  padding:var(--sp-2) var(--sp-5) var(--sp-5);
  border-top:1px solid rgba(22,35,63,0.06);
}
.acc-content>h4{
  font-size:13px;
  font-weight:700;
  color:var(--text-muted);
  margin:var(--sp-4) 0 var(--sp-2);
}
.acc-content .input-box:first-child{margin-top:var(--sp-5);}
.acc-content .stack-gap .input-box:first-child{margin-top:var(--sp-5);}

/* ===== COLOR PICKER ROW (دو رنگ تم) ===== */
.color-row{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:var(--sp-3);
}
.color-box .input-box{margin:0;}
.input-box input[type="color"]{
  padding:6px;
  height:52px;
  cursor:pointer;
  border-radius:var(--r-md);
  border:2px solid #ffffff;
  box-shadow:var(--shadow-soft);
  background:var(--field-bg);
}

/* ===== FORM ===== */
.stack-gap{display:flex;flex-direction:column;gap:var(--sp-5);}

.input-box{position:relative;margin-bottom:var(--sp-5);}
.input-box input,
.input-box select,
.input-box textarea{
  width:100%;
  padding:14px 16px;
  border-radius:var(--r-md);
  border:none;
  background:var(--field-bg);
  font-family:inherit;
  font-size:14.5px;
  color:var(--text-dark);
  outline:none;
  margin-top:var(--sp-2);
}
.input-box input:focus,
.input-box select:focus,
.input-box textarea:focus{
  box-shadow:0 0 0 3px color-mix(in srgb, var(--theme-mid) 35%, transparent);
}
.input-box>label{
  position:absolute;
  top:-4px;right:14px;
  background:var(--panel-light);
  padding:0 8px;
  font-size:12px;
  font-weight:600;
  color:var(--text-muted);
  border-radius:6px;
  z-index:1;
}
.input-hint{display:block;margin-top:-6px;font-size:12.5px;color:var(--text-muted);}
.input-box.has-error input{box-shadow:0 0 0 2px var(--red);}
.edit-form .input-box>label,
.acc-content .input-box>label{background:var(--field-bg);}

/* ===== UPLOAD BOX ===== */
.upload-box{
  display:flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  padding:var(--sp-5);
  border-radius:var(--r-md);
  background:var(--theme-soft);
  color:var(--theme-mid);
  font-size:13.5px;
  font-weight:600;
  margin-bottom:var(--sp-3);
  cursor:pointer;
}
.upload-box svg{
  width:18px;height:18px;
  fill:none;stroke:var(--theme-mid);stroke-width:1.8;
  stroke-linecap:round;stroke-linejoin:round;
}

.admin-preview{margin-top:var(--sp-3);}
.admin-preview img{
  width:80px;height:80px;
  object-fit:cover;
  border-radius:var(--r-md);
  box-shadow:var(--shadow-soft);
}

.visually-hidden{
  position:absolute;width:1px;height:1px;
  overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;
}

/* ===== BUTTONS ===== */
.btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  padding:14px 24px;
  border-radius:var(--r-pill);
  border:none;
  background:var(--field-bg);
  color:var(--text-dark);
  font-family:inherit;
  font-size:14px;
  font-weight:600;
}
.btn-block{width:100%;}
.btn-primary{
  background:var(--card-dark-grad);
  color:var(--text-on-dark);
  box-shadow:var(--shadow-soft);
}
.btn-outline{
  background:transparent;
  color:var(--theme-mid);
  box-shadow:inset 0 0 0 1.5px var(--theme-mid);
}
.btn-danger{
  background:transparent;
  color:var(--red);
  box-shadow:inset 0 0 0 1.5px var(--red);
}
.btn-sm{padding:8px 16px;font-size:12.5px;}

/* ===== DRAG LIST ===== */
.drag-area{display:flex;flex-direction:column;gap:var(--sp-3);margin-bottom:var(--sp-4);}
.drag-item{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:var(--sp-3);
  padding:var(--sp-3);
  background:var(--panel-light);
  border-radius:var(--r-lg);
  box-shadow:var(--shadow-soft);
}
.drag-item.dragging{opacity:.4;}
.drag-main{display:flex;align-items:center;gap:var(--sp-3);min-width:0;}
.grip{color:var(--theme-mid);font-size:16px;}
.drag-item img,
.drag-area img{
  width:48px;height:48px;
  object-fit:cover;
  border-radius:50%;
}
.meta strong{
  display:block;
  font-size:14px;
  font-weight:700;
  color:var(--text-dark);
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  max-width:40vw;
}
.meta small{color:var(--text-muted);font-size:12px;}
.actions{display:flex;gap:6px;}

/* ===== EMPTY STATE ===== */
.empty-hint{
  border-radius:var(--r-lg);
  background:var(--field-bg);
  padding:var(--sp-6) var(--sp-4);
  text-align:center;
  color:var(--text-muted);
  margin-bottom:var(--sp-3);
}
.empty-hint svg{
  width:24px;height:24px;
  fill:none;stroke:var(--theme-mid);stroke-width:1.8;
  stroke-linecap:round;stroke-linejoin:round;
  margin:0 auto var(--sp-2);
  display:block;
}
.empty-hint p{margin:0 0 var(--sp-4);font-size:13.5px;}

/* ===== EDIT FORM DRAWER ===== */
.edit-form{
  display:none;
  margin-top:var(--sp-4);
  padding:var(--sp-5) var(--sp-5) var(--sp-2);
  border-radius:var(--r-lg);
  background:var(--field-bg);
}
.edit-form.open{display:block;}
.edit-form-title{
  font-size:13px;
  font-weight:700;
  color:var(--theme-mid);
  margin-bottom:var(--sp-4);
}

/* ===== STORIES ===== */
.stories-row{
  display:flex;
  gap:var(--sp-4);
  overflow-x:auto;
  padding:var(--sp-2) 0 var(--sp-4);
}
.story{display:flex;flex-direction:column;align-items:center;gap:var(--sp-1);min-width:64px;}
.story-ring{
  width:64px;height:64px;
  border-radius:50%;
  background:var(--card-dark-grad);
  padding:3px;
}
.story-img{
  width:100%;height:100%;
  border-radius:50%;
  overflow:hidden;
  background:var(--field-bg);
}
.story-img img{width:100%;height:100%;object-fit:cover;}
.story-label{font-size:11.5px;color:var(--text-muted);}

/* ===== SLIDER ===== */
.slider-row{
  display:flex;
  gap:var(--sp-4);
  overflow-x:auto;
  padding-bottom:var(--sp-4);
}
.slide{
  min-width:260px;
  border-radius:var(--r-xl);
  overflow:hidden;
  box-shadow:var(--shadow-card);
}
.slide img{width:100%;height:150px;object-fit:cover;}

/* ===== INFO STRIP ===== */
.info-strip{
  display:flex;
  align-items:center;
  gap:var(--sp-3);
  background:var(--panel-light);
  border-radius:var(--r-lg);
  padding:var(--sp-4);
  margin-bottom:var(--sp-3);
  box-shadow:var(--shadow-soft);
}
.info-icon{
  width:40px;height:40px;
  border-radius:50%;
  background:var(--theme-mid);
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;
}
.info-icon svg{width:18px;height:18px;fill:var(--text-on-dark);}
.info-text{display:flex;flex-direction:column;gap:2px;}
.info-text strong{font-size:13px;color:var(--text-dark);}
.info-text span{font-size:13px;color:var(--text-muted);}

/* ===== CATEGORIES GRID ===== */
.categories-grid{
  display:grid;
  grid-template-columns:repeat(2,1fr);
  gap:var(--sp-4);
  padding:var(--sp-4) var(--sp-5) var(--sp-5);
}
.cat-tile{
  display:flex;
  flex-direction:column;
  align-items:center;
  gap:var(--sp-2);
  background:var(--theme-soft);
  border-radius:var(--r-lg);
  padding:var(--sp-4);
  text-align:center;
}
.cat-tile img{
  width:100%;height:90px;
  object-fit:cover;
  border-radius:var(--r-md);
}
.cat-name{font-size:13px;font-weight:600;color:var(--text-dark);}

/* ===== PRODUCT CARDS ===== */
.product-carousel{
  display:flex;
  gap:var(--sp-4);
  overflow-x:auto;
  padding:var(--sp-4) var(--sp-5) var(--sp-5);
}
.product-card{
  min-width:160px;
  max-width:160px;
  flex:0 0 auto;
  background:var(--field-bg);
  border-radius:var(--r-lg);
  padding:var(--sp-3);
  box-shadow:var(--shadow-soft);
}
.p-img{position:relative;margin-bottom:var(--sp-2);}
.p-img img{
  width:100%;
  aspect-ratio:1/1;
  object-fit:cover;
  border-radius:var(--r-md);
}
/* برچسب تخفیف — رنگ مکمل تم */
.p-badge{
  position:absolute;
  top:8px;right:8px;
  background:var(--theme-color2);
  color:#ffffff;
  font-size:11px;
  font-weight:700;
  padding:3px 8px;
  border-radius:var(--r-pill);
}
.p-title{font-size:13.5px;font-weight:600;color:var(--text-dark);margin-bottom:4px;}
.p-price{font-size:14px;font-weight:700;color:var(--text-dark);}
.p-price .unit{font-size:11px;font-weight:400;color:var(--text-muted);margin-right:2px;}
.p-price .old{
  text-decoration:line-through;
  color:var(--text-muted);
  font-size:12px;
  font-weight:400;
  margin-right:6px;
}
.p-price .new{color:var(--theme2-dark);}

/* ===== FOOTER ===== */
.storefront-footer{
  text-align:center;
  padding:var(--sp-6) var(--sp-4);
  background:var(--card-dark-grad);
  border-radius:var(--r-xl);
  color:var(--text-on-dark);
  margin-top:var(--sp-5);
}
.storefront-footer .logo{margin:0 auto var(--sp-3);}
.storefront-footer .brand-name{font-size:15px;font-weight:700;margin-bottom:var(--sp-2);}
.foot-line{font-size:12.5px;color:var(--text-on-dark-muted);margin-bottom:4px;}
.foot-line a{color:var(--text-on-dark);}
.text-muted{color:var(--text-on-dark-muted);}

/* ===== RESPONSIVE ===== */
@media (max-width:480px){
  .page,
  .admin-page{padding:var(--sp-3) var(--sp-3) calc(var(--nav-gap) + var(--sp-4));}
  .categories-grid{grid-template-columns:repeat(2,1fr);gap:var(--sp-3);padding:var(--sp-3);}
  .product-card{min-width:140px;max-width:140px;}
  .slide{min-width:220px;}
  .slide img{height:120px;}
  .meta strong{max-width:32vw;}
  .nav-pill{padding:6px 8px;}
}

@media (max-width:360px){
  .brand-meta h1,
  .admin-topbar h2{font-size:15px;}
  .logo{width:44px;height:44px;}
  .nav-pill span{font-size:10px;}
  .color-row{grid-template-columns:1fr;}
}






































/* ============================================================
   افزوده‌ها — استوری، اسلایدر اصلی، ویترین، دو رنگ تم
   ============================================================ */

/* اسلایدر اصلی (نمایش اسلایدی) */
.main-slider{
  position:relative;
  border-radius:var(--r-xl);
  overflow:hidden;
  box-shadow:var(--shadow-card);
  margin-bottom:var(--sp-5);
  aspect-ratio:16/9;
}
.main-slide{
  position:absolute;inset:0;
  opacity:0;
  transition:opacity .6s ease;
}
.main-slide.active{opacity:1;}
.main-slide img{
  width:100%;height:100%;
  object-fit:cover;
  display:block;
}
.main-slider-dots{
  position:absolute;
  bottom:10px;left:0;right:0;
  display:flex;
  justify-content:center;
  gap:6px;
  z-index:2;
}
.main-slider-dots .dot{
  width:8px;height:8px;
  border-radius:50%;
  background:rgba(255,255,255,.45);
  cursor:pointer;
  transition:background .2s ease, transform .2s ease;
}
.main-slider-dots .dot.active{
  background:#fff;
  transform:scale(1.25);
}

/* پلیر استوری — فول‌اسکرین */
.story-player-overlay{
  display:none;
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.92);
  z-index:1000;
  align-items:center;
  justify-content:center;
}
.story-player-overlay.open{display:flex;}
.story-player-box{
  position:relative;
  width:min(92vw, 400px);
  aspect-ratio:9/16;
  max-height:92vh;
  border-radius:var(--r-lg);
  overflow:hidden;
  background:#111;
}
.sp-progress{
  position:absolute;
  top:8px;right:8px;left:8px;
  display:flex;
  gap:4px;
  z-index:3;
}
.sp-progress i{
  flex:1;
  height:3px;
  border-radius:2px;
  background:rgba(255,255,255,.3);
  overflow:hidden;
}
.sp-progress i span{
  display:block;
  height:100%;
  width:0;
  background:#fff;
  transition:width .1s linear;
}
.sp-images,
.sp-images img{
  position:absolute;inset:0;
  width:100%;height:100%;
}
.sp-images img{
  object-fit:cover;
  opacity:0;
  transition:opacity .4s ease;
}
.sp-images img.on{opacity:1;}
.sp-title{
  position:absolute;
  bottom:14px;right:12px;left:12px;
  z-index:3;
  color:#fff;
  font-size:15px;
  font-weight:700;
  text-align:center;
  text-shadow:0 1px 6px rgba(0,0,0,.85);
}

/* کاروسل ویترین — مثل کاروسل محصول موجود */
.section .product-carousel{scroll-snap-type:x mandatory;}
.section .product-carousel .product-card{scroll-snap-align:start;}

/* حالت دو رنگ — گرادیان سربرگ/دکمه از تم */
.storefront-header,
.admin-topbar,
.btn-primary,
.story-ring,
.info-icon,
.acc-ic{
  background:linear-gradient(135deg,var(--theme-color) 0%,var(--theme-color2) 130%);
}
.admin-nav{
  background:color-mix(in srgb, var(--theme-color) 72%, transparent);
}
.p-badge{
  background:var(--theme-color2);
}
.p-price .new{color:var(--theme-color2);}

















































<?php
session_start();
if (!isset($_SESSION['user'])) { header("Location: /login.php"); exit; }
$user = $_SESSION['user'];
require "admin.php";
/* ⚠️ گزینه ۱: تمام هندلرهای فرم (add_category / add_product / save_site / save_slider و…)
   فقط داخل admin.php هستند. این فایل هیچ هندلر فرمی ندارد تا دوبار ذخیره نشود.
   فقط دو کار AJAX پرداخت و چت پشتیبانی اینجا هندلر می‌شوند چون admin.php آن‌ها را ندارد. */

$root     = $_SERVER['DOCUMENT_ROOT'];
$siteDir  = "$root/sites/$user";
$dataFile = "$siteDir/information.json";

/* ══════ AJAX: پرداخت (زرین‌پال) — همیشه JSON، قبل از هر خروجی HTML ══════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax']) && $_POST['ajax'] === 'pay') {
    ini_set('display_errors', 0);
    header("Content-Type: application/json; charset=utf-8");
    $plan   = ($_POST['plan'] ?? '') === 'month' ? 'month' : 'year';
    $amount = intval($_POST['amount'] ?? 0);
    if ($amount < 1000) { echo json_encode(["success"=>false,"error"=>"مبلغ نامعتبر"]); exit; }

    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    $host   = $_SERVER['HTTP_HOST'] ?? "gotoshop.ir";
    $callback = "$scheme://$host/sites/$user/pay-verify.php";

    $data = [
        "merchant_id" => "6aa06e058c78e865687f7235",
        "amount"      => $amount * 10, /* تومان → ریال */
        "callback_url"=> $callback,
        "description" => "تمدید اشتراک گوتو — پلن " . ($plan === 'year' ? "سالانه" : "ماهانه") . " — کاربر $user"
    ];
    $ch = curl_init("https://api.zarinpal.com/pg/v4/payment/request.json");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_TIMEOUT => 20
    ]);
    $res  = json_decode(curl_exec($ch), true);
    $err  = curl_error($ch);
    curl_close($ch);

    if (!empty($res["data"]["authority"])) {
        $auth = $res["data"]["authority"];
        $pDir = "$root/payments";
        if (!is_dir($pDir)) mkdir($pDir, 0775, true);
        file_put_contents("$pDir/$auth.json", json_encode([
            "user"=>$user, "plan"=>$plan, "amount"=>$amount, "time"=>time()
        ], JSON_PRETTY_PRINT), LOCK_EX);
        echo json_encode(["success"=>true,"url"=>"https://www.zarinpal.com/pg/StartPay/$auth"]);
    } else {
        $code = $res["errors"]["code"] ?? 0;
        echo json_encode(["success"=>false,"error"=>"خطای درگاه (کد $code) $err"]);
    }
    exit;
}

/* ══════ متغیرهای نمایش (از admin.php می‌آیند) ══════ */
$slider      = array_slice($userData["slider"] ?? [], 0, 5);
$categories  = $userData["categories"] ?? [];
$storyCats    = array_values(array_filter($categories, fn($c) => ($c["mode"] ?? "") === "story"));
$squareCats   = array_values(array_filter($categories, fn($c) => ($c["mode"] ?? "") === "square"));
$showcaseCats = array_values(array_filter($categories, fn($c) => ($c["mode"] ?? "") === "showcase"));
$products = json_decode(@file_get_contents("$siteDir/products.json"), true);
if (!is_array($products)) $products = $userData["products"] ?? [];

/* انقضا و قیمت اشتراک */
$allU  = json_decode(@file_get_contents("$root/user.json"), true) ?: [];
$expAt = (int)($allU[$user]["expires_at"] ?? 0);
if (!$expAt) {
    $d = json_decode(@file_get_contents("$siteDir/data.json"), true) ?: [];
    $expAt = (int)($d["expires_at"] ?? 0);
}
$expireDaysLeft = $expAt ? (int)floor(($expAt - time()) / 86400) : 9999;

$priceData = json_decode(@file_get_contents("$root/main/prices.json"), true);
if (!is_array($priceData)) $priceData = ["price" => 3333000, "discounts" => []];
$yearlyPrice  = (int)($priceData["price"] ?? 3333000);
$monthlyPrice = (int)round($yearlyPrice / 12 / 1000) * 1000;
$discounts    = $priceData["discounts"] ?? [];

$JF = JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP;
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/vazirmatn@33.0.2/Vazirmatn-font-face.css" rel="stylesheet">
<title>پنل مدیریت — <?php echo htmlspecialchars($brand ?: 'گوتو'); ?></title>
<style>
:root{--theme-color:<?php echo htmlspecialchars($themeColor); ?>;--theme-color2:<?php echo htmlspecialchars($themeColor2); ?>;}
*{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;}
input,textarea,select{-webkit-user-select:text;user-select:text;font-size:16px;}
html{-webkit-text-size-adjust:100%;}
body{touch-action:manipulation;}
.admin-nav{display:flex;justify-content:center;align-items:center;gap:var(--sp-3);position:fixed;bottom:14px;left:50%;transform:translateX(-50%);padding:var(--sp-3) var(--sp-4);background:color-mix(in srgb, var(--theme-color) 78%, transparent);-webkit-backdrop-filter:blur(24px) saturate(180%);backdrop-filter:blur(24px) saturate(180%);border-radius:var(--r-pill);box-shadow:var(--shadow-float,0 12px 32px rgba(22,35,63,.28)),inset 0 1px 0 rgba(255,255,255,.22);z-index:100;}
.admin-nav .nav-pill{flex:0 0 auto;display:flex;align-items:center;justify-content:center;padding:10px;border-radius:50%;color:#fff;background:rgba(255,255,255,.12);transition:background .2s,transform .18s;}
.admin-nav .nav-pill:hover{background:rgba(255,255,255,.25);transform:translateY(-2px);}
.admin-nav .nav-pill .ic svg{width:20px;height:20px;display:block;}
.nav-dot{position:absolute;top:6px;left:6px;width:10px;height:10px;border-radius:50%;background:var(--red,#e0556b);display:none;}
.nav-pill{position:relative;}
.nav-pill.has-dot .nav-dot{display:block;}
.circle-row{display:flex;gap:var(--sp-3);overflow-x:auto;padding:var(--sp-2) 0 var(--sp-4);}
.c-tile{display:flex;flex-direction:column;align-items:center;gap:4px;min-width:72px;cursor:pointer;background:none;border:none;padding:0;}
.c-ring{width:72px;height:72px;border-radius:50%;border:3px solid var(--theme-color2);padding:3px;display:flex;align-items:center;justify-content:center;background:var(--field-bg);overflow:hidden;position:relative;}
.c-ring img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
.c-ring .plus{font-size:26px;color:var(--theme-mid,var(--theme-color));font-weight:300;}
/* باکس اسلایدر: مستطیلی ۴۸۸×۲۷۵ */
.c-ring.slider-style{width:120px;height:68px;border-radius:var(--r-md);border:2px solid var(--theme-color2);}
.c-ring.slider-style img,.c-ring.slider-style .plus{border-radius:var(--r-md);}
.slider-add-box{
  width:100%;max-width:488px;aspect-ratio:488/275;
  border:2px dashed var(--theme-color2);border-radius:var(--r-lg);
  background:var(--field-bg);display:flex;flex-direction:column;
  align-items:center;justify-content:center;gap:8px;cursor:pointer;
  color:var(--theme-mid,var(--theme-color));font-weight:700;font-size:14px;
  border:none;font-family:inherit;margin-bottom:var(--sp-4);
}
.slider-add-box:active{transform:scale(.99);}
.slider-add-box svg{width:34px;height:34px;}
.c-label{font-size:11px;color:var(--text-muted);max-width:72px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:500;align-items:flex-end;justify-content:center;}
.modal.open{display:flex;}
.modal-box{background:var(--panel-light);border-radius:var(--r-xl) var(--r-xl) 0 0;width:100%;max-width:520px;max-height:88vh;overflow-y:auto;padding:var(--sp-5);}
.modal-title{font-size:15px;font-weight:700;margin-bottom:var(--sp-4);display:flex;justify-content:space-between;align-items:center;gap:8px;}
.modal-title .x{background:none;border:none;font-size:18px;color:var(--text-muted);cursor:pointer;flex-shrink:0;}
.chat-box{display:flex;flex-direction:column;gap:8px;max-height:300px;overflow-y:auto;margin-bottom:var(--sp-3);}
.chat-msg{max-width:80%;padding:10px 14px;border-radius:var(--r-lg);font-size:13.5px;}
.chat-msg.me{align-self:flex-start;background:var(--theme-soft);color:var(--theme-mid);border-bottom-right-radius:4px;}
.chat-msg.them{align-self:flex-end;background:var(--field-bg);color:var(--text-dark);border-bottom-left-radius:4px;}
.chat-msg img{max-width:180px;border-radius:var(--r-md);margin-top:6px;display:block;}
.chat-msg small{display:block;font-size:10px;opacity:.6;margin-top:4px;}
.color-row{display:flex;gap:var(--sp-2);}
.color-box{flex:1;}
.color-picker{position:relative;}
.color-picker input[type="color"]{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;z-index:2;}
.color-swatch{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--field-bg);border-radius:var(--r-md);cursor:pointer;}
.color-swatch .dot{width:32px;height:32px;border-radius:50%;flex-shrink:0;border:3px solid #fff;box-shadow:0 0 0 1px rgba(0,0,0,.15);}
.color-swatch .hex{font-size:13px;font-family:monospace;direction:ltr;color:var(--text-muted);}
.upload-progress{display:none;margin:var(--sp-2) 0;}
.upload-progress.active{display:block;}
.upload-progress .track{height:8px;border-radius:var(--r-pill);background:var(--field-bg);overflow:hidden;}
.upload-progress .bar{height:100%;width:0;background:linear-gradient(90deg,var(--theme-color),var(--theme-color2));transition:width .2s;}
.upload-progress .pct{font-size:12px;color:var(--text-muted);text-align:center;margin-top:4px;}
.story-imgs-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;}
.story-img-tile{position:relative;aspect-ratio:1/1;border-radius:var(--r-md);overflow:hidden;background:var(--field-bg);touch-action:none;}
.story-img-tile img{width:100%;height:100%;object-fit:cover;pointer-events:none;}
.story-img-tile.dragging{opacity:.4;touch-action:none;}
.story-img-tile .del{position:absolute;top:4px;left:4px;z-index:2;width:22px;height:22px;border:none;border-radius:50%;background:var(--red,#e0556b);color:#fff;font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center;}
.sug-btn{display:flex;gap:8px;align-items:center;width:100%;padding:12px 14px;border-radius:var(--r-md);background:var(--field-bg);margin-bottom:8px;font-size:13.5px;border:none;font-family:inherit;cursor:pointer;text-align:right;color:var(--text-dark);}
.sug-btn.ok{opacity:.55;pointer-events:none;}
.sug-btn .ic{width:8px;height:8px;border-radius:50%;background:var(--red,#e0556b);flex-shrink:0;}
.sug-btn.ok .ic{background:var(--green,#3ecf6b);}
.share-chip{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border-radius:var(--r-pill);background:var(--glass-bg,rgba(255,255,255,.14));color:#fff;font-size:13px;font-weight:600;cursor:pointer;border:none;font-family:inherit;}
.topbar-actions{display:flex;gap:8px;align-items:center;}
.expire-banner{background:#fde8ec;color:#b03050;padding:14px 16px;border-radius:var(--r-lg);margin-bottom:var(--sp-4);font-size:13.5px;font-weight:600;text-align:center;cursor:pointer;border:none;font-family:inherit;width:100%;display:block;}
.drag-item.dragging{opacity:.4;touch-action:none;}
.map-chip{display:inline-flex;align-items:center;gap:6px;padding:9px 16px;border-radius:var(--r-pill);background:var(--theme-soft,var(--field-bg));color:var(--theme-mid,var(--theme-color));font-size:13px;font-weight:700;border:none;font-family:inherit;cursor:pointer;text-decoration:none;}
.map-chip:active{transform:scale(.97);}
.map-status{font-size:12px;color:var(--text-muted);margin-top:6px;min-height:16px;}
#mapPreview iframe{width:100%;height:180px;border:0;border-radius:var(--r-lg);display:block;}
.map-help{font-size:12px;color:var(--text-muted);line-height:1.9;margin:8px 0;}
</style>

<script>
const USER = '<?php echo htmlspecialchars($user, ENT_QUOTES); ?>';
const EXPIRE_DAYS   = <?php echo (int)$expireDaysLeft; ?>;
const YEARLY_PRICE  = <?php echo (int)$yearlyPrice; ?>;
const MONTHLY_PRICE = <?php echo (int)$monthlyPrice; ?>;
const DISCOUNTS = <?php echo json_encode((object)($discounts ?? []), $JF); ?>;

let sliderNames = [...<?php echo json_encode($slider, $JF); ?>];
const STORY_CATS = [...<?php echo json_encode(array_map(fn($s)=>[
    "id"=>intval($s['id']),"name"=>$s['name'],"title"=>($s['title']??''),
    "image"=>($s['image']??''),"images"=>implode(',',$s['images']??[])
], $storyCats), $JF); ?>];

function faNum(n){return String(n).replace(/\d/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]);}

/* ── آکاردئون ── */
function toggleAcc(id){
    const c = document.getElementById(id);
    if (!c) return;
    const b = document.querySelector('[data-target="'+id+'"]');
    const open = c.classList.toggle('open');
    if (b) b.setAttribute('aria-expanded', open?'true':'false');
    if (open) c.scrollIntoView({behavior:'smooth',block:'nearest'});
}
function openAcc(id){
    const c = document.getElementById(id);
    if (!c) return;
    c.classList.add('open');
    const b = document.querySelector('[data-target="'+id+'"]');
    if (b) b.setAttribute('aria-expanded','true');
    c.scrollIntoView({behavior:'smooth',block:'start'});
}

/* ── پاپ‌آپ‌ها ── */
function openModal(id){ const m=document.getElementById(id); if(m) m.classList.add('open'); }
function closeModal(id){ const m=document.getElementById(id); if(m) m.classList.remove('open'); }

/* ── آپلود ── */
function makeProgress(parent){
    const d=document.createElement('div');d.className='upload-progress';
    d.innerHTML='<div class="track"><div class="bar"></div></div><div class="pct"></div>';
    parent.appendChild(d);return d;
}
function uploadImage(input, hiddenId, cb, replace=false){
    const file = input.files[0]; if (!file) return;
    const wrap = input.parentElement.querySelector('.upload-progress') || makeProgress(input.parentElement);
    const bar = wrap.querySelector('.bar'), pct = wrap.querySelector('.pct');
    wrap.classList.add('active'); bar.style.width='0%'; pct.textContent='۰٪';
    const fd = new FormData(); fd.append('file', file);
    const xhr = new XMLHttpRequest();
    xhr.open('POST','upload-handler.php'); xhr.withCredentials = true;
    xhr.upload.onprogress = e => { if(e.lengthComputable){const p=Math.round(e.loaded/e.total*100);bar.style.width=p+'%';pct.textContent=faNum(p)+'٪';} };
    xhr.onload = () => {
        wrap.classList.remove('active');
        try{ const d = JSON.parse(xhr.responseText);
            if(!d.success){alert('خطا: '+(d.error||'نامشخص'));return;}
            if (cb) cb(d.name, d.url);
        }catch(e){alert('پاسخ نامعتبر');}
    };
    xhr.onerror = () => { wrap.classList.remove('active'); alert('خطا در ارتباط'); };
    xhr.send(fd); input.value='';
}

/* ── درگ: نگه‌داشتن ۲۵۰ms ── */
function getDragAfter(container,y){
    return [...container.querySelectorAll('.drag-item:not(.dragging)')]
        .reduce((closest,child)=>{
            const box=child.getBoundingClientRect();
            const offset=y-box.top-box.height/2;
            return (offset<0&&offset>closest.offset)?{offset,element:child}:closest;
        },{offset:-Infinity}).element;
}
function setupDragArea(areaId, hiddenId, onChange){
    const area = document.getElementById(areaId); if(!area) return;
    let dragItem = null;
    const collect = () => {
        const ids=[...area.querySelectorAll('.drag-item')].map(el=>el.dataset.id||el.dataset.name);
        const h=document.getElementById(hiddenId); if(h) h.value=ids.join(',');
        if(onChange) onChange(ids);
    };
    const bind = item => {
        item.setAttribute('draggable','true');
        item.addEventListener('dragstart',()=>{dragItem=item;item.classList.add('dragging');});
        item.addEventListener('dragend',()=>{item.classList.remove('dragging');dragItem=null;collect();});
        let holdT=null;
        item.addEventListener('touchstart',()=>{
            holdT=setTimeout(()=>{dragItem=item;item.classList.add('dragging');if(navigator.vibrate)navigator.vibrate(30);},250);
        },{passive:true});
        item.addEventListener('touchmove',e=>{
            if(!dragItem)return;
            e.preventDefault();
            const after=getDragAfter(area,e.touches[0].clientY);
            if(after!==dragItem){ if(!after)area.appendChild(dragItem); else area.insertBefore(dragItem,after); }
        },{passive:false});
        item.addEventListener('touchend',()=>{
            clearTimeout(holdT);
            if(dragItem){dragItem.classList.remove('dragging');dragItem=null;collect();}
        });
    };
    area.querySelectorAll('.drag-item').forEach(bind);
    area._bind = bind;
    area.addEventListener('dragover',e=>{
        e.preventDefault(); if(!dragItem)return;
        const after=getDragAfter(area,e.clientY);
        if(!after)area.appendChild(dragItem);else area.insertBefore(dragItem,after);
    });
}
function paintSwatch(input){
    const sw=input.parentElement.querySelector('.color-swatch'); if(!sw)return;
    sw.querySelector('.dot').style.background=input.value;
    sw.querySelector('.hex').textContent=input.value;
}

/* ── لوکیشن: کاربر خودش از گوگل مپ انتخاب می‌کند ── */
function openGoogleMaps(){
    /* گوگل مپ باز می‌شود؛ کاربر نقطه را انتخاب و «اشتراک‌گذاری» را کپی می‌کند */
    window.open('https://www.google.com/maps','_blank');
}
function saveMapLink(){
    const st = document.getElementById('mapStatus');
    const inp = document.getElementById('map_paste');
    if(!st || !inp) return;
    const raw = inp.value.trim();
    if(!raw){ st.textContent='لینک یا مختصات را جای‌گذاری کنید'; return; }
    /* پشتیبانی از: لینک اشتراک‌گذاری، لینک با @lat,lng یا ?q=, یا «lat,lng» خام */
    let m = raw.match(/@(-?\d+\.\d+),(-?\d+\.\d+)/)
         || raw.match(/[?&]q=(-?\d+\.\d+),(-?\d+\.\d+)/)
         || raw.match(/[?&]ll=(-?\d+\.\d+),(-?\d+\.\d+)/)
         || raw.match(/^(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)$/);
    if (!m){ st.textContent='لینک یا مختصات معتبر نیست — در گوگل مپ روی «اشتراک‌گذاری» بزنید'; return; }
    const url = 'https://www.google.com/maps?q=' + m[1] + ',' + m[2];
    document.getElementById('map_url').value = url;
    st.textContent = '📍 لوکیشن ثبت شد — «ذخیره اطلاعات سایت» را بزنید';
    renderMapPreview(url);
}
function removeMyLocation(){
    const inp = document.getElementById('map_url');
    if (inp) inp.value = '';
    const prev = document.getElementById('mapPreview');
    if (prev) prev.innerHTML = '';
    const st = document.getElementById('mapStatus');
    const paste = document.getElementById('map_paste');
    if (paste) paste.value = '';
    if (st) st.textContent = 'لوکیشن حذف شد — ذخیره کنید';
}
function renderMapPreview(url){
    const prev = document.getElementById('mapPreview');
    if (!prev) return;
    const m = url.match(/@(-?\d+\.\d+),(-?\d+\.\d+)/) || url.match(/[?&]q=(-?\d+\.\d+),(-?\d+\.\d+)/);
    if (m) prev.innerHTML = '<iframe loading="lazy" src="https://maps.google.com/maps?q='+m[1]+','+m[2]+'&z=15&output=embed"></iframe>';
    else prev.innerHTML = '';
}

/* ── اسلایدر: باکس مستطیلی ۴۸۸×۲۷۵ ── */
function renderSliderCircles(){
    const row = document.getElementById('sliderCircles');
    if (!row) return;
    row.innerHTML = '';
    for (let i=0;i<5;i++){
        const has = sliderNames[i];
        const t = document.createElement('button');
        t.type='button'; t.className='c-tile';
        t.innerHTML = '<span class="c-ring slider-style">'+(has
            ? '<img src="/sites/'+USER+'/uploads/'+has+'" alt="">'
            : '<span class="plus">+</span>')+'</span>'
            + '<span class="c-label">'+(has?'اسلاید '+faNum(i+1):'افزودن')+'</span>';
        t.onclick = () => {
            const sp=document.getElementById('slide_pos');
            if(!sp) return;
            document.getElementById('slide_pos').value = i;
            document.getElementById('slide_existing').value = has || '';
            document.getElementById('slidePreview').innerHTML = has ? '<img src="/sites/'+USER+'/uploads/'+has+'">' : '';
            document.getElementById('slide_upload').value = '';
            openModal('sliderModal');
        };
        row.appendChild(t);
    }
}
function sliderAddBox(){
    /* کلیک روی باکس مستطیلی: اولین جای خالی را برای اسلاید جدید باز می‌کند */
    let idx = sliderNames.findIndex(x=>!x);
    if (idx === -1) idx = 0;
    const sp=document.getElementById('slide_pos');
    if(!sp) return;
    sp.value = idx;
    document.getElementById('slide_existing').value = sliderNames[idx] || '';
    document.getElementById('slidePreview').innerHTML = sliderNames[idx] ? '<img src="/sites/'+USER+'/uploads/'+sliderNames[idx]+'">' : '';
    document.getElementById('slide_upload').value = '';
    openModal('sliderModal');
}
function saveSlide(){
    const pos = parseInt(document.getElementById('slide_pos').value);
    const name = document.getElementById('slide_upload').value || document.getElementById('slide_existing').value;
    if (!name){ alert('ابتدا تصویر انتخاب کنید'); return; }
    sliderNames[pos] = name;
    renderSliderCircles(); closeModal('sliderModal');
    const fd = new FormData();
    fd.append('save_slider','1'); fd.append('slider_names', sliderNames.filter(Boolean).join(','));
    fetch('admin-ui.php',{method:'POST',body:fd,credentials:'same-origin'}).then(()=>location.reload());
}
function deleteSlide(){
    const pos = parseInt(document.getElementById('slide_pos').value);
    sliderNames[pos] = '';
    renderSliderCircles(); closeModal('sliderModal');
    const fd = new FormData();
    fd.append('save_slider','1'); fd.append('slider_names', sliderNames.filter(Boolean).join(','));
    fetch('admin-ui.php',{method:'POST',body:fd,credentials:'same-origin'}).then(()=>location.reload());
}

/* ── استوری‌ها ── */
let storyCount = STORY_CATS.length;
function renderStoryCircles(){
    const row = document.getElementById('storyCircles');
    if (!row) return;
    row.innerHTML = '';
    STORY_CATS.forEach(s=>{
        const t=document.createElement('button');
        t.type='button';t.className='c-tile';
        t.innerHTML='<span class="c-ring">'+(s.image
            ? '<img src="/sites/'+USER+'/uploads/'+s.image+'" alt="">'
            : '<span class="plus">✎</span>')+'</span>'
            +'<span class="c-label">'+(s.title||s.name)+'</span>';
        t.onclick=()=>openStoryEditModal(s);
        row.appendChild(t);
    });
    for (let i=storyCount;i<5;i++){
        const t=document.createElement('button');
        t.type='button';t.className='c-tile';
        t.innerHTML='<span class="c-ring"><span class="plus">+</span></span><span class="c-label">استوری جدید</span>';
        t.onclick=()=>{
            const g=id=>document.getElementById(id);
            if(!g('story_modal_title')) return;
            g('story_modal_title').textContent='استوری جدید';
            g('story_form_mode').value='add';
            g('story_form_id').value='';
            g('f_story_name').value='';
            g('f_story_title').value='';
            g('f_story_image').value='';
            g('f_story_images').value='';
            g('storyProfilePrev').innerHTML='';
            g('storyGridEdit').innerHTML='';
            g('storySaveBtn').textContent='ایجاد استوری';
            openModal('storyModal');
        };
        row.appendChild(t);
    }
}
function openStoryEditModal(s){
    const g=id=>document.getElementById(id);
    if(!g('story_modal_title')) return;
    g('story_modal_title').textContent='ویرایش استوری';
    g('story_form_mode').value='edit';
    g('story_form_id').value=s.id;
    g('f_story_name').value=s.name;
    g('f_story_title').value=s.title;
    g('f_story_image').value=s.image;
    g('f_story_images').value=s.images;
    g('storyProfilePrev').innerHTML = s.image ? '<img src="/sites/'+USER+'/uploads/'+s.image+'">' : '';
    g('storySaveBtn').textContent='ذخیره ویرایش';
    renderStoryGrid(s.images);
    openModal('storyModal');
}
function renderStoryGrid(images){
    const grid=document.getElementById('storyGridEdit'); if(!grid) return;
    grid.innerHTML='';
    images.split(',').filter(Boolean).forEach(name=>{
        const t=document.createElement('div');
        t.className='story-img-tile drag-item'; t.dataset.name=name;
        t.innerHTML='<img src="/sites/'+USER+'/uploads/'+name+'" alt=""><button type="button" class="del">✕</button>';
        t.querySelector('.del').onclick=e=>{
            e.stopPropagation();
            const list=document.getElementById('f_story_images').value.split(',').filter(n=>n&&n!==name).join(',');
            document.getElementById('f_story_images').value=list;
            renderStoryGrid(list);
        };
        grid.appendChild(t);
        if (grid._bind) grid._bind(t);
    });
    setupDragArea('storyGridEdit','f_story_images',ids=>{
        document.getElementById('f_story_images').value=ids.filter(Boolean).join(',');
    });
}
function storyImgUploaded(name){
    const cur=document.getElementById('f_story_images').value;
    const list=(cur?cur+',':'')+name;
    document.getElementById('f_story_images').value=list;
    renderStoryGrid(list);
}
function storyProfileUploaded(name){
    document.getElementById('f_story_image').value=name;
    document.getElementById('storyProfilePrev').innerHTML='<img src="/sites/'+USER+'/uploads/'+name+'">';
}
function saveStoryForm(){
    const mode=document.getElementById('story_form_mode').value;
    const name=document.getElementById('f_story_name').value.trim();
    if(!name){alert('نام استوری الزامی است');return;}
    const fd=new FormData();
    if(mode==='edit'){ fd.append('edit_category','1'); fd.append('cat_id',document.getElementById('story_form_id').value); }
    else fd.append('add_category','1');
    fd.append('catname',name);
    fd.append('cattitle',document.getElementById('f_story_title').value);
    fd.append('catslug','');
    fd.append('catmode','story');
    fd.append('catimage_name',document.getElementById('f_story_image').value);
    fd.append('story_images',document.getElementById('f_story_images').value);
    fetch('admin-ui.php',{method:'POST',body:fd,credentials:'same-origin'}).then(()=>location.reload());
}

/* ── پشتیبانی: وصل به manageticket.php (روی خود دامنه) ── */
const TICKET_URL = '/manageticket.php';
function loadChat(){
    fetch(TICKET_URL+'?ajax=load&user='+encodeURIComponent(USER),{credentials:'same-origin'})
        .then(r=>{ if(!r.ok) throw 0; return r.json(); })
        .then(d=>{
            const box=document.getElementById('chatBox');
            if(!box) return;
            box.innerHTML=d.map(m=>
                '<div class="chat-msg '+(m.from==='user'?'me':'them')+'">'
                +(m.text?'<div>'+m.text.replace(/</g,'&lt;')+'</div>':'')
                +(m.image?'<img src="'+m.image+'">':'')
                +'<small>'+(m.from==='user'?'شما':'پشتیبانی')+' · '+m.time+'</small></div>'
            ).join('') || '<div style="text-align:center;color:var(--text-muted);font-size:13px;">پیامی نیست — سوال‌تان را بپرسید</div>';
            box.scrollTop=box.scrollHeight;
        })
        .catch(()=>{ const b=document.getElementById('chatBox'); if(b) b.innerHTML='<div style="text-align:center;color:var(--text-muted);font-size:13px;">خطا در بارگذاری</div>'; });
}
function sendTicket(){
    const textEl=document.getElementById('ticketText');
    const imgEl=document.getElementById('ticketImg');
    if(!textEl) return;
    const text=textEl.value.trim();
    const img=imgEl ? imgEl.value : '';
    if(!text && !img){alert('متن یا عکس بنویسید');return;}
    const fd=new FormData();
    fd.append('ajax','send'); fd.append('text',text); fd.append('image',img);
    fetch(TICKET_URL,{method:'POST',body:fd,credentials:'same-origin'})
        .then(()=>{textEl.value=''; if(imgEl) imgEl.value=''; loadChat();});
}
function checkUnread(){
    fetch(TICKET_URL+'?ajax=unread',{credentials:'same-origin'})
        .then(r=>{ if(!r.ok) throw 0; return r.json(); })
        .then(d=>{ const b=document.getElementById('supportBtn'); if(b) b.classList.toggle('has-dot', d.count>0); })
        .catch(()=>{});
}
setInterval(checkUnread, 15000);

/* ── پیشنهادها ── */
function showSuggestions(){
    const items=[];
    const add=(ok,label,target)=>items.push(
        '<button type="button" class="sug-btn'+(ok?' ok':'')+'" onclick="closeModal(\'sugModal\');openAcc(\''+target+'\')">'
        +'<span class="ic"></span>'+label+'</button>');
    const q=n=>document.querySelector('[name="'+n+'"]');
    add(q('brand') && !!q('brand').value,'نام فروشگاه','site');
    add(q('phone') && !!q('phone').value,'شماره تماس','site');
    add(q('address') && !!q('address').value,'آدرس','site');
    add(q('map_url') && !!q('map_url').value,'لوکیشن گوگل مپ','site');
    add(q('logo_name') && !!q('logo_name').value,'لوگو','site');
    add(sliderNames.filter(Boolean).length>0,'اسلایدر (حداقل یک اسلاید)','sliderSec');
    add(STORY_CATS.length>0,'حداقل یک استوری','storiesSec');
    add((<?php echo count($squareCats)+count($showcaseCats); ?>)>0,'حداقل یک دسته‌بندی','addcat');
    add((<?php echo count($products); ?>)>0,'حداقل یک محصول','addprod');
    const list=document.getElementById('sugList');
    if(list) list.innerHTML=items.join('');
    openModal('sugModal');
}

/* ── تمدید اجاره + پرداخت زرین‌پال ── */
let chosenPlan = null, chosenPrice = 0, discPercent = 0;
function openExpire(){
    const yp = document.getElementById('yp'), mp = document.getElementById('mp');
    if (yp) yp.textContent = faNum(YEARLY_PRICE.toLocaleString('en')) + ' تومان / سال';
    if (mp) mp.textContent = faNum(MONTHLY_PRICE.toLocaleString('en')) + ' تومان / ماه';
    openModal('expireModal');
}
function buyPlan(p){
    chosenPlan = p;
    chosenPrice = p === 'year' ? YEARLY_PRICE : MONTHLY_PRICE;
    applyDisc();
}
function applyDisc(){
    const info = document.getElementById('discInfo');
    const pay  = document.getElementById('payBtn');
    const codeEl = document.getElementById('discCode');
    if(!info || !pay || !codeEl) return;
    const code = codeEl.value.trim().toLowerCase();
    discPercent = (code && DISCOUNTS[code]) ? DISCOUNTS[code] : 0;
    if (code && !discPercent) { info.textContent='کد تخفیف نامعتبر است'; info.style.color='var(--red,#e0556b)'; pay.style.display='none'; return; }
    if (!chosenPlan) { info.textContent='ابتدا پلن سالانه یا ماهانه را انتخاب کنید'; info.style.color='var(--theme-color)'; pay.style.display='none'; return; }
    const final = Math.max(1000, Math.round(chosenPrice - chosenPrice * discPercent / 100));
    info.textContent = 'مبلغ قابل پرداخت: ' + faNum(final.toLocaleString('en')) + ' تومان' + (discPercent ? ' (با ٪'+faNum(discPercent)+' تخفیف)' : '');
    info.style.color = 'var(--green,#2e9e5b)';
    pay.style.display = 'block';
}
function startPay(){
    const pay = document.getElementById('payBtn');
    if(pay){ pay.disabled = true; pay.textContent = 'در حال اتصال به درگاه…'; }
    fetch('admin-ui.php',{method:'POST',credentials:'same-origin',
        body:new URLSearchParams({ajax:'pay',plan:chosenPlan,amount:Math.max(1000,Math.round(chosenPrice - chosenPrice*discPercent/100))})})
        .then(r=>r.json())
        .then(d=>{
            if(d.success && d.url){ location.href = d.url; }
            else { alert(d.error || 'خطا در اتصال به درگاه'); if(pay){ pay.disabled=false; pay.textContent='پرداخت و فعال‌سازی'; } }
        })
        .catch(()=>{ alert('خطا در اتصال به درگاه پرداخت'); if(pay){ pay.disabled=false; pay.textContent='پرداخت و فعال‌سازی'; } });
}

document.addEventListener('DOMContentLoaded',()=>{
    renderSliderCircles();
    renderStoryCircles();
    setupDragArea('cat-sort-area','cat_order');
    setupDragArea('product-sort-area','product_order');
    document.querySelectorAll('input[type="color"]').forEach(paintSwatch);
    const mapInput = document.getElementById('map_url');
    if (mapInput && mapInput.value) renderMapPreview(mapInput.value);
    checkUnread();
    const m=document.getElementById('expireMsg');
    if (EXPIRE_DAYS <= 0) {
        const h=document.getElementById('expireHead');
        if (h) h.textContent = '⛔ اجاره فضای شما تمام شده است';
        if (m) m.textContent = 'برای ادامه استفاده از فروشگاه، اشتراک خود را تمدید کنید.';
        openExpire();
    } else if (EXPIRE_DAYS <= 7) {
        if (m) m.textContent = 'فقط '+faNum(EXPIRE_DAYS)+' روز از اجاره شما باقی مانده. همین حالا تمدید کنید.';
        openExpire();
    }
});
</script>
</head>

<body>
<div class="admin-page">

<div class="admin-topbar">
    <div><h2>پنل مدیریت <span class="who">— <?php echo htmlspecialchars($user); ?></span></h2></div>
    <div class="topbar-actions">
        <button class="share-chip" onclick="showSuggestions()" title="پیشنهاد تکمیل">
            <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6M10 22h4M12 2a7 7 0 00-4 12.7c.6.5 1 1.3 1 2.1V17h6v-.2c0-.8.4-1.6 1-2.1A7 7 0 0012 2z"/></svg>
            پیشنهاد
        </button>
        <button class="share-chip" onclick="shareStore()" title="اشتراک‌گذاری">
            <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"/></svg>
            اشتراک
        </button>
    </div>
</div>

<?php if ($expireDaysLeft <= 7): ?>
<button type="button" class="expire-banner" onclick="openExpire()">⏳ <?php echo $expireDaysLeft <= 0 ? 'اجاره فضای شما تمام شده — برای تمدید و پرداخت بزنید' : faNum($expireDaysLeft).' روز تا پایان اجاره — برای تمدید بزنید'; ?></button>
<?php endif; ?>

<!-- ══════ ۱. اطلاعات سایت + لوکیشن از گوگل مپ ══════ -->
<div class="admin-section">
    <button class="acc-btn" data-target="site" aria-expanded="true" onclick="toggleAcc('site')">
        <span class="acc-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12L12 3l9 9v9H3z"/></svg></span>
        <span class="acc-label">اطلاعات سایت<span class="acc-hint">نام، تماس، دو رنگ، لوگو و لوکیشن</span></span>
        <span class="acc-chevron">▾</span>
    </button>
    <div id="site" class="acc-content open">
        <form method="POST" class="stack-gap">
            <div class="input-box filled"><input type="text" name="brand" value="<?php echo htmlspecialchars($brand); ?>" placeholder=" "><label>نام فروشگاه</label></div>
            <div class="input-box filled"><input type="tel" name="phone" value="<?php echo htmlspecialchars($phone); ?>" placeholder=" "><label>شماره تماس</label></div>
            <div class="input-box filled"><input type="text" name="address" value="<?php echo htmlspecialchars($address); ?>" placeholder=" "><label>آدرس</label></div>

            <a class="map-chip" href="https://www.google.com/maps" target="_blank">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
                🗺️ باز کردن گوگل مپ برای انتخاب لوکیشن
            </a>
            <div class="map-help">در گوگل مپ روی نقطه موردنظر لمس طولانی کنید تا سوزن بیفتد، بعد دکمه «اشتراک‌گذاری» را بزنید و لینک را کپی و همین‌جا جای‌گذاری کنید.</div>
            <div class="input-box filled"><input type="text" id="map_paste" dir="ltr" placeholder=" " oninput="if(event.target.value)saveMapLink()"><label>لینک یا مختصات کپی‌شده از گوگل مپ</label></div>
            <button type="button" class="map-chip" style="background:#fde8ec;color:#b03050;" onclick="removeMyLocation()">حذف لوکیشن</button>
            <div class="map-status" id="mapStatus"></div>
            <div id="mapPreview"></div>
            <input type="hidden" name="map_url" id="map_url" value="<?php echo htmlspecialchars($mapUrl); ?>">

            <div class="color-row">
                <div class="color-box color-picker">
                    <input type="color" name="theme_color" value="<?php echo htmlspecialchars($themeColor); ?>" oninput="paintSwatch(this)">
                    <div class="color-swatch"><span class="dot"></span><span class="hex"></span><small style="margin-inline-start:auto">رنگ اصلی</small></div>
                </div>
                <div class="color-box color-picker">
                    <input type="color" name="theme_color2" value="<?php echo htmlspecialchars($themeColor2); ?>" oninput="paintSwatch(this)">
                    <div class="color-swatch"><span class="dot"></span><span class="hex"></span><small style="margin-inline-start:auto">رنگ مکمل</small></div>
                </div>
            </div>
            <label class="upload-box" for="logoInput">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12M7 8l5-5 5 5M5 21h14"/></svg>
                آپلود لوگو
            </label>
            <input type="file" id="logoInput" class="visually-hidden" accept="image/*"
                   onchange="uploadImage(this,null,(n)=>{document.getElementById('logo_name').value=n;document.getElementById('logoPreview').innerHTML='<img src=\'/sites/'+USER+'/uploads/'+n+'\'>'},true)">
            <div class="upload-progress"><div class="track"><div class="bar"></div></div><div class="pct"></div></div>
            <div id="logoPreview" class="admin-preview">
                <?php if (!empty($logo)): ?><img src="/sites/<?php echo $user; ?>/uploads/<?php echo htmlspecialchars($logo); ?>" alt="لوگو"><?php endif; ?>
            </div>
            <input type="hidden" name="logo_name" id="logo_name" value="<?php echo htmlspecialchars($logo); ?>">
            <button class="btn btn-primary btn-block" name="save_site">ذخیره اطلاعات سایت</button>
        </form>
    </div>
</div>

<!-- ══════ ۲. اسلایدر — باکس مستطیلی ۴۸۸×۲۷۵ ══════ -->
<div class="admin-section">
    <button class="acc-btn" data-target="sliderSec" aria-expanded="false" onclick="toggleAcc('sliderSec')">
        <span class="acc-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="11" rx="2"/><path d="M2 20h20"/></svg></span>
        <span class="acc-label">اسلایدر<span class="acc-hint">اندازه پیشنهادی تصویر: ۴۸۸×۲۷۵</span></span>
        <span class="acc-chevron">▾</span>
    </button>
    <div id="sliderSec" class="acc-content">
        <button type="button" class="slider-add-box" onclick="sliderAddBox()">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M12 9v6M9 12h6"/></svg>
            افزودن اسلاید جدید (۴۸۸×۲۷۵)
        </button>
        <div class="circle-row" id="sliderCircles"></div>
    </div>
</div>

<!-- ══════ ۳. استوری‌ها ══════ -->
<div class="admin-section">
    <button class="acc-btn" data-target="storiesSec" aria-expanded="false" onclick="toggleAcc('storiesSec')">
        <span class="acc-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/></svg></span>
        <span class="acc-label">استوری‌ها<span class="acc-hint">+ = ساخت جدید · کلیک = ویرایش</span></span>
        <span class="acc-chevron">▾</span>
    </button>
    <div id="storiesSec" class="acc-content">
        <div class="circle-row" id="storyCircles"></div>
    </div>
</div>

<!-- ══════ ۴. افزودن دسته‌بندی (جدا) ══════ -->
<div class="admin-section">
    <button class="acc-btn" data-target="addcat" aria-expanded="false" onclick="toggleAcc('addcat')">
        <span class="acc-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M12 2v20M2 12h20"/></svg></span>
        <span class="acc-label">افزودن دسته‌بندی<span class="acc-hint">مربعی: c.webp · ویترین: s.webp</span></span>
        <span class="acc-chevron">▾</span>
    </button>
    <div id="addcat" class="acc-content">
        <form method="POST" class="stack-gap">
            <div class="input-box"><input type="text" name="catname" placeholder=" " required><label>نام دسته</label></div>
            <div class="input-box"><input type="text" name="catslug" placeholder=" "><label>Slug (اختیاری)</label></div>
            <div class="input-box filled">
                <select name="catmode" onchange="updateCatImgHint(this)">
                    <option value="square">مربعی (دو ستونه) — تصویر c.webp</option>
                    <option value="showcase">ویترین صفحه اصلی (کاروسل) — تصویر s.webp</option>
                </select>
                <label>نوع نمایش</label>
            </div>
            <div class="map-help" id="catImgHint">تصویر دسته: <b>c.webp</b> (از فایل‌های آماده استفاده می‌شود)</div>
            <div class="input-box"><input type="text" name="cattitle" placeholder=" "><label>تایتل (برای ویترین)</label></div>
            <button class="btn btn-primary btn-block" name="add_category">افزودن دسته</button>
        </form>

        <h4 style="margin-top:var(--sp-5)">مدیریت دسته‌ها — نگه دارید و بکشید</h4>
        <?php if (empty($squareCats) && empty($showcaseCats)): ?>
        <div class="empty-hint"><p>هنوز دسته‌بندی‌ای نساخته‌اید.</p></div>
        <?php else: ?>
        <form method="POST">
            <div id="cat-sort-area" class="drag-area">
                <?php foreach (array_merge($squareCats,$showcaseCats) as $c): ?>
                <div class="drag-item" data-id="<?php echo intval($c['id']); ?>">
                    <div class="drag-main"><span class="grip">⠿</span>
                        <?php
                        $ci = ($c['mode'] ?? '')==='showcase' ? 's.webp' : 'c.webp';
                        if (file_exists("$siteDir/uploads/$ci")): ?>
                        <img src="/sites/<?php echo $user; ?>/uploads/<?php echo $ci; ?>" alt="">
                        <?php elseif(!empty($c['image'])): ?>
                        <img src="/sites/<?php echo $user; ?>/uploads/<?php echo htmlspecialchars($c['image']); ?>" alt="">
                        <?php endif; ?>
                        <div class="meta"><strong><?php echo htmlspecialchars($c['name']); ?></strong>
                            <small><?php echo ($c['mode'] ?? '')==='showcase'?'ویترین (s.webp)':'مربعی (c.webp)'; ?></small></div>
                    </div>
                    <div class="actions"><a class="btn btn-danger btn-sm" href="?delcat=<?php echo intval($c['id']); ?>">حذف</a></div>
                </div>
                <?php endforeach; ?>
            </div>
            <input type="hidden" name="cat_order" id="cat_order">
            <button class="btn btn-block" name="save_cat_order" style="margin-top:var(--sp-3)">ذخیره ترتیب دسته‌ها</button>
        </form>
        <?php endif; ?>
    </div>
</div>

<!-- ══════ ۵. افزودن محصول (جدا) ══════ -->
<div class="admin-section">
    <button class="acc-btn" data-target="addprod" aria-expanded="false" onclick="toggleAcc('addprod')">
        <span class="acc-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><path d="M3 6h18M16 10a4 4 0 01-8 0"/></svg></span>
        <span class="acc-label">افزودن محصول<span class="acc-hint"><?php echo count($products); ?> محصول فعال</span></span>
        <span class="acc-chevron">▾</span>
    </button>
    <div id="addprod" class="acc-content">
        <form method="POST" enctype="multipart/form-data" class="stack-gap">
            <div class="input-box filled"><input type="text" name="pname" placeholder=" " required><label>نام محصول</label></div>
            <div class="input-box filled"><input type="number" name="pprice" placeholder=" " min="0" required><label>قیمت (تومان)</label></div>
            <div class="input-box filled"><input type="number" name="pstock" placeholder=" " min="0"><label>موجودی</label></div>
            <div class="input-box filled">
                <select name="pcategory" required>
                    <option value="">انتخاب دسته</option>
                    <?php foreach(array_merge($squareCats,$showcaseCats) as $cat): ?>
                    <option value="<?php echo htmlspecialchars($cat["name"]); ?>"><?php echo htmlspecialchars($cat["name"]); ?></option>
                    <?php endforeach; ?>
                </select>
                <label>دسته‌بندی</label>
            </div>
            <div class="input-box filled"><input type="number" name="pdiscount" placeholder=" " min="0" max="100"><label>درصد تخفیف</label></div>
            <div style="display:flex;gap:var(--sp-4);">
                <label style="display:flex;align-items:center;gap:6px;font-size:13.5px;"><input type="checkbox" name="ptags[]" value="selected"> منتخب</label>
                <label style="display:flex;align-items:center;gap:6px;font-size:13.5px;"><input type="checkbox" name="ptags[]" value="bestseller"> پرفروش</label>
            </div>
            <label class="upload-box" for="pimageInput">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12M7 8l5-5 5 5M5 21h14"/></svg>
                تصویر محصول (خودکار WebP می‌شود)
            </label>
            <input type="file" id="pimageInput" name="pimage" class="visually-hidden" accept="image/*"
                   onchange="document.getElementById('pimgPrev').innerHTML=this.files[0]?'<img src=\''+URL.createObjectURL(this.files[0])+'\'':''">
            <div class="upload-progress"><div class="track"><div class="bar"></div></div><div class="pct"></div></div>
            <div id="pimgPrev" class="admin-preview"></div>
            <button class="btn btn-primary btn-block" name="add_product">ذخیره محصول</button>
        </form>

        <h4 style="margin-top:var(--sp-5)">مدیریت محصولات — نگه دارید و بکشید</h4>
        <?php if (empty($products)): ?>
        <div class="empty-hint"><p>هنوز محصولی نیست.</p></div>
        <?php else: ?>
        <form method="POST">
            <div id="product-sort-area" class="drag-area">
                <?php foreach ($products as $p): ?>
                <div class="drag-item" data-id="<?php echo intval($p['id']); ?>">
                    <div class="drag-main"><span class="grip">⠿</span>
                        <?php if(!empty($p['image'])): ?><img src="/sites/<?php echo $user; ?>/uploads/<?php echo htmlspecialchars($p['image']); ?>" alt=""><?php endif; ?>
                        <div class="meta"><strong><?php echo htmlspecialchars($p['title']); ?></strong>
                            <small><?php echo number_format($p['price']); ?> تومان · <?php echo htmlspecialchars($p['category']); ?></small></div>
                    </div>
                    <div class="actions"><a class="btn btn-danger btn-sm" href="?delproduct=<?php echo intval($p['id']); ?>">حذف</a></div>
                </div>
                <?php endforeach; ?>
            </div>
            <input type="hidden" name="product_order" id="product_order">
            <button class="btn btn-block" name="save_product_order" style="margin-top:var(--sp-3)">ذخیره ترتیب محصولات</button>
        </form>
        <?php endif; ?>
    </div>
</div>

</div><!-- /.admin-page -->

<!-- ══════ پاپ‌آپ اسلایدر ══════ -->
<div class="modal" id="sliderModal">
    <div class="modal-box">
        <div class="modal-title"><span>تصویر اسلاید (۴۸۸×۲۷۵)</span><button type="button" class="x" onclick="closeModal('sliderModal')">✕</button></div>
        <input type="hidden" id="slide_pos" value="0"><input type="hidden" id="slide_existing" value="">
        <label class="upload-box" for="slideFile">انتخاب تصویر جدید</label>
        <input type="file" id="slideFile" class="visually-hidden" accept="image/*"
               onchange="uploadImage(this,'slide_upload',(n)=>{document.getElementById('slide_upload').value=n;document.getElementById('slidePreview').innerHTML='<img src=\'/sites/'+USER+'/uploads/'+n+'\'>'},true)">
        <div class="upload-progress"><div class="track"><div class="bar"></div></div><div class="pct"></div></div>
        <div id="slidePreview" class="admin-preview"></div>
        <div style="display:flex;gap:8px;margin-top:var(--sp-4);">
            <button type="button" class="btn btn-primary" style="flex:1" onclick="saveSlide()">ذخیره</button>
            <button type="button" class="btn btn-danger" onclick="deleteSlide()">حذف</button>
        </div>
        <input type="hidden" id="slide_upload" value="">
    </div>
</div>

<!-- ══════ پاپ‌آپ استوری ══════ -->
<div class="modal" id="storyModal">
    <div class="modal-box">
        <div class="modal-title"><span id="story_modal_title">استوری جدید</span><button type="button" class="x" onclick="closeModal('storyModal')">✕</button></div>
        <input type="hidden" id="story_form_mode" value="add">
        <input type="hidden" id="story_form_id" value="">
        <div class="input-box filled"><input type="text" id="f_story_name" placeholder=" "><label>نام استوری</label></div>
        <div class="input-box filled"><input type="text" id="f_story_title" placeholder=" "><label>تایتل (روی تصویر)</label></div>
        <h4 style="margin:var(--sp-3) 0 8px;font-size:13px;color:var(--text-muted);">پروفایل استوری (دایره)</h4>
        <label class="upload-box" for="storyProfFile">انتخاب پروفایل</label>
        <input type="file" id="storyProfFile" class="visually-hidden" accept="image/*"
               onchange="uploadImage(this,null,(n)=>storyProfileUploaded(n),true)">
        <div class="upload-progress"><div class="track"><div class="bar"></div></div><div class="pct"></div></div>
        <div id="storyProfilePrev" class="admin-preview"></div>
        <h4 style="margin:var(--sp-3) 0 8px;font-size:13px;color:var(--text-muted);">عکس‌های استوری (تا ۵) — نگه دارید و بکشید، ✕ حذف</h4>
        <div class="story-imgs-grid" id="storyGridEdit"></div>
        <input type="hidden" id="f_story_images" value="">
        <input type="hidden" id="f_story_image" value="">
        <label class="upload-box" for="storyImgFile" style="margin-top:12px">افزودن عکس به استوری</label>
        <input type="file" id="storyImgFile" class="visually-hidden" accept="image/*"
               onchange="uploadImage(this,null,(n)=>storyImgUploaded(n))">
        <div class="upload-progress"><div class="track"><div class="bar"></div></div><div class="pct"></div></div>
        <button type="button" class="btn btn-primary btn-block" id="storySaveBtn" style="margin-top:var(--sp-4)" onclick="saveStoryForm()">ایجاد استوری</button>
    </div>
</div>

<!-- ══════ پاپ‌آپ پشتیبانی ══════ -->
<div class="modal" id="supportModal" style="align-items:center;padding:16px;">
    <div class="modal-box" style="border-radius:var(--r-xl);">
        <div class="modal-title"><span>پشتیبانی گوتو</span><button type="button" class="x" onclick="closeModal('supportModal')">✕</button></div>
        <div class="chat-box" id="chatBox"></div>
        <div class="input-box"><textarea id="ticketText" rows="2" placeholder="پیام شما…" style="width:100%;padding:12px;border-radius:var(--r-md);border:none;background:var(--field-bg);font-family:inherit;resize:none;"></textarea></div>
        <label class="upload-box" for="ticketFile">پیوست عکس</label>
        <input type="file" id="ticketFile" class="visually-hidden" accept="image/*"
               onchange="uploadImage(this,null,(n)=>{document.getElementById('ticketImg').value=n;this.closest('label').innerHTML='عکس پیوست شد ✓'})">
        <input type="hidden" id="ticketImg" value="">
        <button type="button" class="btn btn-primary btn-block" onclick="sendTicket()">ارسال به پشتیبانی</button>
    </div>
</div>

<!-- ══════ پاپ‌آپ پیشنهاد ══════ -->
<div class="modal" id="sugModal" style="align-items:center;padding:16px;">
    <div class="modal-box" style="border-radius:var(--r-xl);">
        <div class="modal-title"><span>چه چیزهایی هنوز کامل نشده؟ (بزنید تا به بخش مربوطه بروید)</span><button type="button" class="x" onclick="closeModal('sugModal')">✕</button></div>
        <div id="sugList"></div>
    </div>
</div>

<!-- ══════ پاپ‌آپ تمدید اجاره + پرداخت ══════ -->
<div class="modal" id="expireModal" style="align-items:center;padding:16px;">
    <div class="modal-box" style="border-radius:var(--r-xl);text-align:center;">
        <div class="modal-title"><span id="expireHead">⏳ اجاره فضای شما رو به پایان است</span><button type="button" class="x" onclick="closeModal('expireModal')">✕</button></div>
        <p id="expireMsg" style="font-size:14px;color:var(--text-muted);line-height:2;margin:0 0 16px;"></p>
        <div style="display:flex;gap:8px;margin-bottom:16px;">
            <button type="button" class="btn btn-primary" style="flex:1" onclick="buyPlan('year')">سالانه<br><small id="yp"></small></button>
            <button type="button" class="btn" style="flex:1;background:var(--field-bg);color:var(--text-dark);" onclick="buyPlan('month')">ماهانه<br><small id="mp"></small></button>
        </div>
        <div class="input-box" style="margin-bottom:12px;">
            <input type="text" id="discCode" dir="ltr" placeholder=" " oninput="applyDisc()">
            <label>کد تخفیف (اختیاری)</label>
        </div>
        <p id="discInfo" style="font-size:13px;font-weight:700;color:var(--green,#2e9e5b);margin:0 0 12px;min-height:18px;"></p>
        <button type="button" id="payBtn" class="btn btn-primary btn-block" style="display:none;" onclick="startPay()">پرداخت و فعال‌سازی</button>
        <button type="button" class="btn btn-block" style="background:var(--field-bg);color:var(--text-dark);margin-top:8px;" onclick="closeModal('expireModal')">بعداً</button>
    </div>
</div>

<!-- ══════ منوی پایین ══════ -->
<nav class="admin-nav">
    <a href="/sites/<?php echo urlencode($user); ?>/index.php" class="nav-pill" title="ویترین">
        <span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12L12 3l9 9v9H3z"/></svg></span>
    </a>
    <a href="dashboard.php" class="nav-pill" title="داشبورد">
        <span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg></span>
    </a>
    <button type="button" class="nav-pill" id="supportBtn" title="پشتیبانی" onclick="openModal('supportModal');loadChat();">
        <span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"/></svg></span>
        <span class="nav-dot"></span>
    </button>
    <a href="settings.php" class="nav-pill" title="تنظیمات">
        <span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg></span>
    </a>
    <a href="logout.php" class="nav-pill" title="خروج" style="color:#ffb9c4;">
        <span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></svg></span>
    </a>
</nav>

<script>
function shareStore(){
    const link = 'https://gotoshop.ir/<?php echo htmlspecialchars($user); ?>';
    if (navigator.share) navigator.share({title:<?php echo json_encode($brand ?: "ویترین من", JSON_UNESCAPED_UNICODE); ?>, url:link}).catch(()=>{});
    else navigator.clipboard.writeText(link).then(()=>alert('لینک کپی شد:\n'+link));
}
function updateCatImgHint(sel){
    document.getElementById('catImgHint').innerHTML = sel.value === 'showcase'
        ? 'تصویر دسته: <b>s.webp</b> (از فایل‌های آماده استفاده می‌شود)'
        : 'تصویر دسته: <b>c.webp</b> (از فایل‌های آماده استفاده می‌شود)';
}
</script>
</body>
</html>