
<?php
// ---- CONFIG ----
$modalId        = $modalId        ?? 'siteModal';
$modalTitle     = $modalTitle     ?? 'ປະກາດ';
$modalContent   = $modalContent   ?? '<p>ยินดีต้อนรับสู่เว็บไซต์ของเรา 🎉</p>';
$showAuto       = $showAuto       ?? true;            // เปิดอัตโนมัติรอบแรก?
$showOnceADay   = $showOnceADay   ?? false;            // วันละครั้ง?
$cookieName     = $cookieName     ?? 'modal_seen_today';
$cookieMaxAge   = $cookieMaxAge   ?? 60*60*24;        // 24 ชม
// ตรวจคุกกี้เพื่อกำหนดว่าจะ auto-open ไหม
$shouldAutoOpen = $showAuto && (!$showOnceADay || empty($_COOKIE[$cookieName]));
?>
<style>
  /* ===== Modal base ===== */
  .modal-overlay{position:fixed;inset:0;display:none;align-items:center;justify-content:center;
    background:rgba(0,0,0,.45);z-index:9998}
  .modal-overlay.is-open{display:flex}
  .modal{background:#fff;max-width:min(560px,92vw);width:100%;border-radius:16px;box-shadow:0 20px 50px rgba(0,0,0,.25);
    transform:translateY(10px) scale(.98);opacity:0;transition:opacity .18s ease, transform .18s ease;outline: none}
  .modal-overlay.is-open .modal{opacity:1;transform:translateY(0) scale(1)}
  .modal-header{padding:16px 20px;border-bottom:1px solid #eef2f7;display:flex;align-items:center;gap:12px}
  .modal-title{font-size:1.125rem;font-weight:700;line-height:1.3;margin:0;flex:1}
  .modal-close{appearance:none;border:0;background:transparent;font-size:20px;cursor:pointer;opacity:.7}
  .modal-close:hover{opacity:1}
  .modal-body{padding:18px 20px;color:#111827}
  .modal-footer{padding:16px 20px;border-top:1px solid #eef2f7;display:flex;justify-content:flex-end;gap:8px}
  .btn{padding:10px 14px;border-radius:10px;border:1px solid #e5e7eb;background:#0ea5e9;color:#fff;cursor:pointer}
  .btn.secondary{background:#fff;color:#111827}
  /* small screens */
  @media (max-width:480px){.modal{border-radius:14px}}
</style>

<div class="modal-overlay" id="<?= htmlspecialchars($modalId) ?>-overlay" aria-hidden="true">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="<?= htmlspecialchars($modalId) ?>-title" tabindex="-1">
    <div class="modal-header">
      <h2 id="<?= htmlspecialchars($modalId) ?>-title" class="modal-title"><?= $modalTitle ?></h2>
      <button class="modal-close" type="button" aria-label="Close" data-close>&times;</button>
    </div>
    <div class="modal-body">
      <?= $modalContent ?>
    </div>
    <div class="modal-footer">
      <button class="btn secondary" type="button" data-close>ປິດ</button>
      <button class="btn" type="button" data-close>ຕົກລົງ</button>
    </div>
  </div>
</div>

<script>
(function(){
  const overlay = document.getElementById("<?= $modalId ?>-overlay");
  const dialog  = overlay.querySelector(".modal");
  const focusable = 'a[href], button, textarea, input, select, [tabindex]:not([tabindex="-1"])';
  let previousFocus = null;

  function setCookie(name, days=1){
    const d = new Date(); d.setTime(d.getTime() + (days*24*60*60*1000));
    document.cookie = name + "=1; expires=" + d.toUTCString() + "; path=/";
  }
  function openModal(){
    previousFocus = document.activeElement;
    overlay.classList.add("is-open");
    overlay.setAttribute("aria-hidden","false");
    const first = dialog.querySelectorAll(focusable)[0] || dialog;
    first.focus({preventScroll:true});
    // บล็อก scroll พื้นหลังแบบง่าย ๆ
    document.body.style.overflow = 'hidden';
  }
  function closeModal(){
    overlay.classList.remove("is-open");
    overlay.setAttribute("aria-hidden","true");
    document.body.style.overflow = '';
    if (previousFocus) previousFocus.focus({preventScroll:true});
    <?php if ($showOnceADay): ?>
      setCookie("<?= $cookieName ?>", <?= round($cookieMaxAge/86400) ?>);
    <?php endif; ?>
  }

  // ปิดด้วยคลิกฉากหลัง
  overlay.addEventListener('click', (e)=>{ if(e.target === overlay) closeModal(); });
  // ปิดด้วยปุ่ม
  overlay.querySelectorAll("[data-close]").forEach(el=> el.addEventListener('click', closeModal));
  // ปิดด้วย ESC และทำ focus trap
  document.addEventListener('keydown', (e)=>{
    if(!overlay.classList.contains('is-open')) return;
    if(e.key === 'Escape') { e.preventDefault(); closeModal(); }
    if(e.key === 'Tab'){
      const nodes = dialog.querySelectorAll(focusable);
      if(!nodes.length) return;
      const first = nodes[0], last = nodes[nodes.length-1];
      if(e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
      else if(!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
    }
  });

  // เปิดอัตโนมัติรอบแรก (ตาม PHP คำนวณ)
  <?php if ($shouldAutoOpen): ?>
    window.addEventListener('load', openModal);
  <?php endif; ?>

  // ให้ global function เผื่อเรียกด้วยปุ่มจากหน้าอื่น
  window.open<?= preg_replace('/[^A-Za-z0-9_]/','',$modalId) ?> = openModal;
  window.close<?= preg_replace('/[^A-Za-z0-9_]/','',$modalId) ?> = closeModal;
})();
</script>
