<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../config/db.php';

// Resilient load — a single bad query must never blank the whole dashboard.
$dashError = '';
$stats = []; $totalSurveys = 0; $todaySurveys = 0; $totalParcels = 0;
$doneParcels = 0; $totalSurveyors = 0; $pendingSync = 0; $recent = [];
try {
    $stats = $pdo->query("
        SELECT zone,
               COUNT(*) AS total,
               SUM(survey_status = 'completed')   AS done,
               SUM(survey_status = 'in_progress') AS in_prog,
               SUM(survey_status = 'pending')     AS pending
        FROM parcels GROUP BY zone
    ")->fetchAll();

    $totalSurveys   = (int)$pdo->query("SELECT COUNT(*) FROM surveys")->fetchColumn();
    $todaySurveys   = (int)$pdo->query("SELECT COUNT(*) FROM surveys WHERE DATE(survey_date) = CURDATE()")->fetchColumn();
    $totalParcels   = (int)$pdo->query("SELECT COUNT(*) FROM parcels")->fetchColumn();
    $doneParcels    = (int)$pdo->query("SELECT COUNT(*) FROM parcels WHERE survey_status = 'completed'")->fetchColumn();
    $totalSurveyors = (int)$pdo->query("SELECT COUNT(*) FROM surveyors WHERE role = 'surveyor' AND is_active = 1")->fetchColumn();
    $pendingSync    = (int)$pdo->query("SELECT COUNT(*) FROM surveys WHERE sync_status = 'local'")->fetchColumn();

    $recent = $pdo->query("
        SELECT s.survey_date, s.owner_name, s.ward_no, p.parcel_no, p.zone, sv.name AS by_name
        FROM surveys s
        LEFT JOIN parcels p    ON p.id = s.parcel_id
        LEFT JOIN surveyors sv ON sv.id = s.surveyor_id
        ORDER BY s.created_at DESC LIMIT 8
    ")->fetchAll();
} catch (Throwable $e) {
    $dashError = $e->getMessage();
}

$pct = $totalParcels ? round($doneParcels / $totalParcels * 100, 1) : 0;
?>
<?php if ($dashError): ?>
<div class="bg-red-50 border border-red-200 text-red-700 rounded-xl px-5 py-3 mb-6 text-sm">
  ⚠ Dashboard query error: <?= htmlspecialchars($dashError) ?>
</div>
<?php endif; ?>
<?php

$zoneColor = [
    '0-300m'   => ['bar' => 'bg-red-500',    'badge' => 'bg-red-100 text-red-700',    'border' => 'border-red-400'],
    '300-400m' => ['bar' => 'bg-orange-500', 'badge' => 'bg-orange-100 text-orange-700', 'border' => 'border-orange-400'],
    '400-900m' => ['bar' => 'bg-blue-500',   'badge' => 'bg-blue-100 text-blue-700',   'border' => 'border-blue-400'],
];
?>

<!-- Page header -->
<div class="flex items-center justify-between mb-6">
  <div>
    <h2 class="text-xl font-bold text-slate-800">Dashboard</h2>
    <p class="text-sm text-slate-500 mt-0.5">Bancharedanda land compensation survey overview</p>
  </div>
  <div class="flex items-center gap-3">
    <span id="liveDot" class="inline-flex items-center gap-1.5 text-xs font-medium text-green-600">
      <span class="relative flex h-2 w-2">
        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
        <span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
      </span>
      LIVE
    </span>
    <span id="lastUpdated" class="text-xs text-slate-400">updating…</span>
    <span class="text-xs text-slate-400"><?= date('D, d M Y') ?></span>
  </div>
</div>

<!-- Overall progress bar -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-6">
  <div class="flex items-center justify-between mb-3">
    <span class="text-sm font-semibold text-slate-700">Overall Survey Progress</span>
    <span id="statPct" class="text-2xl font-bold text-blue-600"><?= $pct ?>%</span>
  </div>
  <div class="w-full bg-gray-100 rounded-full h-3 overflow-hidden">
    <div id="statBar" class="bg-gradient-to-r from-blue-500 to-green-500 h-3 rounded-full transition-all"
         style="width:<?= $pct ?>%"></div>
  </div>
  <div class="flex justify-between text-xs text-slate-400 mt-2">
    <span><span id="statDone"><?= number_format($doneParcels) ?></span> completed</span>
    <span><span id="statRemaining"><?= number_format($totalParcels - $doneParcels) ?></span> remaining</span>
  </div>
</div>

<!-- Stat cards -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
    <div class="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">Total Parcels</div>
    <div class="text-3xl font-bold text-slate-800"><?= number_format($totalParcels) ?></div>
    <div class="text-xs text-slate-400 mt-1">Registered parcels</div>
  </div>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
    <div class="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">Surveyed</div>
    <div id="statSurveyed" class="text-3xl font-bold text-green-600"><?= number_format($doneParcels) ?></div>
    <div class="text-xs text-slate-400 mt-1"><span id="statPctComplete"><?= $pct ?></span>% complete</div>
  </div>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
    <div class="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">Total Surveys</div>
    <div id="statTotalSurveys" class="text-3xl font-bold text-slate-800"><?= number_format($totalSurveys) ?></div>
    <div class="text-xs text-slate-400 mt-1">Today: <strong id="statTodaySurveys" class="text-blue-600"><?= $todaySurveys ?></strong></div>
  </div>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
    <div class="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">Active Surveyors</div>
    <div class="text-3xl font-bold text-slate-800">
      <span id="statActiveNow" class="text-green-600">0</span><span class="text-slate-300">/<?= $totalSurveyors ?></span>
    </div>
    <div class="text-xs text-slate-500 mt-1">
      online now · <span id="statPendingSync"><?= $pendingSync ?></span> unsynced
    </div>
  </div>
</div>

<!-- Zone breakdown -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
  <?php foreach ($stats as $z):
    $c   = $zoneColor[$z['zone']] ?? ['bar'=>'bg-gray-400','badge'=>'bg-gray-100 text-gray-700','border'=>'border-gray-300'];
    $pz  = $z['total'] ? round($z['done'] / $z['total'] * 100) : 0;
  ?>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 border-l-4 <?= $c['border'] ?>">
    <div class="flex items-center justify-between mb-3">
      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold <?= $c['badge'] ?>">
        Zone <?= htmlspecialchars($z['zone']) ?>
      </span>
      <span class="text-lg font-bold text-slate-700"><?= $pz ?>%</span>
    </div>
    <div class="w-full bg-gray-100 rounded-full h-1.5 mb-4">
      <div class="<?= $c['bar'] ?> h-1.5 rounded-full" style="width:<?= $pz ?>%"></div>
    </div>
    <div class="space-y-1.5 text-sm">
      <div class="flex justify-between">
        <span class="text-slate-500">Total</span>
        <span class="font-semibold"><?= number_format($z['total']) ?></span>
      </div>
      <div class="flex justify-between">
        <span class="text-green-600">Completed</span>
        <span class="font-semibold text-green-600"><?= number_format($z['done']) ?></span>
      </div>
      <div class="flex justify-between">
        <span class="text-amber-600">In Progress</span>
        <span class="font-semibold text-amber-600"><?= number_format($z['in_prog']) ?></span>
      </div>
      <div class="flex justify-between">
        <span class="text-slate-400">Pending</span>
        <span class="font-semibold text-slate-400"><?= number_format($z['pending']) ?></span>
      </div>
    </div>
  </div>
  <?php endforeach ?>
</div>

<!-- Field Team — Today (live) -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6">
  <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
    <h3 class="font-semibold text-slate-700">Field Team — Today</h3>
    <a href="live_map.php" class="text-xs text-blue-600 hover:text-blue-800 font-medium">Live map →</a>
  </div>
  <div id="teamList" class="divide-y divide-gray-50">
    <div class="px-6 py-8 text-center text-sm text-slate-400">Loading team…</div>
  </div>
</div>

<!-- Recent surveys -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
  <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
    <h3 class="font-semibold text-slate-700">Recent Surveys</h3>
    <a href="surveys.php" class="text-xs text-blue-600 hover:text-blue-800 font-medium">View all →</a>
  </div>
  <div class="overflow-x-auto">
    <table class="w-full text-sm">
      <thead>
        <tr class="bg-gray-50 text-xs text-slate-500 uppercase tracking-wide">
          <th class="px-6 py-3 text-left font-medium">Date</th>
          <th class="px-6 py-3 text-left font-medium">Parcel</th>
          <th class="px-6 py-3 text-left font-medium">Zone</th>
          <th class="px-6 py-3 text-left font-medium">Ward</th>
          <th class="px-6 py-3 text-left font-medium">Owner</th>
          <th class="px-6 py-3 text-left font-medium">Surveyor</th>
        </tr>
      </thead>
      <tbody id="recentBody" class="divide-y divide-gray-50">
        <?php foreach ($recent as $r): ?>
        <tr class="hover:bg-gray-50 transition-colors">
          <td class="px-6 py-3 text-slate-600"><?= htmlspecialchars($r['survey_date']) ?></td>
          <td class="px-6 py-3 font-mono text-xs text-slate-700"><?= htmlspecialchars($r['parcel_no']) ?></td>
          <td class="px-6 py-3">
            <?php $zc = $zoneColor[$r['zone']] ?? ['badge'=>'bg-gray-100 text-gray-600']; ?>
            <span class="inline-flex px-2 py-0.5 rounded-full text-xs font-medium <?= $zc['badge'] ?>">
              <?= htmlspecialchars($r['zone']) ?>
            </span>
          </td>
          <td class="px-6 py-3 text-slate-600"><?= htmlspecialchars($r['ward_no']) ?></td>
          <td class="px-6 py-3 text-slate-700"><?= htmlspecialchars($r['owner_name']) ?></td>
          <td class="px-6 py-3 text-slate-500"><?= htmlspecialchars($r['by_name']) ?></td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>
</div>

<script>
(function () {
  const $ = id => document.getElementById(id);
  const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
  const nf = n => Number(n).toLocaleString();

  const zoneBadge = z => {
    if (z && z.indexOf('0-300') === 0)   return 'bg-red-100 text-red-700';
    if (z && z.indexOf('300-400') === 0) return 'bg-orange-100 text-orange-700';
    if (z && z.indexOf('400-900') === 0) return 'bg-blue-100 text-blue-700';
    return 'bg-gray-100 text-gray-600';
  };

  function renderTeam(team) {
    const box = $('teamList');
    if (!team || !team.length) {
      box.innerHTML = '<div class="px-6 py-8 text-center text-sm text-slate-400">No active surveyors</div>';
      return;
    }
    box.innerHTML = team.map(t => {
      const dot = t.online ? 'bg-green-500' : (t.recent ? 'bg-amber-400' : 'bg-gray-300');
      const batt = (t.battery === null || t.battery === undefined) ? '' :
        `<span class="text-xs ${t.battery < 20 ? 'text-red-500' : 'text-slate-400'}">🔋 ${t.battery}%</span>`;
      return `<div class="px-6 py-3 flex items-center gap-3">
        <span class="relative flex h-2.5 w-2.5">
          ${t.online ? '<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>' : ''}
          <span class="relative inline-flex rounded-full h-2.5 w-2.5 ${dot}"></span>
        </span>
        <div class="flex-1 min-w-0">
          <div class="font-medium text-slate-700 text-sm truncate">${esc(t.name)}</div>
          <div class="text-xs text-slate-400">${esc(t.last_seen)}</div>
        </div>
        ${batt}
        <div class="text-right">
          <div class="text-lg font-bold text-blue-600 leading-none">${nf(t.today)}</div>
          <div class="text-[10px] text-slate-400 uppercase tracking-wide">today</div>
        </div>
      </div>`;
    }).join('');
  }

  function renderRecent(recent) {
    const body = $('recentBody');
    if (!body || !recent) return;
    if (!recent.length) {
      body.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-slate-400">No surveys yet</td></tr>';
      return;
    }
    body.innerHTML = recent.map(r => `<tr class="hover:bg-gray-50 transition-colors">
      <td class="px-6 py-3 text-slate-500 text-xs">${esc(r.ago)}</td>
      <td class="px-6 py-3 font-mono text-xs text-slate-700">${esc(r.parcel_no)}</td>
      <td class="px-6 py-3"><span class="inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${zoneBadge(r.zone)}">${esc(r.zone)}</span></td>
      <td class="px-6 py-3 text-slate-600">${esc(r.ward_no)}</td>
      <td class="px-6 py-3 text-slate-700">${esc(r.owner)}</td>
      <td class="px-6 py-3 text-slate-500">${esc(r.by)}</td>
    </tr>`).join('');
  }

  async function refresh() {
    try {
      const res = await fetch('dashboard_stats_ajax.php', { cache: 'no-store' });
      if (!res.ok) throw new Error('http ' + res.status);
      const d = await res.json();

      $('statPct').textContent          = d.pct + '%';
      $('statBar').style.width          = d.pct + '%';
      $('statDone').textContent         = nf(d.done_parcels);
      $('statRemaining').textContent    = nf(d.remaining);
      $('statSurveyed').textContent     = nf(d.done_parcels);
      $('statPctComplete').textContent  = d.pct;
      $('statTotalSurveys').textContent = nf(d.total_surveys);
      $('statTodaySurveys').textContent = nf(d.today_surveys);
      $('statActiveNow').textContent    = d.active_now;
      $('statPendingSync').textContent  = nf(d.pending_sync);

      renderTeam(d.team);
      renderRecent(d.recent);

      $('lastUpdated').textContent = 'updated ' + new Date().toLocaleTimeString();
      $('liveDot').classList.remove('text-red-500');
      $('liveDot').classList.add('text-green-600');
    } catch (e) {
      $('lastUpdated').textContent = 'reconnecting…';
      $('liveDot').classList.remove('text-green-600');
      $('liveDot').classList.add('text-red-500');
    }
  }

  refresh();
  setInterval(refresh, 12000);   // poll every 12s
  document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
})();
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
