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

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: surveys.php'); exit; }

$stmt = $pdo->prepare('
    SELECT s.*, 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 s.id = ?
');
$stmt->execute([$id]);
$r = $stmt->fetch();
if (!$r) { echo '<p class="text-red-600">Survey not found.</p>'; require_once 'includes/footer.php'; exit; }

$os = $pdo->prepare('SELECT * FROM land_owners WHERE survey_id = ? ORDER BY sequence_order');
$os->execute([$id]); $owners = $os->fetchAll();

$ss = $pdo->prepare('SELECT * FROM survey_structures WHERE survey_id = ? ORDER BY sequence_order');
$ss->execute([$id]); $structures = $ss->fetchAll();


function photo(string $name): string {
    if (!$name) return '<span class="text-slate-400 text-xs">No photo</span>';
    return '<a href="' . htmlspecialchars(UPLOAD_URL . $name) . '" target="_blank" class="block">
              <img src="' . htmlspecialchars(UPLOAD_URL . $name) . '"
                   class="h-20 w-28 object-cover rounded-xl border border-gray-100 hover:opacity-80 transition-opacity">
            </a>';
}

$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',
];
$condColor = ['good'=>'bg-green-100 text-green-700','average'=>'bg-amber-100 text-amber-700','dilapidated'=>'bg-red-100 text-red-700'];
?>

<!-- Back + title -->
<div class="flex items-center gap-4 mb-6">
  <a href="surveys.php" class="text-slate-400 hover:text-slate-700 transition-colors">
    <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="M10 19l-7-7m0 0l7-7m-7 7h18"/>
    </svg>
  </a>
  <div>
    <h2 class="text-xl font-bold text-slate-800">Survey #<?= $r['id'] ?></h2>
    <p class="text-sm text-slate-500">
      <?= htmlspecialchars($r['survey_date']) ?> ·
      Ward <?= htmlspecialchars($r['ward_no']) ?> ·
      <?= htmlspecialchars($r['tole']) ?>
    </p>
  </div>
  <span class="ml-auto inline-flex px-3 py-1 rounded-full text-xs font-semibold <?= $zoneColor[$r['zone']] ?? 'bg-gray-100 text-gray-700' ?>">
    Zone <?= htmlspecialchars($r['zone']) ?>
  </span>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">

  <!-- Parcel info -->
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
    <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-4">📍 Parcel Info</h3>
    <dl class="space-y-2 text-sm">
      <div class="flex justify-between"><dt class="text-slate-500">Parcel No</dt><dd class="font-mono font-semibold text-slate-700"><?= htmlspecialchars($r['parcel_no']) ?></dd></div>
      <div class="flex justify-between"><dt class="text-slate-500">Sheet</dt><dd class="text-slate-700"><?= htmlspecialchars($r['sheet_number']) ?></dd></div>
      <div class="flex justify-between"><dt class="text-slate-500">Land Type</dt><dd class="text-slate-700 capitalize"><?= htmlspecialchars($r['land_type']) ?></dd></div>
      <div class="flex justify-between"><dt class="text-slate-500">Ownership</dt><dd class="text-slate-700 capitalize"><?= htmlspecialchars($r['ownership_type']) ?></dd></div>
      <div class="flex justify-between"><dt class="text-slate-500">Surveyor</dt><dd class="text-slate-700"><?= htmlspecialchars($r['surveyor_name']) ?></dd></div>
    </dl>
  </div>

  <!-- Land owners -->
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 lg:col-span-2">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wide">👤 Land Owners</h3>
      <span class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full font-medium">
        <?= count($owners) ?: 1 ?> owner<?= count($owners) > 1 ? 's' : '' ?>
      </span>
    </div>

    <?php if (!empty($owners)): ?>
      <div class="space-y-4">
      <?php foreach ($owners as $i => $o): ?>
        <div class="<?= $i > 0 ? 'border-t border-gray-100 pt-4' : '' ?>">
          <div class="flex items-center gap-2 mb-3">
            <span class="text-sm font-semibold text-slate-700">Owner #<?= $i + 1 ?></span>
            <?php if ($o['is_primary']): ?>
              <span class="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">Primary / Lalpurja</span>
            <?php endif ?>
            <span class="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full"><?= $o['ownership_share_pct'] ?>% share</span>
          </div>
          <div class="grid grid-cols-2 gap-x-6 gap-y-1 text-sm mb-3">
            <div><span class="text-slate-500">Name</span><div class="font-semibold text-slate-700"><?= htmlspecialchars($o['owner_name']) ?></div></div>
            <div><span class="text-slate-500">Citizenship</span><div class="text-slate-700"><?= htmlspecialchars($o['citizenship_no']) ?></div></div>
          </div>
          <div class="flex gap-4">
            <div class="text-center"><?= photo($o['owner_photo']) ?><div class="text-xs text-slate-400 mt-1">Owner</div></div>
            <div class="text-center"><?= photo($o['citizenship_photo']) ?><div class="text-xs text-slate-400 mt-1">Citizenship</div></div>
            <?php if ($o['land_photo']): ?>
            <div class="text-center"><?= photo($o['land_photo']) ?><div class="text-xs text-slate-400 mt-1">Land</div></div>
            <?php endif ?>
          </div>
        </div>
      <?php endforeach ?>
      </div>
    <?php else: ?>
      <!-- Legacy fallback -->
      <div class="grid grid-cols-2 gap-x-6 gap-y-1 text-sm mb-3">
        <div><span class="text-slate-500">Name</span><div class="font-semibold text-slate-700"><?= htmlspecialchars($r['owner_name']) ?></div></div>
        <div><span class="text-slate-500">Citizenship</span><div class="text-slate-700"><?= htmlspecialchars($r['citizenship_no']) ?></div></div>
      </div>
      <div class="flex gap-4">
        <div class="text-center"><?= photo($r['owner_photo']) ?><div class="text-xs text-slate-400 mt-1">Owner</div></div>
        <div class="text-center"><?= photo($r['citizenship_photo']) ?><div class="text-xs text-slate-400 mt-1">Citizenship</div></div>
        <div class="text-center"><?= photo($r['land_photo']) ?><div class="text-xs text-slate-400 mt-1">Land</div></div>
      </div>
    <?php endif ?>
  </div>
