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

$flash = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $id = (int)($_POST['id'] ?? 0);
    if ($_POST['action'] === 'edit' && $id) {
        $owner = preg_replace('/[^A-Za-z .\'\-]/', '', (string)($_POST['owner_name'] ?? ''));
        $owner = trim(preg_replace('/\s+/', ' ', $owner));
        $ward  = trim(preg_replace('/[^0-9]/', '', (string)($_POST['ward_no'] ?? '')));
        $tole  = trim(preg_replace('/[^\x20-\x7E]/', '', (string)($_POST['tole'] ?? '')));
        try {
            $pdo->prepare('UPDATE surveys SET owner_name=?, ward_no=?, tole=? WHERE id=?')
                ->execute([$owner, $ward, $tole, $id]);
            $flash = 'updated';
        } catch (Exception $e) { $flash = 'error:' . $e->getMessage(); }
    } elseif ($_POST['action'] === 'delete' && $id) {
        try {
            // Find parcel for status reset
            $pq = $pdo->prepare('SELECT parcel_id FROM surveys WHERE id = ?');
            $pq->execute([$id]);
            $parcelId = (int)($pq->fetchColumn() ?: 0);
            // Remove child rows then the survey
            $pdo->prepare('DELETE FROM land_owners       WHERE survey_id = ?')->execute([$id]);
            $pdo->prepare('DELETE FROM survey_structures  WHERE survey_id = ?')->execute([$id]);
            try { $pdo->prepare('DELETE FROM survey_households WHERE survey_id = ?')->execute([$id]); } catch (Exception $e) {}
            $pdo->prepare('DELETE FROM surveys WHERE id = ?')->execute([$id]);
            // Reset parcel to pending only if no other survey remains for it
            if ($parcelId) {
                $c = $pdo->prepare('SELECT COUNT(*) FROM surveys WHERE parcel_id = ?');
                $c->execute([$parcelId]);
                if ((int)$c->fetchColumn() === 0) {
                    $pdo->prepare('UPDATE parcels SET survey_status = "pending" WHERE id = ?')->execute([$parcelId]);
                }
            }
            $flash = 'deleted';
        } catch (Exception $e) { $flash = 'error:' . $e->getMessage(); }
    }
}

$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 25;
$offset = ($page - 1) * $limit;

$where  = ['1=1'];
$params = [];

if (!empty($_GET['zone']))       { $where[] = 'p.zone = ?';            $params[] = $_GET['zone']; }
if (!empty($_GET['ward']))       { $where[] = 's.ward_no = ?';         $params[] = $_GET['ward']; }
if (!empty($_GET['surveyor_id'])){ $where[] = 's.surveyor_id = ?';     $params[] = (int)$_GET['surveyor_id']; }
if (!empty($_GET['owner']))      { $where[] = 's.owner_name LIKE ?';   $params[] = '%' . $_GET['owner'] . '%'; }
if (!empty($_GET['date_from']))  { $where[] = 's.survey_date >= ?';    $params[] = $_GET['date_from']; }
if (!empty($_GET['date_to']))    { $where[] = 's.survey_date <= ?';    $params[] = $_GET['date_to']; }

$w = implode(' AND ', $where);

