<?php
// survey_description_view.php (PDO version)

declare(strict_types=1);

// ===== Guard & includes =====
if (!isset($_GET["newFileId"]) && !isset($_GET["PropertyId"])) {
    header("Location:../property/process_property_view.php");
    exit;
}

require_once "../../includes/connect.php"; // must define $pdo = new PDO(..., ..., ...);
// Recommended in connect.php:
// $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

//require_once "../get_instrument.php";
//require_once "../get_zones.php";
//require_once "../get_layout.php";

// ===== Inputs =====
$propertyid = isset($_GET["PropertyId"]) ? trim((string)$_GET["PropertyId"]) : null;
$newFileId  = isset($_GET["newFileId"]) ? trim((string)$_GET["newFileId"]) : null;

// ===== Fetch property via PDO =====
try {
    if ($propertyid) {
        $stmt = $pdo->prepare("
            SELECT propertydesc, lgacode, propertyid, propertynumber
            FROM property
            WHERE propertyid = :pid
            LIMIT 1
        ");
        $stmt->execute([':pid' => $propertyid]);
    } else {
        $stmt = $pdo->prepare("
            SELECT f.fileid, f.filenumber, p.propertydesc, p.lgacode, p.propertyid, p.propertynumber
            FROM file f
            INNER JOIN property p ON f.fileid = p.fileid
            WHERE f.fileid = :fid
            LIMIT 1
        ");
        $stmt->execute([':fid' => $newFileId]);
    }

    $row = $stmt->fetch();
    if (!$row) {
        $msg = urlencode("Property not found.");
        header("Location:../report_view.php?msg=$msg");
        exit;
    }
    // unpack
    $propertydesc   = $row['propertydesc'] ?? '';
    $lgacode        = $row['lgacode'] ?? '';
    $propertyid     = $row['propertyid'] ?? ($propertyid ?? '');
    $propertynumber = $row['propertynumber'] ?? '';
    $filenumber     = $row['filenumber'] ?? '';
} catch (Throwable $e) {
    http_response_code(500);
    die("Database error [property]: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'));
}

// ===== Fetch survey details via PDO =====
try {
    $stmt2 = $pdo->prepare("SELECT * FROM survey_details WHERE propertyid = :pid LIMIT 1");
    $stmt2->execute([':pid' => $propertyid]);
    $r2 = $stmt2->fetch();
    if (!$r2) {
        $msg = urlencode("Please fill the survey details first");
        header("Location:../report_view.php?msg=$msg");
        exit;
    }
} catch (Throwable $e) {
    http_response_code(500);
    die("Database error [survey_details]: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'));
}

// ===== Parse survey details =====
$SurveyNo   = $r2['SurveyNo']   ?? null;
$TracingNo  = $r2['TracingNo']  ?? null;
$Area       = $r2['Area']       ?? '';
$BeaconNo   = $r2['BeaconNo']   ?? '';
$Dummy3     = $r2['Dummy3']     ?? '';

$beacon        = $BeaconNo !== '' ? explode("#", (string)$BeaconNo) : [];
$beacon_count  = max(0, count($beacon) - 1);
$details       = $Dummy3 !== '' ? explode("|", (string)$Dummy3) : [];
$c1 = isset($details[0]) ? explode(":", $details[0]) : []; // start:north:east
$c2 = isset($details[1]) ? explode("<", $details[1]) : []; // segments

// ===== Helpers =====
function e($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$startBeaconLabel = "";
if (!empty($beacon) && isset($beacon[0])) {
    $tmp = ltrim($beacon[0]);
    $startBeaconLabel = strlen($tmp) > 0 ? substr($tmp, 1) : "";
}

$northVal = $c1[1] ?? null;
$eastVal  = $c1[2] ?? null;

function abs_val_dir($val, $posLabel, $negLabel) {
    if ($val === null || $val === "") return ["", ""];
    $num = (float)$val;
    $abs = str_replace("-", "", (string)$val);
    $dir = $num >= 0 ? $posLabel : $negLabel;
    return [$abs, $dir];
}
[$northAbs, $northDir] = abs_val_dir($northVal, "North", "South");
[$eastAbs,  $eastDir ] = abs_val_dir($eastVal,  "East",  "West");

// For optional display
$newFileNumber = $_GET['newFileNumber'] ?? $filenumber ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Descriptions of Survey</title>

<style>
:root{
  --bg:#0f172a;--card:#111827;--text:#e5e7eb;--muted:#94a3b8;--accent:#22d3ee;--border:#1f2937;--chip:#0ea5e9;--shadow:0 10px 30px rgba(0,0,0,.35)
}
.light{--bg:#f8fafc;--card:#fff;--text:#0f172a;--muted:#475569;--accent:#0891b2;--border:#e2e8f0;--chip:#0369a1;--shadow:0 8px 24px rgba(2,6,23,.06)}
*{box-sizing:border-box}html,body{height:100%}
body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,"Noto Sans",sans-serif}
.container{max-width:1200px;margin:32px auto;padding:0 16px}
.header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px}
.title{font-size:clamp(22px,2.6vw,32px);font-weight:800;letter-spacing:-.02em;display:flex;align-items:center;gap:10px}
.title .chip{font-size:12px;font-weight:700;background:linear-gradient(90deg,var(--chip),#38bdf8);color:#fff;padding:4px 10px;border-radius:999px}
.actions{display:flex;gap:8px;flex-wrap:wrap}
.btn{border:1px solid var(--border);background:var(--card);color:var(--text);padding:10px 14px;border-radius:10px;cursor:pointer;transition:.2s;box-shadow:var(--shadow)}
.btn:hover{transform:translateY(-1px)}.btn.primary{background:var(--accent);color:#00212a;border-color:transparent;font-weight:700}.btn.ghost{background:transparent}.btn.icon{display:flex;align-items:center;gap:8px;font-weight:600}
.grid{display:grid;gap:16px;grid-template-columns:1fr}
@media(min-width:900px){.grid{grid-template-columns:1.15fr 1fr}}
.card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:18px;box-shadow:var(--shadow)}
.card h3{margin:0 0 12px 0;font-size:16px;text-transform:uppercase;letter-spacing:.14em;color:var(--muted)}
.kv{display:grid;grid-template-columns:200px 1fr;gap:10px 16px}
.kv .label{color:var(--muted)}.kv .value{font-weight:600;letter-spacing:.01em}
.table-wrap{overflow:auto;border-radius:14px;border:1px solid var(--border);background:var(--card);box-shadow:var(--shadow)}
table{width:100%;border-collapse:separate;border-spacing:0;min-width:720px}
thead th{position:sticky;top:0;background:linear-gradient(180deg,rgba(255,255,255,.02),rgba(0,0,0,0));text-align:left;font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:var(--muted);padding:14px 12px;border-bottom:1px solid var(--border)}
tbody td{padding:14px 12px;border-bottom:1px dashed var(--border);vertical-align:top}
tbody tr:hover{background:rgba(2,132,199,.06)}.badge{font-size:12px;border:1px solid var(--border);padding:2px 8px;border-radius:999px;color:var(--muted)}
.footer-actions{display:flex;justify-content:flex-end;margin-top:18px;gap:8px}
@media print{.actions,.footer-actions,.theme-toggle{display:none!important}body{background:#fff;color:#000}.card,.table-wrap{box-shadow:none;border-color:#ddd}}
.theme-toggle{display:flex;align-items:center;gap:8px;border:1px solid var(--border);background:var(--card);padding:8px 12px;border-radius:999px;box-shadow:var(--shadow);color:var(--muted)}
.theme-toggle input{accent-color:var(--accent);cursor:pointer}
.small-muted{color:var(--muted);font-size:12px}.hr{height:1px;background:var(--border);margin:12px 0 2px}
.small-copy{
  padding:4px 8px;
  margin-left:6px;
  font-size:12px;
  line-height:1;
  border-radius:6px;
}
</style>
</head>
<body id="appRoot">
<div class="container">
  <div class="header">
    <div class="title">Descriptions of Survey <span class="chip">Property</span></div>
    <div class="actions">
      <label class="theme-toggle"><input type="checkbox" id="themeChk" /><span>Light mode</span></label>
      <button class="btn icon ghost" id="printBtn" type="button">🖨️ <span>Print</span></button>
      <form action="print_survey_description.php" method="get" style="margin:0">
        <input type="hidden" name="PropertyId" value="<?php echo e($propertyid)?>">
        <button class="btn icon primary" type="submit">🧾 <span>Print (Server)</span></button>
      </form>
    </div>
  </div>

  <div class="small-muted">
    Property ID: <strong><?php echo e($propertynumber); ?></strong>
    <span class="hr"></span>
  </div>

  <div class="grid">
    <div class="card">
      <h3>Property Information</h3>
      <div class="kv">
        <?php if(!empty($newFileNumber)): ?>
          <div class="label">File Number</div><div class="value"><?php echo e($newFileNumber); ?></div>
        <?php endif; ?>
        <div class="label">Property ID</div>
<div class="value">
  <?php echo e($propertynumber); ?>
  <button type="button" class="btn ghost small-copy" id="copyPidBtn" 
          data-pid="<?php echo e($propertynumber); ?>" title="Copy Property ID">
    📋
  </button>
</div>
        <div class="label">Property Description</div><div class="value"><?php echo e($propertydesc); ?></div>
        <div class="label">Town Planning Zone</div><div class="value"><?php// echo e(getTownPlanZone($lgacode)); ?></div>
      </div>
    </div>

    <div class="card">
      <h3>Survey Information</h3>
      <div class="kv">
        <div class="label">Survey Plan Number</div><div class="value"><?php echo e($SurveyNo ?? "—"); ?></div>
        <div class="label">Tracing Number</div><div class="value"><?php echo e($TracingNo ?? "—"); ?></div>
        <div class="label">Area</div><div class="value"><?php echo $Area !== '' ? e($Area)." sq. meters" : "—"; ?></div>
      </div>
    </div>
  </div>

  <div class="card" style="margin-top:16px">
    <h3>Survey Description</h3>
    <div class="kv" style="margin-bottom:6px">
      <div class="label">Start Beacon</div><div class="value"><?php echo e($startBeaconLabel ?: "—"); ?></div>
      <div class="label">Northing</div><div class="value"><?php echo $northAbs !== "" ? e($northAbs)." ".e($northDir) : "—"; ?></div>
      <div class="label">Easting</div><div class="value"><?php echo $eastAbs  !== "" ? e($eastAbs) ." ".e($eastDir)  : "—"; ?></div>
      <div class="label">Unit</div><div class="value">Meters</div>
    </div>
  </div>

  <div class="card" style="margin-top:16px">
    <h3>Land Beacon Numbers</h3>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th style="width:90px">S/N</th>
            <th>Bearing (Degree&nbsp;Minutes)</th>
            <th style="width:140px">Length</th>
            <th style="width:220px">Beacon Number</th>
            <th style="width:120px">Peg&nbsp;Point</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $b2 = [];
          for ($i = 2; $i < $beacon_count + 2; $i++) {
              if (isset($c2[$i-2])) $b2[$i] = explode(":", $c2[$i-2]);

              $bearingDeg   = isset($b2[$i][1]) ? trim($b2[$i][1]) : "";
              $bearingMin   = isset($b2[$i][2]) ? trim($b2[$i][2]) : "";
              $bearingLabel = trim($bearingDeg . ($bearingDeg !== "" && $bearingMin !== "" ? "° " : "") . $bearingMin);

              $length = isset($b2[$i][3]) ? trim($b2[$i][3]) : "";

              $beaconLabel = "";
              if (isset($beacon[$i-1]) && trim($beacon[$i-1]) !== "") {
                  $beaconLabel = substr(ltrim($beacon[$i-1]), 1);
              } elseif (isset($beacon[0]) && $i == $beacon_count + 1) {
                  $beaconLabel = substr(ltrim($beacon[0]), 1);
              }

              $pegPoint = (!empty($b2[$i][4])) ? "Peg point" : "";
              ?>
              <tr>
                <td><span class="badge"><?php echo e($i-1); ?></span></td>
                <td><?php echo $bearingLabel !== "" ? e($bearingLabel) : "—"; ?></td>
                <td><?php echo $length !== "" ? e($length) : "—"; ?></td>
                <td><?php echo $beaconLabel !== "" ? e($beaconLabel) : "—"; ?></td>
                <td><?php echo $pegPoint !== "" ? e($pegPoint) : "—"; ?></td>
              </tr>
              <?php
          } ?>
        </tbody>
      </table>
    </div>
    <div class="footer-actions">
      <button class="btn icon" type="button" id="toTop">⬆️ <span>Back to Top</span></button>
    </div>
  </div>

  <form action="print_survey_description.php" method="get" id="serverPrintForm" style="display:none">
    <input type="hidden" name="PropertyId" value="<?php echo e($propertyid)?>" />
  </form>
</div>

<script>
// Theme toggle with localStorage
(function(){
  const root = document.getElementById('appRoot');
  const chk  = document.getElementById('themeChk');
  const saved = localStorage.getItem('survey_theme') || 'dark';
  if (saved === 'light') { root.classList.add('light'); chk.checked = true; }
  chk.addEventListener('change', () => {
    if (chk.checked) { root.classList.add('light'); localStorage.setItem('survey_theme','light'); }
    else { root.classList.remove('light'); localStorage.setItem('survey_theme','dark'); }
  });
})();
document.getElementById('printBtn').addEventListener('click', () => window.print());
document.getElementById('toTop').addEventListener('click', () => window.scrollTo({top:0, behavior:'smooth'}));
// Copy Property ID
const copyBtn = document.getElementById('copyPidBtn');
if (copyBtn) {
  copyBtn.addEventListener('click', () => {
    const pid = copyBtn.getAttribute('data-pid') || '';
    if (!pid) return;
    navigator.clipboard.writeText(pid).then(() => {
      copyBtn.textContent = "✅";
      setTimeout(()=>{ copyBtn.textContent = "📋"; }, 1500);
    });
  });
}
</script>
</body>
</html>