</div>

<!-- Structures -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
  <div class="flex items-center justify-between mb-4">
    <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wide">🏠 Structures</h3>
    <span class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full font-medium">
      <?= count($structures) ?: 1 ?> structure<?= count($structures) > 1 ? 's' : '' ?>
    </span>
  </div>
  <?php $displayStructures = !empty($structures) ? $structures : [null]; ?>
  <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
  <?php foreach ($displayStructures as $i => $s):
    $isLegacy = ($s === null);
    if ($isLegacy) $s = [
        'structure_type'=>$r['structure_type'], 'structure_type_other'=>$r['structure_type_other'],
        'construction_material'=>$r['construction_material'], 'num_floors'=>$r['num_floors'],
        'floor_length_m'=>$r['floor_length_m'], 'floor_breadth_m'=>$r['floor_breadth_m'],
        'year_built'=>$r['year_built'], 'structure_condition'=>$r['structure_condition'],
        'is_occupied'=>$r['is_occupied'], 'is_rented'=>$r['is_rented'],
        'monthly_rent'=>$r['monthly_rent'], 'num_rooms'=>$r['num_rooms'],
        'structure_photo'=>$r['structure_photo'], 'owner_type'=>'land_owner',
        'structure_owner_name'=>'', 'structure_owner_citizenship'=>'',
        'structure_photo_2'=>'', 'structure_photo_3'=>'', 'structure_photo_4'=>''
    ];
    $cc = $condColor[$s['structure_condition']] ?? 'bg-gray-100 text-gray-600';
  ?>
  <div class="border border-gray-100 rounded-xl p-4">
    <div class="flex items-center gap-2 mb-3">
      <span class="font-semibold text-slate-700 text-sm">Structure #<?= $i + 1 ?></span>
      <span class="text-xs px-2 py-0.5 rounded-full capitalize <?= $cc ?>"><?= htmlspecialchars($s['structure_condition']) ?></span>
      <span class="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full capitalize"><?= htmlspecialchars($s['structure_type']) ?></span>
    </div>
    <dl class="grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm mb-3">
      <div><dt class="text-slate-400 text-xs">Material</dt><dd class="text-slate-700"><?= htmlspecialchars($s['construction_material']) ?></dd></div>
      <div><dt class="text-slate-400 text-xs">Floors / Rooms</dt><dd class="text-slate-700"><?= $s['num_floors'] ?> / <?= $s['num_rooms'] ?></dd></div>
      <div><dt class="text-slate-400 text-xs">Size</dt><dd class="text-slate-700"><?= $s['floor_length_m'] ?>m × <?= $s['floor_breadth_m'] ?>m</dd></div>
      <div><dt class="text-slate-400 text-xs">Year Built</dt><dd class="text-slate-700"><?= $s['year_built'] ?: '—' ?></dd></div>
      <div><dt class="text-slate-400 text-xs">Occupied</dt><dd><?= $s['is_occupied'] ? '<span class="text-green-600">✅ Yes</span>' : '<span class="text-slate-400">No</span>' ?></dd></div>
      <div><dt class="text-slate-400 text-xs">Rented</dt><dd><?= $s['is_rented'] ? '<span class="text-amber-600">Yes — NPR '.number_format($s['monthly_rent']).'</span>' : '<span class="text-slate-400">No</span>' ?></dd></div>
      <?php if ($s['owner_type'] === 'different'): ?>
      <div class="col-span-2"><dt class="text-slate-400 text-xs">Structure Owner</dt><dd class="text-slate-700 font-medium"><?= htmlspecialchars($s['structure_owner_name']) ?> (<?= htmlspecialchars($s['structure_owner_citizenship']) ?>)</dd></div>
      <?php endif ?>
    </dl>
    <div class="grid grid-cols-2 gap-2">
      <?= photo($s['structure_photo'] ?? '') ?>
      <?= photo($s['structure_photo_2'] ?? '') ?>
      <?= photo($s['structure_photo_3'] ?? '') ?>
      <?= photo($s['structure_photo_4'] ?? '') ?>
    </div>
  </div>
  <?php endforeach ?>
  </div>
</div>


<?php if ($r['remarks']): ?>
<div class="bg-amber-50 border border-amber-200 rounded-2xl p-5">
  <h3 class="text-xs font-semibold text-amber-700 uppercase tracking-wide mb-2">📝 Remarks</h3>
  <p class="text-sm text-amber-800"><?= nl2br(htmlspecialchars($r['remarks'])) ?></p>
</div>
<?php endif ?>

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