$stmt = $pdo->prepare("
    SELECT s.id, s.survey_date, s.owner_name, s.ward_no, s.tole, s.land_type, s.created_at,
           p.parcel_no, p.zone, p.sheet_number,
           sv.name AS surveyor_name
    FROM surveys s
    LEFT JOIN parcels p    ON p.id = s.parcel_id
    LEFT JOIN surveyors sv ON sv.id = s.surveyor_id
    WHERE $w ORDER BY s.created_at DESC LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$cStmt = $pdo->prepare("SELECT COUNT(*) FROM surveys s LEFT JOIN parcels p ON p.id = s.parcel_id WHERE $w");
$cStmt->execute($params);
$total = (int)$cStmt->fetchColumn();
$pages = max(1, (int)ceil($total / $limit));

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

$surveyorList = $pdo->query("SELECT id, name FROM surveyors WHERE is_active=1 ORDER BY name")->fetchAll();

// Build query string helper
function qs(array $override = []): string {
    $params = array_merge($_GET, $override);
    unset($params['page']);
    return http_build_query(array_filter($params, fn($v) => $v !== ''));
}
?>

<div class="flex items-center justify-between mb-6">
  <div>
    <h2 class="text-xl font-bold text-slate-800">Surveys
      <span class="ml-2 text-sm font-normal text-slate-500"><?= number_format($total) ?> total</span>
    </h2>
  </div>
  <a href="export.php" class="inline-flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700
     text-white text-sm font-medium rounded-xl transition-colors shadow-sm">
    ⬇ Export CSV
  </a>
</div>

<?php if ($flash === 'updated'): ?>
<div class="mb-4 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">✅ Survey updated.</div>
<?php elseif ($flash === 'deleted'): ?>
<div class="mb-4 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">✅ Survey deleted.</div>
<?php elseif (str_starts_with($flash, 'error:')): ?>
<div class="mb-4 px-4 py-3 bg-red-50 border border-red-200 rounded-xl text-red-700 text-sm">⚠️ <?= htmlspecialchars(substr($flash,6)) ?></div>
<?php endif ?>

<!-- Filters -->
<form method="get" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-5">
  <div class="flex flex-wrap gap-3 items-end">
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">Zone</label>
      <select name="zone" class="px-3 py-2 border border-gray-200 rounded-xl text-sm text-slate-700
                                 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
        <option value="">All Zones</option>
        <option value="0-300m"   <?= ($_GET['zone']??'')==='0-300m'   ? 'selected':'' ?>>0–300m</option>
        <option value="300-400m" <?= ($_GET['zone']??'')==='300-400m' ? 'selected':'' ?>>300–400m</option>
        <option value="400-900m" <?= ($_GET['zone']??'')==='400-900m' ? 'selected':'' ?>>400–900m</option>
      </select>
    </div>
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">Ward</label>
      <input type="text" name="ward" placeholder="Ward No"
             value="<?= htmlspecialchars($_GET['ward']??'') ?>"
             class="px-3 py-2 border border-gray-200 rounded-xl text-sm w-20 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
    </div>
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">Surveyor</label>
      <select name="surveyor_id" class="px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
        <option value="">All</option>
        <?php foreach ($surveyorList as $sv): ?>
          <option value="<?= $sv['id'] ?>" <?= (($_GET['surveyor_id']??'')==$sv['id'])?'selected':'' ?>>
            <?= htmlspecialchars($sv['name']) ?>
          </option>
        <?php endforeach ?>
      </select>
    </div>
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">Owner Name</label>
      <input type="text" name="owner" placeholder="Search owner"
             value="<?= htmlspecialchars($_GET['owner']??'') ?>"
             class="px-3 py-2 border border-gray-200 rounded-xl text-sm w-36 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
    </div>
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">From</label>
      <input type="date" name="date_from" value="<?= htmlspecialchars($_GET['date_from']??'') ?>"
             class="px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
    </div>
    <div>
      <label class="block text-xs font-medium text-slate-500 mb-1">To</label>
      <input type="date" name="date_to" value="<?= htmlspecialchars($_GET['date_to']??'') ?>"
             class="px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
    </div>
    <button type="submit"
            class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition-colors">
      Filter
    </button>
    <a href="surveys.php"
       class="px-4 py-2 border border-gray-200 text-slate-600 hover:bg-gray-50 text-sm rounded-xl transition-colors">
      Reset
    </a>
  </div>
</form>

<!-- Table -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
  <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 border-b border-gray-100">
          <th class="px-5 py-3 text-left font-medium">#</th>
          <th class="px-5 py-3 text-left font-medium">Date</th>
          <th class="px-5 py-3 text-left font-medium">Zone</th>
          <th class="px-5 py-3 text-left font-medium">Sheet</th>
          <th class="px-5 py-3 text-left font-medium">Parcel No</th>
          <th class="px-5 py-3 text-left font-medium">Ward</th>
          <th class="px-5 py-3 text-left font-medium">Owner</th>
          <th class="px-5 py-3 text-left font-medium">Surveyor</th>
          <th class="px-5 py-3 text-left font-medium"></th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php if (!$rows): ?>
          <tr><td colspan="9" class="px-5 py-12 text-center text-slate-400">No surveys found</td></tr>
        <?php endif ?>
        <?php foreach ($rows as $r): ?>
        <tr class="hover:bg-gray-50 transition-colors">
          <td class="px-5 py-3 text-slate-400 text-xs"><?= $r['id'] ?></td>
          <td class="px-5 py-3 text-slate-600"><?= htmlspecialchars($r['survey_date']) ?></td>
          <td class="px-5 py-3">
            <span class="inline-flex px-2 py-0.5 rounded-full text-xs font-medium <?= $zoneColor[$r['zone']] ?? 'bg-gray-100 text-gray-600' ?>">
              <?= htmlspecialchars($r['zone']) ?>
            </span>
          </td>
          <td class="px-5 py-3 text-slate-500 text-xs"><?= htmlspecialchars($r['sheet_number']) ?></td>
          <td class="px-5 py-3 font-mono text-xs text-slate-700"><?= htmlspecialchars($r['parcel_no']) ?></td>
          <td class="px-5 py-3 text-slate-600"><?= htmlspecialchars($r['ward_no']) ?></td>
          <td class="px-5 py-3 text-slate-700 font-medium"><?= htmlspecialchars($r['owner_name']) ?></td>
          <td class="px-5 py-3 text-slate-500"><?= htmlspecialchars($r['surveyor_name']) ?></td>
          <td class="px-5 py-3">
            <div class="flex items-center gap-2">
              <a href="survey_detail.php?id=<?= $r['id'] ?>"
                 class="text-blue-600 hover:text-blue-800 text-xs font-medium">View</a>
              <button type="button"
                @click='$dispatch("edit-survey", <?= htmlspecialchars(json_encode([
                    "id"=>$r["id"],"owner_name"=>$r["owner_name"],
                    "ward_no"=>$r["ward_no"],"tole"=>$r["tole"]
                ]), ENT_QUOTES) ?>)'
                class="text-xs px-2.5 py-1 border border-blue-200 text-blue-600 hover:bg-blue-50 rounded-lg">Edit</button>
              <form method="post" class="inline"
                    onsubmit="return confirm('Delete survey #<?= $r['id'] ?> (<?= htmlspecialchars(addslashes($r['owner_name']), ENT_QUOTES) ?>)? This removes its owners, structures & photos records. Parcel resets to pending.');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <button class="text-xs px-2.5 py-1 border border-red-200 text-red-600 hover:bg-red-50 rounded-lg">Delete</button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($pages > 1): ?>
  <div class="px-5 py-4 border-t border-gray-100 flex items-center justify-between">
    <span class="text-xs text-slate-500">
      Page <?= $page ?> of <?= $pages ?> · <?= number_format($total) ?> surveys
    </span>
    <div class="flex gap-1">
      <?php if ($page > 1): ?>
        <a href="?page=<?= $page-1 ?>&<?= qs() ?>"
           class="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-slate-600">← Prev</a>
      <?php endif ?>
      <?php for ($i = max(1,$page-2); $i <= min($pages,$page+2); $i++): ?>
        <a href="?page=<?= $i ?>&<?= qs() ?>"
           class="px-3 py-1.5 text-xs border rounded-lg <?= $i===$page ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-200 hover:bg-gray-50 text-slate-600' ?>">
          <?= $i ?>
        </a>
      <?php endfor ?>
      <?php if ($page < $pages): ?>
        <a href="?page=<?= $page+1 ?>&<?= qs() ?>"
           class="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-slate-600">Next →</a>
      <?php endif ?>
    </div>
  </div>
  <?php endif ?>
