<?php
declare(strict_types=1);
require_once __DIR__ . '/auth.php';
require_admin();
require_once __DIR__ . '/cron_runner.php'; // self-cron: room expiry check
require_once __DIR__ . '/layout.php';

$pdo  = lk_pdo();
$csrf = lk_csrf_token();
$flash = '';
$flashType = 'ok';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    lk_csrf_check();
    $act = (string)($_POST['act'] ?? '');

    if ($act === 'add_rooms') {
        $raw   = trim((string)($_POST['codes'] ?? ''));
        $lines = preg_split('/[\r\n,;|]+/', $raw);
        $added = 0; $skip = 0;
        $ins = $pdo->prepare("INSERT IGNORE INTO rooms (room_code, status, is_assigned, created_at, expires_at) VALUES (?, 'waiting', 0, NOW(), DATE_ADD(NOW(), INTERVAL 15 MINUTE))");
        foreach ($lines as $line) {
            $code = preg_replace('/\s+/', '', $line);
            if ($code === '') continue;
            $ins->execute([$code]);
            if ($ins->rowCount() > 0) $added++;
            else $skip++;
        }
        $flash = "Added $added room code(s)." . ($skip > 0 ? " ($skip duplicate skipped)" : '');

    } elseif ($act === 'delete_room') {
        $id = (int)($_POST['rid'] ?? 0);
        if ($id > 0) {
            $pdo->prepare("DELETE FROM rooms WHERE id=?")->execute([$id]);
            $flash = 'Room deleted.';
        }

    } elseif ($act === 'reset_room') {
        $id = (int)($_POST['rid'] ?? 0);
        if ($id > 0) {
            $pdo->prepare("UPDATE rooms SET is_assigned=0, status='waiting', assigned_user_id=NULL, assigned_at=NULL, expires_at=DATE_ADD(NOW(), INTERVAL 15 MINUTE), assigned_to=NULL, instance_id=NULL, started_at=NULL, closed_at=NULL WHERE id=?")->execute([$id]);
            $flash = 'Room reset to waiting.';
        }

    } elseif ($act === 'set_status') {
        $id     = (int)($_POST['rid'] ?? 0);
        $status = (string)($_POST['status'] ?? '');
        if ($id > 0 && in_array($status, ['waiting','assigned','started','closed'], true)) {
            $extraCols = '';
            $extraParams = [];
            if ($status === 'waiting') {
                $extraCols = ', is_assigned=0, assigned_at=NULL, expires_at=DATE_ADD(NOW(), INTERVAL 15 MINUTE), assigned_to=NULL, instance_id=NULL, started_at=NULL, closed_at=NULL';
            } elseif ($status === 'started') {
                $extraCols = ', started_at=NOW()';
            } elseif ($status === 'closed') {
                $extraCols = ', closed_at=NOW()';
            }
            $pdo->prepare("UPDATE rooms SET status=? $extraCols WHERE id=?")->execute([$status, $id]);
            $flash = "Room #$id → $status";
        }

    } elseif ($act === 'close_expired') {
        $n = (int)$pdo->exec("UPDATE rooms SET status='closed', closed_at=NOW() WHERE status='assigned' AND expires_at IS NOT NULL AND expires_at < NOW()");
        $flash = "Closed $n expired room(s).";

    } elseif ($act === 'clear_closed') {
        $n = (int)$pdo->exec("DELETE FROM rooms WHERE status='closed'");
        $flash = "Deleted $n closed room(s).";

    } elseif ($act === 'delete_all_waiting') {
        $n = (int)$pdo->exec("DELETE FROM rooms WHERE status='waiting' AND is_assigned=0");
        $flash = "Deleted $n waiting room(s).";
    }
}

// Filters
$filterStatus = (string)($_GET['status'] ?? 'all');
if (!in_array($filterStatus, ['all','waiting','assigned','started','closed'], true)) $filterStatus = 'all';
$search = trim((string)($_GET['q'] ?? ''));
$page   = max(1, (int)($_GET['p'] ?? 1));

$where  = '1=1';
$params = [];
if ($filterStatus !== 'all') { $where .= ' AND status=?'; $params[] = $filterStatus; }
if ($search !== '') {
    $where .= ' AND (room_code LIKE ? OR COALESCE(instance_id,"") LIKE ? OR COALESCE(assigned_to,"") LIKE ?)';
    $s = "%$search%";
    $params = array_merge($params, [$s, $s, $s]);
}

