<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
    (function () {
        try { if (localStorage.getItem('aptechny-dvor-admin-token-v1')) return; } catch (e) {}
        function hmMetrikaUrl() {
            try { var u = new URL(location.href); ['track', 'token', 'reset', 'invite', 'key', 'code', 'sk'].forEach(function (k) { u.searchParams.delete(k); }); u.hash = ''; return u.toString(); } catch (e) { return location.origin + location.pathname; }
        }
        window.dataLayer = window.dataLayer || [];
        (function(m,e,t,r,i,k,a){
            m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
            m[i].l=1*new Date();
            for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
            k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)
        })(window, document,'script','https://mc.yandex.ru/metrika/tag.js?id=114074336', 'ym');

        ym(114074336, 'init', {ssr:true, clickmap:true, ecommerce:"dataLayer", referrer: document.referrer, url: hmMetrikaUrl(), accurateTrackBounce:true, trackLinks:true});
    })();
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/114074336" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->
<title>Быстрая заявка — Сельский двор</title>
<meta name="robots" content="noindex">
<style>
  * { box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; max-width: 480px; margin: 0 auto; padding: 24px 20px 40px; color: #2b2118; background: #fffaf3; }
  h1 { font-size: 1.35rem; margin: 0 0 6px; }
  p.lead { color: #8a7a63; margin: 0 0 24px; line-height: 1.5; }
  label { display: block; font-weight: 700; font-size: 0.9rem; margin: 18px 0 6px; }
  input, textarea { width: 100%; padding: 12px 14px; border: 1px solid #e6dcc8; border-radius: 10px; font-size: 1rem; font-family: inherit; background: #fff; color: #2b2118; }
  textarea { min-height: 100px; resize: vertical; }
  input:focus, textarea:focus { outline: none; border-color: #a8570e; }
  .hint { font-size: 0.82rem; color: #8a7a63; margin-top: 4px; }
  button { display: block; width: 100%; margin-top: 24px; background: linear-gradient(135deg,#e67a12,#a8570e); color: #fff; font-weight: 700; font-size: 1.05rem; padding: 15px; border: none; border-radius: 12px; cursor: pointer; }
  button:disabled { opacity: 0.6; }
  .err { color: #b71c1c; font-size: 0.88rem; margin-top: 10px; display: none; }
  .success { display: none; text-align: center; padding: 30px 10px; }
  .success .icon { font-size: 3rem; margin-bottom: 10px; }
  .success h2 { margin: 0 0 8px; font-size: 1.2rem; }
  .success p { color: #8a7a63; line-height: 1.5; }
  .matches { margin-top: 18px; text-align: left; }
  .match { display:block; padding:12px; margin:8px 0; border:1px solid #eadfc9; border-radius:10px; background:#fff; color:#2b2118; text-decoration:none; }
  .match strong { display:block; } .match small { color:#8a7a63; }
</style>
</head>
<body>

  <div id="formWrap">
    <h1>🛵 Быстрая заявка</h1>
    <p class="lead">Напишите, что вам нужно, — мы перезвоним и оформим заказ. Отвечаем обычно в течение дня.</p>

    <label for="name">Ваше имя</label>
    <input type="text" id="name" placeholder="Например: Айгуль" autocomplete="name">

    <label for="phone">Телефон *</label>
    <input type="tel" id="phone" placeholder="+7 700 000 00 00" autocomplete="tel" required>

    <label for="village">Куда доставить?</label>
    <input type="text" id="village" placeholder="Например: Тасты" autocomplete="address-level2">
    <div class="hint">Село/город помогает нам быстрее подобрать продавца.</div>

    <label for="text">Что вам нужно? *</label>
    <textarea id="text" placeholder="Например: творог 2 кг, мёд 1 банка" required></textarea>

    <p class="err" id="errMsg"></p>
    <button type="button" id="submitBtn">Отправить заявку</button>
  </div>

  <div class="success" id="successWrap">
    <div class="icon">✅</div>
    <h2>Заявка отправлена</h2>
    <p id="successText">Мы её уже видим и скоро свяжемся с вами по указанному телефону.</p>
    <div class="matches" id="matches"></div>
  </div>

<script>
(function () {
  var btn = document.getElementById("submitBtn");
  var errEl = document.getElementById("errMsg");
  var busy = false;

  try {
    var params = new URLSearchParams(window.location.search);
    var q = (params.get("q") || "").trim();
    var village = (params.get("village") || "").trim();
    var parts = [];
    if (q) parts.push("Ищу: " + q);
    if (village) { parts.push("Доставить в село: " + village); document.getElementById("village").value = village; }
    if (q) document.getElementById("text").value = "Ищу: " + q;
    else if (parts.length && !document.getElementById("text").value.trim()) document.getElementById("text").value = parts.join("\n");
  } catch (e) {}

  function escapeHtml(v) { return String(v == null ? "" : v).replace(/[&<>"']/g, function (c) { return {"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"}[c]; }); }

  btn.addEventListener("click", function () {
    if (busy) return;
    var name = document.getElementById("name").value.trim();
    var phone = document.getElementById("phone").value.trim();
    var text = document.getElementById("text").value.trim();
    var village = document.getElementById("village").value.trim();

    errEl.style.display = "none";
    if (!phone) { errEl.textContent = "Укажите телефон."; errEl.style.display = "block"; return; }
    if (!text) { errEl.textContent = "Опишите, что вам нужно."; errEl.style.display = "block"; return; }

    busy = true;
    btn.disabled = true;
    btn.textContent = "Отправляем…";

    fetch("api/orders.php?action=quick-request-submit", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: name, phone: phone, text: text, village: village })
    })
      .then(function (res) {
        return res.json().then(function (data) {
          if (!res.ok || data.error) throw new Error(data.error || "Не удалось отправить заявку.");
          return data;
        });
      })
      .then(function (data) {
        var matches = document.getElementById("matches");
        if (data && data.matched_count) {
          document.getElementById("successText").textContent = "Заявка принята. Мы сразу нашли " + data.matched_count + " подходящих вариантов — можно посмотреть их сейчас.";
          matches.innerHTML = data.matches.map(function (m) {
            return '<a class="match" href="' + m.url + '"><strong>' + escapeHtml(m.name) + '</strong><small>' + Number(m.price || 0).toLocaleString('ru-RU') + ' ₸' + (m.seller_name ? ' · ' + escapeHtml(m.seller_name) : '') + '</small></a>';
          }).join("");
        } else {
          document.getElementById("successText").textContent = "Заявка принята. Точного совпадения пока не нашли — оператор продолжит поиск.";
        }
        try {
          navigator.sendBeacon && navigator.sendBeacon("api/stats.php?action=event", new Blob([JSON.stringify({event:"demand_cta", page:location.pathname, target:"quick-request-submit", source:document.referrer||""})], {type:"application/json"}));
        } catch (e) {}
        document.getElementById("formWrap").style.display = "none";
        document.getElementById("successWrap").style.display = "block";
      })
      .catch(function (err) {
        errEl.textContent = err.message;
        errEl.style.display = "block";
        busy = false;
        btn.disabled = false;
        btn.textContent = "Отправить заявку";
      });
  });
})();
</script>
</body>
</html>
