<?php
// property_create.php — theming via localStorage + inline bearing appendages
declare(strict_types=1);
session_start();
require_once __DIR__ . '/../../includes/connect.php';

// --- Auth helpers ---
function require_login(): void {
  if (empty($_SESSION['user']['id'])) {
    header('Location: login.php?next=' . urlencode($_SERVER['REQUEST_URI'])); exit;
  }
}
function has_permission(string $perm): bool {
  if (!empty($_SESSION['user']['permissions'])) {
    $p = json_decode((string)$_SESSION['user']['permissions'], true) ?: [];
    if (!empty($p[$perm])) return true;
  }
  try {
    global $pdo;
    $stmt = $pdo->prepare('SELECT roledesc FROM roles WHERE roleid=:r LIMIT 1');
    $stmt->execute([':r' => $_SESSION['user']['roleid'] ?? 0]);
    $json = (string)($stmt->fetchColumn() ?: '');
    $p = json_decode($json, true) ?: [];
    $_SESSION['user']['permissions'] = json_encode($p);
    return !empty($p[$perm]);
  } catch(Throwable $e){ return false; }
}
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
/*
require_login();
if (!has_permission('properties:create')) {
  http_response_code(403);
  echo "<!doctype html><meta charset='utf-8'><title>Forbidden</title>
        <style>body{font-family:system-ui,Segoe UI,Roboto,Arial;padding:48px;background:#f8fafc;color:#0f172a}
        .card{max-width:680px;margin:auto;background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:24px}
        h1{margin:0 0 8px;font-size:22px}p{color:#334155}
        a.button{display:inline-block;margin-top:14px;padding:10px 14px;border:1px solid #94a3b8;border-radius:10px;color:#0f172a;text-decoration:none}
        </style>
        <div class='card'><h1>Access denied</h1>
        <p>You don’t have permission (<code>properties:create</code>) to access this page.</p>
        <a class='button' href='default.php'>Back to Dashboard</a></div>";
  exit;
}
*/
// --- Handle POST (same as earlier; adjust to your schema) ---
$flash = ['type'=>null,'msg'=>null];
if ($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) throw new RuntimeException('Invalid submission token.');
    $plotNumber   = trim($_POST['plotNumber'] ?? '');
    $plotDesc     = trim($_POST['plotDesc'] ?? '');
    $townPlanZone = trim($_POST['townPlanZone'] ?? '');
    $layout       = trim($_POST['layout'] ?? '');
    $surveyNo     = trim($_POST['SurveyNo'] ?? '');
    $tracingNo    = trim($_POST['TracingNo'] ?? '');
    $benchmark    = trim($_POST['Benchmark'] ?? '');
    $area         = trim($_POST['area'] ?? '');
    $unit         = trim($_POST['unit'] ?? '1');
    $scale        = trim($_POST['scale'] ?? '');
    $surveyor     = trim($_POST['Surveyor'] ?? '');
    $designation  = trim($_POST['designation'] ?? '');
    $dateSurvey   = sprintf('%04d-%02d-%02d',(int)($_POST['year'] ?? 0),(int)($_POST['month'] ?? 0),(int)($_POST['day'] ?? 0));
    $approvalBy   = trim($_POST['approval'] ?? '');
    $designation2 = trim($_POST['designation2'] ?? '');
    $dateApproval = sprintf('%04d-%02d-%02d',(int)($_POST['year2'] ?? 0),(int)($_POST['month2'] ?? 0),(int)($_POST['day2'] ?? 0));

    if ($plotNumber===''||$plotDesc===''||$townPlanZone===''||$layout==='') throw new RuntimeException('Fill all required Property Details.');
    if ($surveyNo===''||$tracingNo===''||$benchmark===''||$area===''||$scale===''||$surveyor===''||$designation==='') throw new RuntimeException('Complete required Survey Details.');

    $beacons = $_POST['beacons'] ?? [];
    $beacons = array_values(array_filter($beacons, function($r){
      return trim($r['deg']??'')!=='' || trim($r['min']??'')!=='' || trim($r['length']??'')!=='' || trim($r['number']??'')!=='';
    }));

    $pdo->beginTransaction();
    $stmt = $pdo->prepare("INSERT INTO property
      (plot_number, plot_desc, town_zone, layout_id, survey_no, tracing_no, benchmark, area, unit_factor, scale, surveyor, surveyor_desig, date_survey, approved_by, approver_desig, date_approval, created_by, created_at)
      VALUES (:plot_number,:plot_desc,:town_zone,:layout_id,:survey_no,:tracing_no,:benchmark,:area,:unit_factor,:scale,:surveyor,:survey_desig,:date_survey,:approved_by,:approver_desig,:date_approval,:created_by,NOW())");
    $stmt->execute([
      ':plot_number'=>$plotNumber, ':plot_desc'=>$plotDesc, ':town_zone'=>$townPlanZone, ':layout_id'=>$layout,
      ':survey_no'=>$surveyNo, ':tracing_no'=>$tracingNo, ':benchmark'=>$benchmark, ':area'=>$area,
      ':unit_factor'=>$unit, ':scale'=>$scale, ':surveyor'=>$surveyor, ':survey_desig'=>$designation,
      ':date_survey'=>$dateSurvey, ':approved_by'=>$approvalBy, ':approver_desig'=>$designation2,
      ':date_approval'=>$dateApproval, ':created_by'=>$_SESSION['user']['id'],
    ]);
    $pid = (int)$pdo->lastInsertId();

    if (!empty($beacons)){
      $b = $pdo->prepare("INSERT INTO property_beacons (property_id, idx, deg, `min`, length, beacon_number, peg)
                          VALUES (:pid,:idx,:deg,:min,:length,:number,:peg)");
      $i=1;
      foreach($beacons as $r){
        $b->execute([
          ':pid'=>$pid, ':idx'=>$i++,
          ':deg'=>trim($r['deg']??''), ':min'=>trim($r['min']??''), ':length'=>trim($r['length']??''),
          ':number'=>trim($r['number']??''), ':peg'=>!empty($r['peg'])?1:0
        ]);
      }
    }
    $pdo->commit();
    $flash=['type'=>'success','msg'=>'Property created successfully.'];
    $_POST=[];
  }catch(Throwable $e){
    if ($pdo->inTransaction()) $pdo->rollBack();
    $flash=['type'=>'error','msg'=>'Error: '.htmlspecialchars($e->getMessage())];
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Create Property</title>

<!-- Apply theme BEFORE paint -->
<script>
(function(){
  try{
    var theme = localStorage.getItem('theme') || 'light';
    document.documentElement.setAttribute('data-theme', theme);
  }catch(e){}
})();
</script>

<style>
/* THEME TOKENS */
:root{
  --bg:#f8fafc; --card:#ffffff; --ink:#0f172a; --muted:#475569; --border:#e2e8f0;
  --accent:#2563eb; --accent-2:#16a34a; --danger:#dc2626; --ring:rgba(37,99,235,.25);
  --field:#ffffff; --field-ink:#0f172a;
}
:root[data-theme="dark"]{
  --bg:#0b1020; --card:#0f1832; --ink:#e6ebff; --muted:#a5b2d9; --border:#1f2a4a;
  --accent:#3b82f6; --accent-2:#22c55e; --danger:#ef4444; --ring:rgba(59,130,246,.35);
  --field:#0a1430; --field-ink:#e6ebff;
}

*{box-sizing:border-box}
body{margin:0;font-family:system-ui,Segoe UI,Roboto,Arial;background:var(--bg);color:var(--ink)}
.wrap{max-width:1100px;margin:36px auto;padding:0 20px}
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}
.h-title{font-size:26px;font-weight:700}
.badge{font-size:12px;padding:4px 8px;border:1px solid var(--border);border-radius:999px;color:var(--muted);background:var(--card)}
.card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:22px;box-shadow:0 6px 16px rgba(15,23,42,.08);margin-bottom:16px}
.grid{display:grid;gap:14px}
.grid-2{grid-template-columns:repeat(2,minmax(0,1fr))}
.grid-3{grid-template-columns:repeat(3,minmax(0,1fr))}
label span{display:block;font-size:12px;color:var(--muted);margin-bottom:6px}
input[type=text],select{
  width:100%;background:var(--field);border:1px solid var(--border);color:var(--field-ink);
  border-radius:10px;padding:10px 12px;outline:none
}
input[type=text]:focus,select:focus{border-color:var(--accent);box-shadow:0 0 0 4px var(--ring)}
.actions{display:flex;gap:10px;justify-content:flex-end;margin-top:6px}
.btn{appearance:none;border:1px solid var(--border);background:var(--card);color:var(--ink);padding:10px 14px;border-radius:10px;cursor:pointer}
.btn:hover{filter:brightness(0.98)}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#fff}
.btn-ghost{background:transparent}
.btn-danger{background:var(--danger);border-color:var(--danger);color:#fff}
.toast{position:fixed;top:18px;left:50%;transform:translateX(-50%);background:var(--card);border:1px solid var(--border);border-radius:12px;padding:12px 16px;z-index:50;box-shadow:0 8px 18px rgba(2,6,23,.12)}
.toast.success{border-color:#22c55e}
.toast.error{border-color:#ef4444}
.table{width:100%;border-collapse:separate;border-spacing:0 8px}
.table thead th{text-align:left;font-size:12px;color:var(--muted);font-weight:600;padding:0 10px 6px;border-bottom:1px solid var(--border)}
.table tbody tr{background:var(--card);border:1px solid var(--border)}
.table tbody td{padding:10px;border-top:1px solid var(--border);border-bottom:1px solid var(--border)}
.table tbody tr:first-child td{border-top-left-radius:10px;border-top-right-radius:10px}
.table tbody tr:last-child td{border-bottom-left-radius:10px;border-bottom-right-radius:10px}
.icon-btn{width:36px;height:36px;border-radius:8px;display:inline-grid;place-items:center;border:1px solid var(--border);background:var(--card);color:var(--ink);cursor:pointer}
.icon-btn:hover{background:rgba(148,163,184,.15)}
.flex{display:flex;gap:10px;align-items:center}
hr.sep{border:none;border-top:1px dashed var(--border);margin:10px 0}
.small{font-size:12px;color:var(--muted)}
.required::after{content:" *"; color:#b45309}

/* Input appendage (inline select next to input) */
.input-append{
  display:flex; align-items:stretch; gap:6px;
}
.input-append input[type=text]{flex:1}
.input-append .append{
  width:160px; /* nice compact select width */
}
@media (max-width: 640px){
  .grid-2, .grid-3{grid-template-columns:1fr}
  .input-append{flex-direction:column}
  .input-append .append{width:100%}
}
</style>
</head>
<body>
<div class="wrap">
  <div class="header">
    <div class="h-title">Create Property</div>
    <div class="flex" style="gap:8px">
      <button type="button" class="btn" id="toggleThemeBtn" title="Toggle theme">Toggle Theme</button>
      <div class="badge">Signed in: <?=htmlspecialchars($_SESSION['user']['fullname'] ?? 'User')?> • Role #<?= (int)($_SESSION['user']['roleid'] ?? 0) ?></div>
    </div>
  </div>

  <?php if ($flash['type']): ?>
    <div class="toast <?= $flash['type'] === 'success' ? 'success' : 'error' ?>">
      <?= htmlspecialchars($flash['msg']) ?>
    </div>
    <script>setTimeout(function(){var t=document.querySelector('.toast'); if(t) t.remove();}, 3500);</script>
  <?php endif; ?>

  <form method="post" action="process_create.php" id="propertyForm" autocomplete="off" novalidate >
    <input type="hidden" name="csrf" value="<?=htmlspecialchars($_SESSION['csrf'])?>">

    <!-- Property Details -->
    <div class="card">
      <div class="flex" style="justify-content:space-between"><strong>Property Details</strong><div class="small">Required fields marked *</div></div>
      <div class="grid grid-2">
        <label><span class="required">Plot Number</span><input type="text" name="plotNumber" required></label>
        <label><span class="required">Town Planning Zone</span>
          <select name="townPlanZone" required>
            <option value="">— Select —</option>
            <option>Abakaliki</option><option>Afikpo</option><option>Ebonyi</option><option>Edda</option>
            <option>Ezza North</option><option>Ezza South</option><option>Ikwo</option><option>Ishielu</option>
            <option>Ivo</option><option>Izzi</option><option>Ohaozara</option><option>Ohaukwu</option><option>Onicha</option>
          </select>
        </label>
      </div>
      <div class="grid grid-2" >
        <label><span class="required">Plot Description</span><input type="text" name="plotDesc" required></label>
        <label><span class="required">Layout</span>
          <select name="layout" required>
            <option value="">— Select Layout —</option>
            <option>Nkaliki Layout</option><option>Aguogboriga Layout</option><option>Mile 50 Layout</option>
            <option>Salt City Estate</option><option>Industrial Layout</option><option>City Centre Estate</option>
          </select>
        </label>
      </div>
      
    </div>

    <!-- Survey Details -->
    <div class="card">
      <strong>Survey Details</strong>
      <div class="grid grid-3" style="margin-top:10px">
        <label><span class="required">Survey Plan Number</span><input type="text" name="SurveyNo" required></label>
        <label><span class="required">Tracing Number</span><input type="text" name="TracingNo" required></label>
        <label><span class="required">Origin / Benchmark</span>
          <select name="Benchmark" required>
            <option value="">— Select —</option>
            <option>WGS 84</option><option>UTM ZONE 32(N)</option><option>NIG. NAT.</option>
            <option>NK 48</option><option>AN77783</option><option>A C S I</option>
          </select>
        </label>
      </div>
      <div class="grid grid-3">
        <label><span class="required">Area</span><input type="text" name="area" required></label>
        <label><span class="required">Unit</span>
          <select name="unit" required>
            <option value="1">Square Meter</option><option value="0.092903">Square Foot</option>
            <option value="0.8361274">Square Yard</option><option value="4046.9">Acre</option><option value="10000">Hectare</option>
          </select>
        </label>
        <label><span class="required">Scale</span><input type="text" name="scale" required placeholder="e.g. 1:500"></label>
      </div>
      <div class="grid grid-3">
        <label><span class="required">Surveyor</span><input type="text" name="Surveyor" required></label>
        <label><span class="required">Designation of Surveyor</span>
          <select name="designation" required>
            <option value="">— Select —</option>
            <option>Surveyor General</option><option>Ag. Surveyor General</option>
            <option>Surveyor</option><option>Reg. Surveyor</option><option>Licensed Surveyor</option>
          </select>
        </label>
        <label><span class="required">Date of Survey</span>
          <div class="grid" style="grid-template-columns:1fr 1fr 1fr;">
            <select name="day" required><option value="">Day</option><?php for($d=1;$d<=31;$d++) echo "<option>".str_pad((string)$d,2,'0',STR_PAD_LEFT)."</option>"; ?></select>
            <select name="month" required><option value="">Month</option><?php for($m=1;$m<=12;$m++) echo "<option>".str_pad((string)$m,2,'0',STR_PAD_LEFT)."</option>"; ?></select>
            <select name="year" required><option value="">Year</option><?php for($y=(int)date('Y');$y>=1906;$y--) echo "<option>$y</option>"; ?></select>
          </div>
        </label>
      </div>
      <hr class="sep">
      <div class="grid grid-3">
        <label><span>Approved By</span><input type="text" name="approval"></label>
        <label><span>Designation</span>
          <select name="designation2">
            <option value="">— Select —</option>
            <option>Surveyor General</option><option>Ag. Surveyor General</option><option>Surveyor</option><option>Reg. Surveyor</option><option>Licensed Surveyor</option>
          </select>
        </label>
        <label><span>Date of Approval</span>
          <div class="grid" style="grid-template-columns:1fr 1fr 1fr;">
            <select name="day2"><option value="">Day</option><?php for($d=1;$d<=31;$d++) echo "<option>".str_pad((string)$d,2,'0',STR_PAD_LEFT)."</option>"; ?></select>
            <select name="month2"><option value="">Month</option><?php for($m=1;$m<=12;$m++) echo "<option>".str_pad((string)$m,2,'0',STR_PAD_LEFT)."</option>"; ?></select>
            <select name="year2"><option value="">Year</option><?php for($y=(int)date('Y');$y>=1906;$y--) echo "<option>$y</option>"; ?></select>
          </div>
        </label>
      </div>
    </div>

    <!-- Geospatial -->
    <div class="card">
      <strong>Geospatial Information</strong>
      <div class="grid grid-2" style="margin-top:10px">
        <label><span class="required">Start Beacon</span>
          <input type="text" name="startbeacon" required>
        </label>
        <label><span>Linear Unit</span>
          <select name="units">
            <option value="1">Meters</option>
            <option value="0.3048">Feet</option>
            <option value="0.9144">Yards</option>
          </select>
        </label>
      </div>
      <div class="grid grid-2" >
        <!-- Northing with inline North/South select -->
        <label>
          <span class="required"> Northing</span>
          <div class="input-append">
            <input type="text" name="northing" placeholder="e.g 123456.78" required>
            <select class="append" name="nunits" title="North/South" required>
              <option value="0">—</option>
              <option value="1">North</option>
              <option value="-1">South</option>
            </select>
          </div>
        </label>
        <!-- Easting with inline East/West select -->
        <label>
          <span class="required">Easting</span>
          <div class="input-append">
            <input type="text" name="easting" placeholder="e.g 234567.89" required>
            <select class="append" name="eunits" title="East/West" required>
              <option value="0">—</option>
              <option value="1">East</option>
              <option value="-1">West</option>
            </select>
          </div>
        </label>
      </div>
      
    </div>

    <!-- Land Beacons -->
    <div class="card">
      <div class="flex" style="justify-content:space-between;align-items:center">
        <strong>Land Beacon Numbers</strong>
        <div class="flex">
          <button class="btn" type="button" id="addBeaconBtn">+ Add Beacon</button>
          <button class="btn btn-ghost" type="button" id="clearAllBeaconsBtn" title="Clear all">Clear All</button>
        </div>
      </div>

      <table class="table">
        <thead>
          <tr>
            <th style="width:60px">S/N</th>
            <th>Bearing (Deg)</th>
            <th>Minutes</th>
            <th>Length</th>
            <th>Beacon Number</th>
            <th>Peg</th>
            <th style="width:70px">Action</th>
          </tr>
        </thead>
        <tbody id="beaconsBody"></tbody>
      </table>
      <div class="small">Four rows are ready by default. Click “+ Add Beacon” to add more.</div>
    </div>

    <div class="actions">
      <button type="reset" class="btn">Reset</button>
      <button type="submit" class="btn btn-primary">Submit Property</button>
    </div>
  </form>
</div>

<script>
// Theme toggle helper (uses localStorage.theme)
document.getElementById('toggleThemeBtn')?.addEventListener('click', function(){
  var cur = document.documentElement.getAttribute('data-theme') || 'light';
  var next = cur === 'light' ? 'dark' : 'light';
  document.documentElement.setAttribute('data-theme', next);
  try{ localStorage.setItem('theme', next); }catch(e){}
});

// Beacons dynamic table (4 defaults)
(function(){
  var body = document.getElementById('beaconsBody');
  var addBtn = document.getElementById('addBeaconBtn');
  var clearBtn = document.getElementById('clearAllBeaconsBtn');
  var idx = 0;

  function makeCell(html){
    var td = document.createElement('td');
    td.innerHTML = html;
    return td;
  }
  function rowTemplate(i){
    var tr = document.createElement('tr');
    tr.appendChild(makeCell('<span class="sn">'+(i+1)+'</span>'));
    tr.appendChild(makeCell('<input type="text" inputmode="decimal" name="beacons['+i+'][deg]" placeholder="0–359">'));
    tr.appendChild(makeCell('<input type="text" inputmode="decimal" name="beacons['+i+'][min]" placeholder="0–59.99">'));
    tr.appendChild(makeCell('<input type="text" inputmode="decimal" name="beacons['+i+'][length]" placeholder="Distance">'));
    tr.appendChild(makeCell('<input type="text" name="beacons['+i+'][number]" placeholder="Beacon ID">'));
    tr.appendChild(makeCell('<input type="checkbox" name="beacons['+i+'][peg]" value="1">'));
    tr.appendChild(makeCell('<button type="button" class="icon-btn" data-action="delete" aria-label="Delete">✖</button>'));
    return tr;
  }
  function addRow(){ body.appendChild(rowTemplate(idx)); idx++; }
  function renumber(){
    var rows = body.querySelectorAll('tr');
    var i=0;
    rows.forEach(function(tr){
      var sn = tr.querySelector('.sn'); if (sn) sn.textContent = String(i+1);
      tr.querySelectorAll('input').forEach(function(input){
        input.name = input.name.replace(/beacons\[\d+\]/,'beacons['+i+']');
      });
      i++;
    });
    idx = rows.length;
  }
  function clearAll(){ body.innerHTML=''; idx=0; }

  body.addEventListener('click', function(e){
    var t = e.target;
    if (t && t.getAttribute && t.getAttribute('data-action')==='delete'){
      var tr = t.closest('tr'); if (tr){ tr.remove(); renumber(); }
    }
  });
  addBtn.addEventListener('click', addRow);
  clearBtn.addEventListener('click', clearAll);

  // Default 4 rows
  addRow(); addRow(); addRow(); addRow();

  // Basic client validation
  document.getElementById('propertyForm').addEventListener('submit', function(e){
    var ok = true;
    body.querySelectorAll('tr').forEach(function(tr){
      var deg = (tr.querySelector('input[name*="[deg]"]')||{}).value || '';
      var min = (tr.querySelector('input[name*="[min]"]')||{}).value || '';
      var len = (tr.querySelector('input[name*="[length]"]')||{}).value || '';
      function isNum(x){ return x==='' || /^\d+(\.\d+)?$/.test(x); }
      if (!isNum(deg) || !isNum(min) || !isNum(len)) ok=false;
      if (deg!=='' && (Number(deg)<0 || Number(deg)>=360)) ok=false;
      if (min!=='' && (Number(min)<0 || Number(min)>=60)) ok=false;
    });
    if (!ok){ e.preventDefault(); alert('Fix invalid Beacon values (Deg 0–359, Min 0–59.99, Length numeric).'); }
  });
})();
</script>
</body>
</html>