$perPage = 20;
$dbError = '';
$total = 0; $rooms = [];
$counts = ['all'=>0,'waiting'=>0,'assigned'=>0,'started'=>0,'closed'=>0];

try {
    $stCount = $pdo->prepare("SELECT COUNT(*) FROM rooms WHERE $where");
    $stCount->execute($params);
    $total  = (int)$stCount->fetchColumn();
    $pages  = max(1, (int)ceil($total / $perPage));
    $page   = min($page, $pages);
    $offset = ($page - 1) * $perPage;

    $stRooms = $pdo->prepare("SELECT * FROM rooms WHERE $where ORDER BY id DESC LIMIT ? OFFSET ?");
    $stRooms->execute(array_merge($params, [$perPage, $offset]));
    $rooms = $stRooms->fetchAll(PDO::FETCH_ASSOC);

    foreach (['waiting','assigned','started','closed'] as $s) {
        $st2 = $pdo->prepare("SELECT COUNT(*) FROM rooms WHERE status=?");
        $st2->execute([$s]);
        $counts[$s] = (int)$st2->fetchColumn();
    }
    $counts['all'] = array_sum([$counts['waiting'], $counts['assigned'], $counts['started'], $counts['closed']]);
} catch (Throwable $e) {
    $dbError = 'DB error: ' . $e->getMessage() . ' — Please run <a href="/fix_db.php">fix_db.php</a> or <a href="/install.php">install.php</a>.';
    $pages = 1;
}