</div>

<!-- Edit Survey Modal (basic fields) -->
<div x-data="{ open:false, f:{ id:'', owner_name:'', ward_no:'', tole:'' } }"
     @edit-survey.window="f = $event.detail; open = true"
     x-show="open" x-cloak
     class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
  <div @click.outside="open=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
    <div class="flex items-center justify-between mb-5">
      <h3 class="text-lg font-bold text-slate-800">Edit Survey</h3>
      <button @click="open=false" class="text-slate-400 hover:text-slate-700">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>
    <p class="text-xs text-slate-400 mb-4">Quick-fix basic fields. For full edits use the mobile app draft.</p>
    <form method="post" class="space-y-4">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" :value="f.id">
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">Owner Name</label>
        <input type="text" name="owner_name" x-model="f.owner_name"
               class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Ward No</label>
          <input type="text" name="ward_no" x-model="f.ward_no" inputmode="numeric"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Tole</label>
          <input type="text" name="tole" x-model="f.tole"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>
      <div class="flex gap-3 pt-2">
        <button type="button" @click="open=false"
                class="flex-1 px-4 py-2.5 border border-gray-200 text-slate-600 hover:bg-gray-50 text-sm font-medium rounded-xl">Cancel</button>
        <button type="submit"
                class="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl">Save</button>
      </div>
    </form>
  </div>
</div>

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