<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/../lib/helpers.php';

$c = cfg();
$base = base_url_dir();

/** ✅ SOL GÖRSEL URL */
$leftImageUrl = "https://noth.wanyweb.com/tahta/img/nothla.png";

$board = (string)($_COOKIE['tahta_board_id'] ?? '');
if (!preg_match('/^B[a-f0-9]{20}$/', $board)) {
  $board = random_board_id();
  setcookie('tahta_board_id', $board, [
    'expires' => time() + 3600*24*365,
    'path' => ($c['cookie_path'] ?? '/tahta'),
    'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
}

$boardKey = hmac($board, $c['app_key']);
setcookie('tahta_board_key', $boardKey, [
  'expires'  => time() + 3600*24*365,
  'path'     => ($c['cookie_path'] ?? '/tahta'),
  'secure'   => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
  'httponly' => true,
  'samesite' => 'Lax',
]);

?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <title>Tahta</title>
  <meta name="theme-color" content="#F2F3F5">

  <!-- ✅ SADECE POPPINS -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

  <!-- ✅ QR render (tarayıcıda üret, server-side fetch'e bağlı kalma) -->
  <script defer src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>

  <style>
    :root{
      --bg:#f2f3f5;
      --card:#ffffff;
      --text:#0f1114;
      --muted:rgba(15,17,20,.60);
      --line:rgba(15,17,20,.12);
      --accent:#2d2fe6;
      --shadow:0 26px 90px rgba(0,0,0,.14);
      --r:18px;
    }
    *{box-sizing:border-box}
    html,body{height:100%}
    body{
      margin:0;
      font-family:"Poppins", sans-serif; /* ✅ sadece poppins */
      background:var(--bg);
      color:var(--text);
    }

    .hud{
      position:fixed;
      top:18px; left:18px; right:18px;
      display:flex;
      justify-content:flex-end;
      align-items:center;
      gap:14px;
      z-index:10;
      pointer-events:none;
    }
    .hud > *{pointer-events:auto}
    .hudStat{
      font-size:13px;
      color:rgba(15,17,20,.78);
      display:flex;gap:6px;user-select:none;
      font-weight:600;
    }
    .hudStat b{color:#111;font-weight:800}
    .hudBtn{
      border:0;border-radius:12px;
      padding:12px 18px;
      font-weight:800;
      font-size:13px;
      letter-spacing:.02em;
      cursor:pointer;color:#fff;
      background:var(--accent);
    }
    .hudBtn:active{transform:translateY(1px)}

    .overlay{
      position:fixed; inset:0;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:28px;
      background:transparent;
      z-index:5;
    }
    .overlay.hidden{display:none}

    .authCard{
      width:min(1380px, 96vw);
      height:min(740px, 94vh);
      background:var(--card);
      border-radius:var(--r);
      overflow:hidden;
      display:grid;
      grid-template-columns: 1fr 1.1fr;
      box-shadow:var(--shadow);
    }

    /* ✅ SOL: GÖRSEL %100 (IMG + object-fit) */
    .left{
      position:relative;
      color:#fff;
      background:#111;
      overflow:hidden;
    }
    .leftBgImg{
      position:absolute; inset:0;
      width:100%;
      height:100%;
      object-fit:cover;
      object-position:center;
      transform:scale(1.02);
      filter:saturate(1.05) contrast(1.05);
      z-index:0;
      pointer-events:none;
      user-select:none;
    }
    .leftOverlay{
      position:absolute; inset:0;
      background:
        radial-gradient(900px 600px at 20% 10%, rgba(0,0,0,.18), transparent 55%),
        radial-gradient(900px 600px at 90% 30%, rgba(0,0,0,.22), transparent 60%),
        linear-gradient(180deg, rgba(0,0,0,.20), rgba(0,0,0,.48));
      pointer-events:none;
      z-index:1;
    }
    .leftInner{
      position:relative; z-index:2;
      height:100%;
      padding:44px;
      display:flex;
      flex-direction:column;
      justify-content:space-between;
    }
    .leftKicker{font-size:13px;opacity:.92;letter-spacing:.06em;font-weight:600}
    .leftTitle{
      margin-top:14px;
      font-size:38px;
      line-height:1.12;
      font-weight:900;
      max-width:92%;
      text-shadow:0 16px 40px rgba(0,0,0,.35);
    }
    .leftFoot{
      display:flex;
      justify-content:space-between;
      align-items:flex-end;
      gap:14px;
      padding:14px 0 0 0;
    }
    .firmBlock{min-width:0}
    .firmName{font-weight:900;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .firmInfo{margin-top:6px;font-size:13px;opacity:.88;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .phone{font-weight:900;font-size:14px;white-space:nowrap;opacity:.94}

    /* ✅ SAĞ PANEL: büyütüldü */
    .right{
      padding:60px 76px;
      display:flex;
      flex-direction:column;
      justify-content:center;
      gap:16px;
      background:#fff;
      color:var(--text);
    }
    .h1{
      margin:0;
      font-size:40px;     /* ✅ daha büyük */
      font-weight:900;
      letter-spacing:-.02em;
      color:#111;
    }
    .p{
      margin:12px 0 0 0;
      font-size:18px;     /* ✅ daha büyük */
      color:var(--muted);
      line-height:1.65;
      font-weight:500;
    }

    .form{margin-top:20px;display:flex;flex-direction:column;gap:16px}

    .label{
      font-size:14px;     /* ✅ daha büyük */
      color:rgba(15,17,20,.78);
      font-weight:800;
      margin-top:2px;
      letter-spacing:.02em;
    }

    .fieldLike{
      width:100%;
      border:1px solid var(--line);
      border-radius:16px;
      padding:16px 18px;
      background:#fff;
      font-size:18px;     /* ✅ daha büyük */
      color:#111;
      min-height:56px;
      display:flex;
      align-items:center;
      overflow:hidden;
      font-weight:600;
    }

    /* ✅ SADECE POPPINS: monospace kaldırıldı */
    .fieldMono{
      font-family:"Poppins", sans-serif;
      font-size:14px;
      font-weight:600;
      word-break:break-all;
      line-height:1.45;
    }

    .row{display:flex;align-items:center;justify-content:space-between;gap:12px}
    .linkBtn{
      border:0;background:transparent;padding:0;
      font-size:14px;     /* ✅ daha büyük */
      font-weight:900;
      color:var(--accent);
      cursor:pointer;white-space:nowrap;
      letter-spacing:.02em;
    }

    .bigCode{
      border:0 !important;
      background:transparent !important;
      padding:0 !important;
      min-height:auto !important;
      font-weight:900;
      font-size:44px;     /* ✅ daha büyük */
      letter-spacing:.22em;
      line-height:1.1;
    }

    .qrArea{display:flex;justify-content:center;margin-top:18px}
    .qr{
      width:300px;height:300px; /* ✅ biraz daha büyük */
      border-radius:18px;
      background:#fff;
      border:1px solid rgba(15,17,20,.10);
      overflow:hidden;
      box-shadow:0 16px 44px rgba(0,0,0,.12);
      display:grid;
      place-items:center;
    }
    .qr img{width:100%;height:100%;display:block;object-fit:cover}

    .tiny{
      font-size:15px;     /* ✅ daha büyük */
      color:rgba(15,17,20,.62);
      line-height:1.65;
      margin-top:10px;
      font-weight:500;
    }
    .meta{
      margin-top:20px;
      display:flex;
      justify-content:space-between;
      gap:10px;
      font-size:14px;     /* ✅ daha büyük */
      color:rgba(15,17,20,.65);
      font-weight:600;
    }
    .meta b{color:#111;font-weight:900}
    .err{margin-top:12px;color:#b91c1c;font-size:13px;line-height:1.5;white-space:pre-wrap;font-weight:600}

    .visuallyHidden{display:none !important}

    @media(max-width:1080px){
      .authCard{grid-template-columns:1fr;height:auto}
      .left{min-height:320px}
      .leftInner{padding:28px}
      .right{padding:28px}
      .leftTitle{font-size:32px}
      .h1{font-size:32px}
      .p{font-size:16px}
      .label{font-size:13px}
      .fieldLike{font-size:16px}
      .bigCode{font-size:36px}
      .qr{width:260px;height:260px}
      .tiny{font-size:14px}
      .meta{font-size:13px}
    }
  </style>
</head>
<body>

  <div class="hud">
    <div class="hudStat">Durum: <b id="st">—</b></div>
    <button class="hudBtn" id="lockBtn">KİLİTLE</button>
  </div>

  <div id="overlay" class="overlay">
    <div class="authCard">

      <div class="left">
        <img
          class="leftBgImg"
          id="leftBgImg"
          src="<?= htmlspecialchars($leftImageUrl, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>"
          alt=""
          decoding="async"
          loading="eager"
          fetchpriority="high"
        />
        <div class="leftOverlay"></div>

        <div class="leftInner">
          <div>
            <div class="leftKicker">by Wany</div>
            <div class="leftTitle">Noth Remote<br>Uzaktan Kontrol Sistemi</div>
          </div>

          <div class="leftFoot">
            <div class="firmBlock">
              <div class="firmName">Noth Bilgi ve Eğitim Teknolojileri</div>
              <div class="firmInfo"> • by Wany Technologies</div>
            </div>
            <div class="phone">+90 850 840 30 82</div>
          </div>
        </div>
      </div>

      <div class="right">
        <div>
          <div id="title" class="h1">Ekran kilitli</div>
          <div id="desc" class="p">Açma/kapama ve eşleştirme işlemi <b>mobilde giriş yapan kullanıcı</b> tarafından yapılır.</div>
        </div>

        <!-- PAIR -->
        <div id="pairBox" class="form">
          <div class="row">
            <div class="label">Eşleştirme Kodu</div>
            <button class="linkBtn" id="refreshBtn" type="button">Kodu Yenile</button>
          </div>

          <!-- ✅ eşleştirme & kilitleme aynı font + aynı büyüklük -->
          <div id="pairCode" class="fieldLike bigCode">------</div>

          <div class="tiny">Mobilde <b>controller</b> sayfasında “EŞLEŞTİR” → QR okut / linki aç → sonra bu kodu gir.</div>
        </div>

        <!-- UNLOCK -->
        <div id="unlockBox" class="form" style="display:none">
          <div class="label">Güvenlik Kodu</div>
          <div id="unlockCode" class="fieldLike bigCode">------</div>

          <div class="visuallyHidden">
            <button class="linkBtn" id="copyUnlockBtn" type="button">Kopyala</button>
            <div id="unlockLink" class="fieldLike fieldMono">—</div>
          </div>

          <div class="tiny">Noth Remote → QR → Aktifleştir.</div>
        </div>

        <div class="qrArea">
          <div class="qr">
            <img id="qrImg" alt="QR">
          </div>
        </div>

        <div class="meta">
          <div>Tahta: <b id="bid">—</b></div>
          <div>Atama: <b id="own">—</b></div>
        </div>

        <div id="err" class="err" style="display:none"></div>
      </div>

    </div>
  </div>

<script>
(async function(){
  const BASE  = <?= json_encode($base) ?>;
  const BOARD = <?= json_encode($board) ?>;
  const POLL  = <?= (int)$c['poll_ms'] ?>;

  const st = document.getElementById('st');
  const overlay = document.getElementById('overlay');
  const bid = document.getElementById('bid');
  const own = document.getElementById('own');
  const qrImg = document.getElementById('qrImg');
  const lockBtn = document.getElementById('lockBtn');

  const title = document.getElementById('title');
  const desc  = document.getElementById('desc');

  const pairBox = document.getElementById('pairBox');
  const pairCodeEl = document.getElementById('pairCode');
  const refreshBtn = document.getElementById('refreshBtn');

  const unlockBox = document.getElementById('unlockBox');
  const unlockCodeEl = document.getElementById('unlockCode');
  const unlockLinkEl = document.getElementById('unlockLink');
  const copyUnlockBtn = document.getElementById('copyUnlockBtn');

  const err = document.getElementById('err');

  let lastFrozen = null;

  function showErr(msg){
    if(!msg){ err.style.display='none'; err.textContent=''; return; }
    err.style.display='block';
    err.textContent = msg;
  }

  async function post(action, data){
    const form = new URLSearchParams(data||{});
    const res = await fetch(`${BASE}/api.php?action=${encodeURIComponent(action)}`, {
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: form.toString(),
      cache:'no-store'
    });
    const text = await res.text();
    let j = null;
    try { j = JSON.parse(text); } catch(e){
      throw new Error(`HTTP ${res.status} | JSON değil:\n` + text.slice(0,400));
    }
    if(!res.ok) throw new Error(`HTTP ${res.status}:\n` + JSON.stringify(j, null, 2));
    return j;
  }

  function qrSrc(dataUrl){
    return `${BASE}/qr.php?d=` + encodeURIComponent(dataUrl);
  }

  async function setQr(url){
    // 1) Tarayıcıda üret (en sağlam)
    try{
      if (window.QRCode && typeof window.QRCode.toDataURL === 'function') {
        const data = await window.QRCode.toDataURL(url, { width: 300, margin: 1 });
        qrImg.src = data;
        return;
      }
    }catch(e){}

    // 2) Eski yol: server-side proxy
    qrImg.src = qrSrc(url);

    // 3) Proxy çalışmazsa: direkt dış servis (son çare)
    qrImg.onerror = () => {
      qrImg.onerror = null;
      qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=` + encodeURIComponent(url);
    };
  }

  function setPairUI(pairUrl, code){
    title.textContent = 'Ekran kilitli';
    desc.innerHTML = 'Açma/kapama ve eşleştirme işlemi <b>mobilde giriş yapan kullanıcı</b> tarafından yapılır.';
    pairBox.style.display = 'block';
    unlockBox.style.display = 'none';
    pairCodeEl.textContent = (code || '------');
    setQr(pairUrl);
  }

  function setUnlockUI(unlockUrl, unlockCode){
    title.textContent = 'Tahta şu anda kilitli';
    desc.innerHTML = 'Lütfen <b>aktifleştirin</b>. Bu işlem sadece <b>yetklili</b> tarafından yapılabilir.';
    pairBox.style.display = 'none';
    unlockBox.style.display = 'block';
    unlockCodeEl.textContent = (unlockCode || '------');
    unlockLinkEl.textContent = unlockUrl;
    setQr(unlockUrl);
  }

  async function boot(){
    showErr('');
    try{
      const j = await post('board_boot', { board: BOARD });

      bid.textContent = BOARD;
      own.textContent = j.owned ? 'Atandı' : 'Boş';

      st.textContent = j.is_frozen ? 'Kilitli' : 'Açık';
      overlay.classList.toggle('hidden', j.is_frozen === 0);

      lastFrozen = (j.is_frozen ? 1 : 0);

      if (j.is_frozen === 1) {
        if (j.owned === 1) {
          const unlockUrl = `${BASE}/controller.php?unlock=1&board=${encodeURIComponent(j.board)}&nonce=${encodeURIComponent(j.unlock_nonce||'')}&code=${encodeURIComponent(j.unlock_code||'')}`;
          setUnlockUI(unlockUrl, j.unlock_code || '------');
        } else {
          const pairUrl = `${BASE}/controller.php?pair=1&board=${encodeURIComponent(j.board)}&nonce=${encodeURIComponent(j.pairing_nonce)}`;
          setPairUI(pairUrl, j.pairing_code);
        }
      }

    }catch(e){
      showErr('board_boot çalışmadı:\n' + (e && e.message ? e.message : e) + `\n\nBASE=${BASE}\nBOARD=${BOARD}`);
    }
  }

  async function getStatus(){
    try{
      const res = await fetch(`${BASE}/api.php?action=status&board=${encodeURIComponent(BOARD)}`, {cache:'no-store'});
      const j = await res.json();
      if(!j.ok) return;

      const frozen = j.is_frozen ? 1 : 0;
      st.textContent = frozen ? 'Kilitli' : 'Açık';
      overlay.classList.toggle('hidden', frozen === 0);

      if (lastFrozen === null) {
        lastFrozen = frozen;
        if (frozen === 1) await boot();
        return;
      }
      if (frozen !== lastFrozen) {
        lastFrozen = frozen;
        if (frozen === 1) await boot();
      }
    }catch(e){}
  }

  async function freeze(){
    try{ await post('freeze', { board: BOARD }); }catch(e){}
    await boot();
  }

  function copyText(t){
    t = (t||'').trim();
    if(!t || t==='—') return;
    navigator.clipboard.writeText(t).catch(()=>{ prompt('Kopyala:', t); });
  }

  copyUnlockBtn.addEventListener('click', ()=>copyText(unlockLinkEl.textContent));
  // ✅ Kodu Yenile: sahipsiz tahta için direkt yeni PIN+nonce üret
  refreshBtn.addEventListener('click', async ()=>{
    try{
      const j = await post('pair_refresh', { board: BOARD });
      const pairUrl = `${BASE}/controller.php?pair=1&board=${encodeURIComponent(BOARD)}&nonce=${encodeURIComponent(j.pairing_nonce)}`;
      setPairUI(pairUrl, j.pairing_code);
    }catch(e){
      await boot();
    }
  });
  lockBtn.addEventListener('click', freeze);

  await boot();
  setInterval(getStatus, POLL);
})();
</script>
</body>
</html>