lk_layout_head('Rooms');
lk_layout_nav('rooms');
?>
<style>
.status-sel{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.14);color:#e2e8f0;border-radius:8px;padding:4px 8px;font-size:11px;font-weight:700;font-family:inherit;cursor:pointer;outline:none;}
.status-sel:focus{border-color:#10b981;}
.status-sel option{background:#111c35;color:#e2e8f0;}
</style>
<div class="page">
  <div class="page-head">
    <h2>Room Management</h2>
    <p>Ludo King room code গুলো এখানে manage করুন।</p>
  </div>

  <?php if ($flash !== ''): ?>
    <div class="flash flash-<?= $flashType === 'ok' ? 'ok' : 'bad' ?>"><?= lk_e($flash) ?></div>
  <?php endif; ?>
  <?php if ($dbError !== ''): ?>
    <div class="flash flash-bad"><?= $dbError ?></div>
  <?php endif; ?>

  <!-- ADD ROOMS -->
  <div class="card" style="margin-bottom:20px;">
    <div class="sec-head">Add Room Codes</div>
    <form method="post">
      <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
      <input type="hidden" name="act" value="add_rooms">
      <div class="field">
        <label class="lbl">Room Codes — one per line, or comma/semicolon separated</label>
        <textarea class="inp" name="codes" rows="4" placeholder="13312434&#10;56789012&#10;..."></textarea>
      </div>
      <button class="btn btn-green" type="submit">➕ Add Rooms</button>
    </form>
  </div>

  <!-- STATUS COUNTS -->
  <div class="grid-4" style="margin-bottom:16px;">
    <?php foreach (['all','waiting','assigned','closed'] as $s): ?>
    <a href="?status=<?= $s ?><?= $search !== '' ? '&q='.urlencode($search) : '' ?>" style="text-decoration:none;">
      <div class="kpi" data-status="<?= $s ?>" style="cursor:pointer;<?= $filterStatus===$s ? 'border-color:var(--a1);box-shadow:0 0 14px rgba(16,185,129,.18);' : '' ?>">
        <div class="kpi-label"><?= ucfirst($s) ?></div>
        <div class="kpi-val" style="font-size:22px;<?= $s==='waiting' ? 'color:var(--gold)' : '' ?>"><?= number_format($counts[$s]) ?></div>
      </div>
    </a>
    <?php endforeach; ?>
  </div>

  <!-- BULK ACTIONS + SEARCH -->
  <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:16px;">
    <form method="post" style="display:inline;">
      <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
      <input type="hidden" name="act" value="close_expired">
      <button class="btn btn-gold btn-sm" type="submit">⏱ Close Expired</button>
    </form>
    <form method="post" style="display:inline;" onsubmit="return confirm('Delete ALL closed rooms?');">
      <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
      <input type="hidden" name="act" value="clear_closed">
      <button class="btn btn-red btn-sm" type="submit">🗑 Clear Closed</button>
    </form>
    <form method="post" style="display:inline;" onsubmit="return confirm('Delete ALL waiting rooms?');">
      <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
      <input type="hidden" name="act" value="delete_all_waiting">
      <button class="btn btn-ghost btn-sm" type="submit">🗑 Clear Waiting</button>
    </form>
    <form method="get" style="display:inline-flex;gap:6px;margin-left:auto;align-items:center;">
      <input type="hidden" name="status" value="<?= lk_e($filterStatus) ?>">
      <input class="inp" type="text" name="q" value="<?= lk_e($search) ?>" placeholder="Search code / instance…" style="width:190px;padding:7px 12px;font-size:13px;">
      <button class="btn btn-ghost btn-sm" type="submit">Search</button>
      <?php if ($search !== ''): ?><a href="?status=<?= lk_e($filterStatus) ?>" class="btn btn-ghost btn-sm">✕</a><?php endif; ?>
    </form>
  </div>

  <!-- TABLE -->
  <div class="card">
    <div style="overflow-x:auto;">
    <table class="tbl">
      <thead>
        <tr>
          <th>#</th>
          <th>Room Code</th>
          <th>Status</th>
          <th>Instance / Assigned To</th>
          <th>SS</th>
          <th>Expires</th>
          <th>Created</th>
          <th style="min-width:160px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($rooms)): ?>
          <tr><td colspan="8" style="text-align:center;color:var(--muted);padding:32px;">No rooms found.</td></tr>
        <?php endif; ?>
        <?php foreach ($rooms as $r):
          $st  = (string)($r['status'] ?? 'unknown');
          $exp = !empty($r['expires_at']) && strtotime((string)$r['expires_at']) < time();
          $cls = match($st) {
            'waiting'  => 'badge-muted',
            'assigned' => 'badge-gold',
            'started'  => 'badge-green',
            'closed'   => 'badge-red',
            default    => 'badge-muted'
          };
        ?>
        <tr data-rid="<?= (int)$r['id'] ?>">
          <td style="color:var(--muted);font-size:11px;"><?= (int)$r['id'] ?></td>
          <td>
            <span class="code" style="font-size:16px;"><?= lk_e((string)($r['room_code'] ?? '')) ?></span>
          </td>
          <td data-cell="status">
            <span class="badge <?= $cls ?>"><?= lk_e($st) ?><?= ($st==='assigned' && $exp) ? ' ⚠expired' : '' ?></span>
          </td>
          <td data-cell="instance" style="font-size:12px;color:var(--muted);">
            <?php $inst = (string)($r['instance_id'] ?? ''); $ato = (string)($r['assigned_to'] ?? ''); ?>
            <?= $inst !== '' ? lk_e($inst) : ($ato !== '' ? lk_e($ato) : '—') ?>
          </td>
          <td style="text-align:center;">
            <?php $ss = trim((string)($r['screenshot_path'] ?? '')); ?>
            <?php if ($ss !== ''): ?>
              <a href="/<?= lk_e($ss) ?>" target="_blank" title="View screenshot"
                 style="display:inline-block;width:36px;height:28px;background:rgba(16,185,129,.15);border:1px solid rgba(16,185,129,.3);border-radius:6px;text-align:center;line-height:28px;font-size:14px;text-decoration:none;">📷</a>
            <?php else: ?>
              <span style="color:var(--muted);font-size:11px;">—</span>
            <?php endif; ?>
          </td>
          <td data-cell="expires" style="font-size:11px;color:<?= ($st==='assigned'&&$exp)?'#fca5a5':'var(--muted)' ?>;">
            <?= $r['expires_at'] ? lk_e((string)$r['expires_at']) : '—' ?>
          </td>
          <td style="font-size:11px;color:var(--muted);"><?= lk_e((string)($r['created_at'] ?? '')) ?></td>
          <td>
            <div style="display:flex;gap:5px;align-items:center;flex-wrap:wrap;">
              <!-- Quick status change -->
              <form method="post" style="display:inline-flex;gap:4px;align-items:center;">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="set_status">
                <input type="hidden" name="rid" value="<?= (int)$r['id'] ?>">
                <select name="status" class="status-sel" onchange="this.form.submit()" title="Change status">
                  <?php foreach (['waiting','assigned','started','closed'] as $opt): ?>
                    <option value="<?= $opt ?>" <?= $st===$opt?'selected':'' ?>><?= $opt ?></option>
                  <?php endforeach; ?>
                </select>
              </form>
              <!-- Reset -->
              <?php if ($st !== 'waiting'): ?>
              <form method="post" style="display:inline;">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="reset_room">
                <input type="hidden" name="rid" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-ghost btn-sm" type="submit" title="Reset to waiting">↺</button>
              </form>
              <?php endif; ?>
              <!-- Delete -->
              <form method="post" style="display:inline;" onsubmit="return confirm('Delete room <?= (int)$r['id'] ?>?');">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="delete_room">
                <input type="hidden" name="rid" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-red btn-sm" type="submit" title="Delete">✕</button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    </div>

    <!-- PAGINATION -->
    <?php if ($pages > 1): ?>
    <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:16px;justify-content:center;">
      <?php for ($i = max(1,$page-3); $i <= min($pages,$page+3); $i++): ?>
        <a href="?status=<?= lk_e($filterStatus) ?>&p=<?= $i ?><?= $search!==''?'&q='.urlencode($search):'' ?>"
           class="btn btn-sm <?= $i===$page?'btn-green':'btn-ghost' ?>"><?= $i ?></a>
      <?php endfor; ?>
    </div>
    <?php endif; ?>
    <p style="font-size:12px;color:var(--muted);margin-top:10px;" id="liveStatus">
      Showing <?= count($rooms) ?> of <?= number_format($total) ?> rooms (page <?= $page ?>/<?= $pages ?>)
      &nbsp;<span id="liveDot" style="color:var(--muted);font-size:11px;">⏳ live</span>
    </p>
  </div>
</div>

<script>
(function(){
  var filterStatus = <?= json_encode($filterStatus) ?>;
  var searchQ      = <?= json_encode($search) ?>;
  var dot          = document.getElementById('liveDot');
  var INTERVAL     = 10000;

  var BADGE = {
    waiting : 'badge badge-muted',
    assigned: 'badge badge-gold',
    started : 'badge badge-green',
    closed  : 'badge badge-red',
  };

  function esc(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

  function patchRows(rows) {
    rows.forEach(function(r) {
      var tr = document.querySelector('tr[data-rid="' + parseInt(r.id) + '"]');
      if (!tr) return; // new row not on page — skip

      var st  = r.status || 'unknown';
      var exp = parseInt(r.db_is_expired) === 1;
      var cls = (exp && st === 'assigned') ? 'badge badge-red' : (BADGE[st] || 'badge badge-muted');
      var label = esc(st) + (exp && st === 'assigned' ? ' ⚠expired' : '');

      // patch status cell
      var stCell = tr.querySelector('[data-cell="status"]');
      if (stCell) stCell.innerHTML = '<span class="' + cls + '">' + label + '</span>';

      // patch instance cell
      var instCell = tr.querySelector('[data-cell="instance"]');
      if (instCell) instCell.textContent = r.instance_id || r.assigned_to || '—';

      // patch expires cell
      var expCell = tr.querySelector('[data-cell="expires"]');
      if (expCell) {
        expCell.textContent = r.expires_at || '—';
        expCell.style.color = (st === 'assigned' && exp) ? '#fca5a5' : 'var(--muted)';
      }

      // update the status <select> so it stays in sync
      var sel = tr.querySelector('select[name="status"]');
      if (sel) sel.value = st;
    });
  }

  function updateCounts(counts) {
    ['all','waiting','assigned','closed'].forEach(function(k){
      var el = document.querySelector('.kpi[data-status="' + k + '"] .kpi-val');
      if (el && counts[k] !== undefined) el.textContent = counts[k];
    });
  }

  function tick() {
    var url = '/api/rooms_live.php?status=' + encodeURIComponent(filterStatus);
    if (searchQ) url += '&q=' + encodeURIComponent(searchQ);

    fetch(url, {credentials:'same-origin'})
      .then(function(r){ return r.json(); })
      .then(function(data) {
        if (!data.ok) return;
        patchRows(data.rows);
        if (data.counts) updateCounts(data.counts);
        if (dot) {
          dot.textContent = '🟢 ' + new Date().toLocaleTimeString('bn-BD');
          dot.style.color = '#10b981';
        }
      })
      .catch(function(){
        if (dot) { dot.textContent = '🔴 offline'; dot.style.color = '#f87171'; }
      });
  }

  setTimeout(tick, 2000);
  setInterval(tick, INTERVAL);
})();
</script>
<?php lk_layout_foot(); ?>
