<?php
/************************************************************
 * view.php — Property details with map + Survey (Canvas)
 * Adds: INNER JOIN file (t2) and Archived Files (documents)
 * Expects: ?propertyId=PRP...  (or ?property=PRP...)
 ************************************************************/

// --- DB CONNECT (PDO) ---
require_once __DIR__ . '/../../includes/connect.php'; // MUST define $pdo (PDO)
require_once "../../includes/connect.php";
require_once "../../includes/functions.php";
require_once "../../vendors/coordinates.php";



// ---------- helpers (assumed in your codebase) ----------
// utm2ll($easting,$northing,$zone,true)
// midPoint($eastings,$northings) -> object {x, y}
// getTownPlanZone($lgacode)
// getFileNumber($fileid)

// ---------- input ----------
$zone = 32; // NAT Zero UTM Zone 32N
$propertyParam = $_GET['propertyId'] ?? ($_GET['property'] ?? '') ?? '';
if (!$propertyParam) {
  http_response_code(400);
  exit("Missing propertyId");
}

// ---------- property + file (JOIN) ----------
$st = $pdo->prepare("
  SELECT 
      t1.fileid,
      t1.plotnumber,
      t1.propertydesc,
      t1.lgacode,
      t1.propertyid,
      t1.propertynumber,
      t1.layoutid,
      t2.filenumber AS file_number
  FROM property AS t1
  INNER JOIN file AS t2 ON t2.fileid = t1.fileid
  WHERE t1.propertynumber = :pn
  LIMIT 1
");
$st->execute([':pn' => $propertyParam]);
$prop = $st->fetch();
if (!$prop) {
  http_response_code(404);
  exit("Property not found.");
}
extract($prop); // + file_number

// ---------- survey ----------
$st = $pdo->prepare("SELECT *, Dummy4 FROM survey_details WHERE propertyid = :pid LIMIT 1");
$st->execute([':pid' => $propertyid]);
$sv = $st->fetch();

$survey = false;
$beacon_rows = [];
$labels = [];
$eastings = [];
$northings = [];
$latLngs = [];
$midpointLatLng = null;

// defaults from survey
$SurveyNo = $TracingNo = $Benchmark = $Surveyor = $Surveyor_Title = $Survey_Date = $Dummy6 = $Dummy7 = '';
$Area = 0;

if ($sv) {
  $survey = true;
  extract($sv, EXTR_OVERWRITE);

  $bcnTokens = array_values(array_filter(array_map('trim', explode("#", (string)$BeaconNo))));
  foreach ($bcnTokens as $token) {
    $beaconId = ltrim($token, "*");
    $beaconId=substr($beaconId,1);
    if ($beaconId === '') continue;
   
    $cst = $pdo->prepare("SELECT northing, easting FROM coordinates WHERE beaconno = :b LIMIT 1");
    $cst->execute([':b' => $beaconId]);
    if ($c = $cst->fetch()) {
      $northings[] = (float)$c['northing'];
      $eastings[]  = (float)$c['easting'];
      $labels[]    = $beaconId;

      // To Lat/Lng for map
      $conv = json_decode(utm2ll((float)$c['easting'], (float)$c['northing'], $zone, true), false);
      if ($conv && isset($conv->attr)) {
        [$lat, $lng] = array_map('floatval', array_values((array) $conv->attr));
        $latLngs[] = ['lat' => $lat, 'lng' => $lng];
      }

      $beacon_rows[] = [
        'beacon'   => $beaconId,
        'northing' => (float)$c['northing'],
        'easting'  => (float)$c['easting'],
      ];
    }
  }

  // midpoint (UTM -> lat/lng)
  if (count($eastings) >= 1) {
    $mid = midPoint($eastings, $northings); // -> {x,y}
    $md  = json_decode(utm2ll($mid->x, $mid->y, $zone, true), false);
    if ($md && isset($md->attr)) {
      [$mlat, $mlng] = array_map('floatval', array_values((array)$md->attr));
      $midpointLatLng = ['lat' => $mlat, 'lng' => $mlng];
    }
  }
}

// ---------- documents (Archived Files) ----------
$documents = [];
if (!empty($file_number)) {
  $dst = $pdo->prepare("
    SELECT filename, filepath, title, doc_type, filesize
    FROM documents
    WHERE title = :title
    ORDER BY filename ASC
  ");
  $dst->execute([':title' => $file_number]);
  $documents = $dst->fetchAll() ?: [];
}

// ---------- derived ----------
$filenameLegacy = function_exists('getFileNumber') ? str_replace("/", ".", getFileNumber($fileid)) : ('FILE-' . $fileid);
$pdf = "files/data/{$filenameLegacy}.pdf";

$AreaNum  = is_numeric($Area ?? 0) ? (float)$Area : 0.0;
$raw_rent = 100 * $AreaNum;
$rent     = number_format($raw_rent, 0);

$pageName      = "Property Details";
$townPlanZone  = function_exists('getTownPlanZone') ? strtoupper(getTownPlanZone($lgacode)) : '';
$propertyTitle = htmlspecialchars($propertynumber ?: $propertyParam, ENT_QUOTES);

$descSafe = htmlspecialchars($propertydesc ?? '', ENT_QUOTES);
$plotSafe = htmlspecialchars($plotnumber ?? 'NA', ENT_QUOTES);
$lgaSafe  = htmlspecialchars($lgacode ?? '', ENT_QUOTES);

// JSON for JS
$latLngsJson   = json_encode($latLngs, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$midJson       = json_encode($midpointLatLng, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$labelsJson    = json_encode($labels, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$eastingsJson  = json_encode($eastings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$northingsJson = json_encode($northings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

// survey footer meta
$surveyMeta = [
  'plan'     => $SurveyNo ?: 'NA',
  'tracing'  => $TracingNo ?: 'NA',
  'origin'   => 'UTM ZONE 32(N)',
  'area'     => number_format($AreaNum, 2) . ' sq. m',
  'signedBy' => trim(($Surveyor ?? '') . ' ( ' . ($Surveyor_Title ?? '') . ' )'),
  'approved' => trim(($Dummy6 ?? '') . ' ' . ($Dummy7 ?? '')),
  'date'     => $Survey_Date ?: '0000-00-00',
  'title1'   => strtoupper($townPlanZone ?: 'ABAKALIKI'),
  'title2'   => $propertydesc ?: '',
];
$surveyMetaJson = json_encode($surveyMeta, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= $pageName ?>: <?= $propertyTitle ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap & Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    body { background: #fbfbfd; }
    .map-wrap { border-radius: 12px; overflow: hidden; }
    .stat-card { border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,.06); }
    .pill { background: #f7f7fa; border-radius: 8px; padding: .5rem .75rem; }
    .btn-amber { background:#c96e2b; color:#fff; border: none; }
    .btn-amber:hover { background:#b86022; color:#fff; }
    .section-title { font-weight: 700; margin: 1.5rem 0 .75rem; }
    .details-title { font-weight:800; font-size:1.75rem; }
    .property-id { color:#d5802f; }
    .tabs .nav-link { border-radius: 6px; }
    .tabs .nav-link.active { background:#eaf2ff; color:#0d6efd; }
    .table-props tr th { width: 260px; color:#6b7280; font-weight:600; }
    .table-props tr td { color:#111827; }
    .map-search { background:#fff; border:1px solid #d1d5db; border-radius:8px; padding:.5rem; }
    canvas#surveyCanvas { width:100%; max-width:900px; height:auto; border:1px solid #e5e7eb; border-radius:12px; background:#fff; }
    .table-narrow td, .table-narrow th { padding: .45rem .6rem; }
    /* Modal */
    .modal-content { border-radius:1rem; overflow:hidden; }
    #docViewerLoading { position:absolute; inset:0; z-index:10; background:rgba(0,0,0,.35); display:none; }
  </style>
</head>
<body>

<div class="container py-3">

  <!-- Search -->
  <div class="row mb-2">
    <div class="col-12">
      <form class="d-flex gap-2 map-search" action="view.php" method="get">
        <div class="input-group">
          <span class="input-group-text">Search</span>
          <input type="text" class="form-control" name="propertyId" placeholder="Input Property Number or File Number" value="<?= htmlspecialchars($propertyParam, ENT_QUOTES) ?>">
        </div>
        <button class="btn btn-outline-primary">Search Property</button>
      </form>
    </div>
  </div>

  <!-- Map -->
  <div class="row">
    <div class="col-12">
      <div class="map-wrap"><div id="map" style="height:420px;"></div></div>
    </div>
  </div>

  <!-- Header -->
  <div class="row mt-4">
    <div class="col-12 text-center">
      <div class="details-title">Property Details: <span class="property-id"><?= $propertyTitle ?></span></div>
      <?php if (!empty($file_number)): ?>
        <div class="text-muted">File Number: <strong><?= htmlspecialchars($file_number, ENT_QUOTES) ?></strong></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Stats -->
  <div class="row g-3 mt-2">
    <div class="col-md-4">
      <div class="bg-white p-3 stat-card h-100">
        <div class="fw-semibold text-center text-muted">Property Description</div>
        <div class="text-center mt-2"><?= nl2br($descSafe) ?></div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="bg-white p-3 stat-card h-100 text-center">
        <div class="display-6 fw-bold"><?= number_format($AreaNum, 2) ?></div>
        <div class="text-muted">Area (sq.meters)</div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="bg-white p-3 stat-card h-100 text-center">
        <div class="display-6 fw-bold">₦<?= $rent ?></div>
        <div class="text-muted">Outstanding Ground Rent</div>
      </div>
    </div>
  </div>

  <!-- Actions -->
  <div class="row mt-3">
    <div class="col-12 d-flex flex-wrap gap-2 justify-content-center">
      <a class="btn btn-amber" href="request_status.php?propertyId=<?= urlencode($propertynumber) ?>">Request Property Status</a>
      <a class="btn btn-amber" href="pay_ground_rent.php?propertyId=<?= urlencode($propertynumber) ?>&amount=<?= urlencode($raw_rent) ?>">Pay Ground Rent (<?= number_format($raw_rent) ?>)</a>
      <a class="btn btn-amber" href="place_caveat.php?propertyId=<?= urlencode($propertynumber) ?>">Place Caveat</a>
    </div>
  </div>

  <!-- Tabs -->
  <div class="row mt-4">
    <div class="col-12 tabs">
      <ul class="nav nav-pills mb-3" role="tablist">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#pane-desc" type="button">Property Description</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#pane-survey" type="button">Survey</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#pane-pay" type="button">Payment History</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#pane-arch" type="button">Archived Files</button></li>
      </ul>

      <div class="tab-content">
        <!-- Description -->
        <div class="tab-pane fade show active" id="pane-desc">
          <h5 class="section-title">Land Identification Information</h5>
          <div class="bg-white p-3 rounded-3">
            <div class="table-responsive">
              <table class="table table-borderless table-props mb-0">
                <tbody>
                  <tr><th>Plot Number</th><td><?= $plotSafe ?: 'NA' ?></td></tr>
                  <tr><th>Property Description</th><td><?= nl2br($descSafe) ?></td></tr>
                  <tr><th>Layout</th><td><?= htmlspecialchars($layoutid ?? 'NA', ENT_QUOTES) ?></td></tr>
                  <tr><th>LGA</th><td><?= $lgaSafe ?></td></tr>
                  <?php if ($townPlanZone): ?>
                    <tr><th>Town Planning Zone</th><td><?= htmlspecialchars($townPlanZone, ENT_QUOTES) ?></td></tr>
                  <?php endif; ?>
                  <?php if (is_file($pdf)): ?>
                    <tr><th>Survey Plan (PDF)</th><td><a class="btn btn-sm btn-outline-primary" href="<?= htmlspecialchars($pdf, ENT_QUOTES) ?>" target="_blank"><i class="bi bi-file-earmark-pdf"></i> Open Plan</a></td></tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Survey -->
        <div class="tab-pane fade" id="pane-survey">
          <h5 class="section-title">Land Survey Information</h5>
          <div class="bg-white p-3 rounded-3 mb-3">
            <div class="table-responsive">
              <table class="table table-borderless table-narrow mb-0">
                <tbody>
                  <tr><th style="width:260px;">Survey Plan Number</th><td><?= htmlspecialchars($SurveyNo ?: 'NA', ENT_QUOTES) ?></td></tr>
                  <tr><th>Tracing Number</th><td><?= htmlspecialchars($TracingNo ?: 'NA', ENT_QUOTES) ?></td></tr>
                  <tr><th>Origin</th><td>UTM ZONE 32(N)</td></tr>
                  <tr><th>Area</th><td><?= number_format($AreaNum, 2) ?> sq. meters</td></tr>
                </tbody>
              </table>
            </div>
          </div>

          <h5 class="section-title">Land Beacon Numbers</h5>
          <div class="bg-white p-3 rounded-3 mb-3">
            <div class="table-responsive">
              <table class="table table-striped table-narrow mb-0">
                <thead>
                  <tr><th>S/N</th><th>Beacon</th><th>Northing</th><th>Easting</th></tr>
                </thead>
                <tbody>
                <?php if ($survey && !empty($beacon_rows)): ?>
                  <?php foreach ($beacon_rows as $i => $b): ?>
                    <tr>
                      <td><?= $i+1 ?></td>
                      <td><?= htmlspecialchars($b['beacon'], ENT_QUOTES) ?></td>
                      <td><?= number_format($b['northing'], 3) ?></td>
                      <td><?= number_format($b['easting'], 3) ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php else: ?>
                  <tr><td colspan="4" class="text-muted">No beacon coordinates found.</td></tr>
                <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>

          <h5 class="section-title">Land Digital Survey Plan</h5>
          <div class="bg-white p-3 rounded-3">
            <div class="d-flex justify-content-center">
              <canvas id="surveyCanvas" width="900" height="700"></canvas>
            </div>
          </div>
        </div>

        <!-- Payment History (placeholder) -->
        <div class="tab-pane fade" id="pane-pay">
          <h5 class="section-title">Payment History</h5>
          <div class="bg-white p-3 rounded-3"><div class="text-muted">Coming soon.</div></div>
        </div>

        <!-- Archived Files -->
        <div class="tab-pane fade" id="pane-arch">
          <h5 class="section-title">Archived Files</h5>
          <div class="bg-white p-3 rounded-3">
            <?php if (!empty($documents)): ?>
              <div class="table-responsive">
                <table class="table table-striped table-narrow mb-0">
                  <thead>
                    <tr>
                      <th>Title</th>
                      <th>Type</th>
                      <th>Size</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($documents as $doc):
                      $title = htmlspecialchars($doc['title'] ?? '', ENT_QUOTES);
                      $type  = htmlspecialchars($doc['doc_type'] ?? '', ENT_QUOTES);
                      $size  = is_numeric($doc['filesize'] ?? null) ? (int)$doc['filesize'] : null;
                      $sizeHuman = $size !== null ? ( $size >= 1048576 ? round($size/1048576,2).' MB' : ( $size >= 1024 ? round($size/1024,2).' KB' : $size.' B') ) : '—';
                      $path  = rtrim((string)$doc['filepath'], '/');
                      $name  = ltrim((string)$doc['filename'], '/');
                      $href  = ($path !== '' ? $path.'/' : '').$name;
                    ?>
                      <tr>
                        <td><?= $title ?></td>
                        <td><?= $type ?: '—' ?></td>
                        <td><?= $sizeHuman ?></td>
                        <td class="text-nowrap">
                          <button 
                            type="button"
                            class="btn btn-sm btn-outline-primary btn-view-doc"
                            data-href="<?= htmlspecialchars($href, ENT_QUOTES) ?>"
                            data-title="<?= $title ?>"
                            data-type="<?= $type ?>">
                            <i class="bi bi-eye"></i> View
                          </button>
                          <a class="btn btn-sm btn-outline-secondary"
                             href="<?= htmlspecialchars($href, ENT_QUOTES) ?>"
                             download>
                            <i class="bi bi-download"></i> Download
                          </a>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            <?php else: ?>
              <div class="text-muted">No archived files found for File Number <strong><?= htmlspecialchars($file_number ?? '—', ENT_QUOTES) ?></strong>.</div>
            <?php endif; ?>
          </div>
        </div>

      </div>
    </div>
  </div>

</div>

<!-- Gmail-style document viewer modal -->
<div class="modal fade" id="docViewerModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title d-flex align-items-center gap-2">
            <i class="bi bi-file-earmark-text"></i>
            <span id="docViewerTitle">Document</span>
        </h5>

        <!-- Right side: Download next to Close -->
        <div class="d-flex align-items-center gap-2 ms-auto">
            <a id="docViewerDownload" class="btn btn-sm btn-light" href="#" download>
            <i class="bi bi-download"></i> Download
            </a>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
    </div>
      <div class="modal-body p-0" style="min-height:70vh; background:#111; position:relative;">
        <div id="docViewerLoading" class="w-100 h-100 d-flex align-items-center justify-content-center text-white">
          <div class="text-center">
            <div class="spinner-border text-light mb-3" role="status"></div>
            <div>Loading preview…</div>
          </div>
        </div>
        <iframe id="docViewerFrame" src="" title="Document preview" style="border:0; width:100%; height:70vh; background:#fff;"></iframe>
      </div>
      <div class="modal-footer justify-content-between">
        <div class="text-muted small">If the preview doesn’t load, click <strong>Download</strong> or “Open in new tab”.</div>
        <div class="d-flex gap-2">
          <a id="docViewerOpenNewTab" class="btn btn-outline-secondary" href="#" target="_blank" rel="noopener">
            <i class="bi bi-box-arrow-up-right"></i> Open in new tab
          </a>
          <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script async src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBko05o_XWNpuZQRV0DrMifzQU2tAZKXig&callback=initMap"></script>

<script>
// ---------------------- Google Map ----------------------
const PARCEL_POINTS = <?= $latLngsJson ?: '[]' ?>;
const MIDPOINT     = <?= $midJson ?: 'null' ?>;

function initMap() {
  const center = MIDPOINT || (PARCEL_POINTS[0] || {lat:6.32485,lng:8.1132});
  const map = new google.maps.Map(document.getElementById('map'), {
    center, zoom: MIDPOINT ? 18 : 8, mapTypeId: 'hybrid',
    mapTypeControl: true, streetViewControl: true, fullscreenControl: true
  });

  if (PARCEL_POINTS.length >= 3) {
    const poly = new google.maps.Polygon({
      paths: PARCEL_POINTS, strokeColor: '#ff7a00', strokeOpacity: 0.9, strokeWeight: 2,
      fillColor: '#ff7a00', fillOpacity: 0.25
    });
    poly.setMap(map);
    const bounds = new google.maps.LatLngBounds();
    PARCEL_POINTS.forEach(pt => bounds.extend(pt));
    map.fitBounds(bounds);
  }

  new google.maps.InfoWindow({
    content: `<div style="min-width:220px">
      <div class="fw-bold mb-1">Land</div>
      <div><strong>Property Number:</strong> <?= htmlspecialchars($propertynumber, ENT_QUOTES) ?></div>
      <div><?= nl2br($descSafe) ?></div>
      <div class="mt-1"><small><?= number_format($AreaNum,2) ?> sq.meters</small></div>
    </div>`
  }).open(map, new google.maps.Marker({position:center, map}));
}

// ---------------------- Survey Canvas ----------------------
const SURVEY_LABELS    = <?= $labelsJson ?: '[]' ?>;
const SURVEY_EASTINGS  = <?= $eastingsJson ?: '[]' ?>;
const SURVEY_NORTHINGS = <?= $northingsJson ?: '[]' ?>;
const SURVEY_META      = <?= $surveyMetaJson ?>;

function drawSurveyPlan() {
  const c = document.getElementById('surveyCanvas');
  if (!c || SURVEY_EASTINGS.length < 3) return;
  const ctx = c.getContext('2d');

  ctx.clearRect(0,0,c.width,c.height);
  ctx.fillStyle = '#fff';
  ctx.fillRect(0,0,c.width,c.height);

  const M = {top: 80, right: 80, bottom: 140, left: 120};

  const minE = Math.min(...SURVEY_EASTINGS), maxE = Math.max(...SURVEY_EASTINGS);
  const minN = Math.min(...SURVEY_NORTHINGS), maxN = Math.max(...SURVEY_NORTHINGS);
  const wM = (maxE - minE) || 1, hM = (maxN - minN) || 1;

  const drawW = c.width - M.left - M.right, drawH = c.height - M.top - M.bottom;
  const scale = Math.min(drawW / wM, drawH / hM) * 0.9; // 10% padding

  function toPx(E, N){ return { x: M.left + (E - minE)*scale, y: M.top + (maxN - N)*scale }; }
  const pts = SURVEY_EASTINGS.map((E,i)=>toPx(E, SURVEY_NORTHINGS[i]));

  ctx.lineWidth = 2; ctx.strokeStyle = '#e53935'; ctx.fillStyle = 'rgba(229,57,53,0.08)';
  ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y);
  for (let i=1;i<pts.length;i++) ctx.lineTo(pts[i].x, pts[i].y);
  ctx.closePath(); ctx.fill(); ctx.stroke();

  // beacons + labels
  ctx.fillStyle='#000'; ctx.strokeStyle='#000';
  pts.forEach((p,i)=>{ ctx.beginPath(); ctx.arc(p.x, p.y, 4, 0, Math.PI*2); ctx.fill();
    ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto'; ctx.textAlign='left'; ctx.textBaseline='bottom';
    ctx.fillText(SURVEY_LABELS[i] || `B${i+1}`, p.x+6, p.y-6);
  });

  function dist(i,j){ const dx=SURVEY_EASTINGS[j]-SURVEY_EASTINGS[i], dy=SURVEY_NORTHINGS[j]-SURVEY_NORTHINGS[i]; return Math.hypot(dx,dy); }
  function bearing(i,j){ const dx=SURVEY_EASTINGS[j]-SURVEY_EASTINGS[i], dy=SURVEY_NORTHINGS[j]-SURVEY_NORTHINGS[i]; let b=(Math.atan2(dx,dy)*180/Math.PI); if(b<0)b+=360; return b; }

  ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto'; ctx.fillStyle='#111'; ctx.strokeStyle='rgba(0,0,0,0.1)';
  for (let i=0;i<pts.length;i++){ const j=(i+1)%pts.length; const p=pts[i], q=pts[j];
    const mx=(p.x+q.x)/2, my=(p.y+q.y)/2;
    const d=dist(i,j), b=bearing(i,j);
    const vx=q.x-p.x, vy=q.y-p.y, len=Math.hypot(vx,vy)||1, nx=-vy/len, ny=vx/len, off=14;
    const lx=mx+nx*off, ly=my+ny*off;
    ctx.textAlign='center'; ctx.textBaseline='middle'; ctx.fillText(`${d.toFixed(2)} m   /   ${b.toFixed(1)}°`, lx, ly);
  }

  // North arrow
  function drawNorth(x,y,s=36){ ctx.save(); ctx.translate(x,y); ctx.fillStyle='#2e7d32'; ctx.strokeStyle='#2e7d32'; ctx.lineWidth=2;
    ctx.beginPath(); ctx.moveTo(0,-s); ctx.lineTo(s*0.4,s*0.6); ctx.lineTo(0,s*0.3); ctx.lineTo(-s*0.4,s*0.6); ctx.closePath(); ctx.fill();
    ctx.font='bold 14px system-ui,-apple-system,Segoe UI,Roboto'; ctx.textAlign='center'; ctx.textBaseline='top'; ctx.fillText('N',0,s*0.65); ctx.restore(); }
  drawNorth(c.width-60, M.top+30);

  // Scale bar (20 m)
  function scaleBar(x,y,meters=20){ const px=meters*scale; ctx.save(); ctx.strokeStyle='#333'; ctx.fillStyle='#333'; ctx.lineWidth=2;
    ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x+px,y); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(x,y-5); ctx.lineTo(x,y+5); ctx.moveTo(x+px,y-5); ctx.lineTo(x+px,y+5); ctx.stroke();
    ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto'; ctx.textAlign='center'; ctx.textBaseline='top'; ctx.fillText(`${meters} METERS`, x+px/2, y+6); ctx.restore(); }
  scaleBar(M.left+40, c.height - M.bottom + 30, 20);

  // Headers & footer meta
  ctx.fillStyle='#111'; ctx.font='bold 12px system-ui,-apple-system,Segoe UI,Roboto'; ctx.textAlign='left'; ctx.textBaseline='top';
  ctx.fillText(SURVEY_META.title1 || 'ABAKALIKI', M.left, 16);
  ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto'; wrapText(ctx, (SURVEY_META.title2||'').toUpperCase(), M.left, 34, c.width - M.left - M.right, 16);
  ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto'; ctx.fillStyle='#d32f2f'; ctx.fillText('Area : ' + (SURVEY_META.area || ''), M.left, 34 + 34);

  const footerY = c.height - 62; ctx.fillStyle='#111'; ctx.font='12px system-ui,-apple-system,Segoe UI,Roboto';
  const lines=[`Origin: ${SURVEY_META.origin||'UTM ZONE 32(N)'}`, `Plan Number : ${SURVEY_META.plan||'NA'}`, `Tracing No : ${SURVEY_META.tracing||'NA'}`, `Signed by: ${SURVEY_META.signedBy||'NA'}`, `Approved by: ${SURVEY_META.approved||'NA'}`, `${SURVEY_META.date||''}`];
  lines.forEach((line,i)=>{ ctx.textAlign='center'; ctx.textBaseline='top'; ctx.fillText(line, c.width/2, footerY + i*14); });

  function wrapText(ctx,text,x,y,maxWidth,lineHeight){ const words=(text||'').split(/\s+/); let line='', yy=y;
    for(let n=0;n<words.length;n++){ const test=line+words[n]+' '; if(ctx.measureText(test).width>maxWidth && n>0){ ctx.fillText(line,x,yy); line=words[n]+' '; yy+=lineHeight; } else { line=test; } }
    if(line) ctx.fillText(line,x,yy);
  }
}

document.addEventListener('DOMContentLoaded', () => {
  const surveyBtn = document.querySelector('[data-bs-target="#pane-survey"]');
  if (surveyBtn) surveyBtn.addEventListener('shown.bs.tab', drawSurveyPlan, {once:true});
});
</script>

<script>
// ---------------------- Docs Viewer Modal ----------------------
(function() {
  const modalEl   = document.getElementById('docViewerModal');
  const modal     = new bootstrap.Modal(modalEl, { backdrop: 'static' });
  const frameEl   = document.getElementById('docViewerFrame');
  const titleEl   = document.getElementById('docViewerTitle');
  const loadingEl = document.getElementById('docViewerLoading');
  const dlBtn     = document.getElementById('docViewerDownload');
  const newTabBtn = document.getElementById('docViewerOpenNewTab');

  function buildPreviewURL(href, type) {
    const url = String(href || '');
    const ext = (url.split('.').pop() || '').toLowerCase();
    const isPDF   = (type || '').toLowerCase() === 'pdf' || ext === 'pdf';
    const isImage = ['png','jpg','jpeg','gif','webp','bmp','svg'].includes(ext);
    if (isPDF || isImage) return url;
    return `https://docs.google.com/gview?embedded=1&url=${encodeURIComponent(url)}`;
  }
  function showLoading(show) { loadingEl.style.display = show ? 'flex' : 'none'; }

  document.addEventListener('click', function(evt) {
    const btn = evt.target.closest('.btn-view-doc');
    if (!btn) return;

    const href  = btn.getAttribute('data-href')  || '';
    const title = btn.getAttribute('data-title') || 'Document';
    const type  = (btn.getAttribute('data-type') || '').trim();

    titleEl.textContent = title;
    dlBtn.href = href;
    newTabBtn.href = href;

    const previewURL = buildPreviewURL(href, type || '');
    frameEl.src = 'about:blank';
    showLoading(true);
    frameEl.onload = () => showLoading(false);
    frameEl.onerror = () => showLoading(false);
    frameEl.src = previewURL;

    modal.show();
  });

  modalEl.addEventListener('hidden.bs.modal', () => { frameEl.src = 'about:blank'; });
})();
</script>
</body>
</html>

