<?php
//
// ---- HANDLE SUBMIT (PDO) ----
if (isset($_POST)) {
  // Your PDO connection (must set $pdo = new PDO(...))
  require_once __DIR__ . '/../../includes/connect.php'; // -> $pdo (PDO)

  // OPTIONAL: if you had a legacy helper, here’s a PDO replacement
  function pdoCheckNewPropertyExists(PDO $pdo, string $beaconsPacked, string $tracingNo): void {
    // Adjust table/columns if yours differ
    $sql = "SELECT COUNT(*) FROM survey_details WHERE TracingNo = :tr OR BeaconNo = :bn";
    $st  = $pdo->prepare($sql);
    $st->execute([':tr'=>$tracingNo, ':bn'=>$beaconsPacked]);
    if ((int)$st->fetchColumn() > 0) {
      $msg = urlencode("A property with that tracing number or beacon set already exists.");
      header("Location: ../report_view.php?msg={$msg}");
      exit;
    }
  }

  // Quick helper for trimming & HTML-escaping strings that go back to the UI
  $h = static fn($v) => is_string($v) ? htmlspecialchars(trim($v), ENT_QUOTES, 'UTF-8') : $v;

  // Map / sanitize incoming values (no manual SQL escaping needed with PDO binds)
  $plotNumber   = $h($_POST['plotNumber']   ?? '');
  $plotDesc     = $h($_POST['plotDesc']     ?? '');
  $townPlanZone = $h($_POST['townPlanZone'] ?? '');
  $layout       = $h($_POST['layout']       ?? '');

  $SurveyNo   = $h($_POST['SurveyNo']   ?? '');
  $TracingNo  = $h($_POST['TracingNo']  ?? '');
  $Benchmark  = $h($_POST['Benchmark']  ?? '');
  $area       = $h($_POST['area']       ?? '');
  $unit       = (float)($_POST['unit']  ?? 1);
  $scale      = $h($_POST['scale']      ?? '');
  $Surveyor   = $h($_POST['Surveyor']   ?? '');
  $designation= $h($_POST['designation']?? '');

  $day   = (int)($_POST['day']   ?? 0);
  $month = (int)($_POST['month'] ?? 0);
  $year  = (int)($_POST['year']  ?? 0);
  $date  = sprintf('%04d-%02d-%02d', $year, $month, $day);

  $approval   = $h($_POST['approval']   ?? '');
  $designation2 = $h($_POST['designation2'] ?? '');
  $day2   = (int)($_POST['day2']   ?? 0);
  $month2 = (int)($_POST['month2'] ?? 0);
  $year2  = (int)($_POST['year2']  ?? 0);
  $date2  = sprintf('%04d-%02d-%02d', $year2, $month2, $day2);

  $startbeacon = preg_replace('/\s/', '', (string)($_POST['startbeacon'] ?? ''));

  // Geospatial axes + units/signs
  $northing = (float)($_POST['northing'] ?? 0);
  $easting  = (float)($_POST['easting']  ?? 0);
  $nunits   = (float)($_POST['nunits']   ?? 0); // 1, -1, or 0
  $eunits   = (float)($_POST['eunits']   ?? 0); // 1, -1, or 0
  $units    = (float)($_POST['units']    ?? 1); // linear unit factor

  // Legacy schema mappings used by your guide
  $PlanNo   = $SurveyNo;           // coordinates.PlanNo
  $origin   = $Benchmark;          // coordinates.Origin
  $locality = $townPlanZone;       // coordinates.Locality
  $district = $layout;             // coordinates.District

  // Optional legacy fields
  $propertyType = $h($_POST['propertyType'] ?? '0');
  $creator      = $h($_POST['creator']      ?? ($_SESSION['user']['fullname'] ?? ($_SESSION['user']['id'] ?? 'system')));

  // Start point (mirror your legacy math exactly)
  $north = $units * $nunits * $northing;
  $east  = $units * $eunits * $easting;

  $start_north = $north;
  $start_east  = $east;

  // Packed strings expected by legacy flow
  $details      = "{$startbeacon}:{$north}:{$east}|";
  $beacons_str  = "";   // "!B001#!B002#"
  $last         = 1;

  // ---- Collect dynamic beacons[] into same sequence legacy loop expects
  $beaconsArr = [];
  if (!empty($_POST['beacons']) && is_array($_POST['beacons'])) {
    foreach ($_POST['beacons'] as $row) {
      $deg    = isset($row['deg'])    && $row['deg']    !== '' ? (float)$row['deg']    : null;
      $min    = isset($row['min'])    && $row['min']    !== '' ? (float)$row['min']    : 0.0;
      $length = isset($row['length']) && $row['length'] !== '' ? (float)$row['length'] : null;
      $number = isset($row['number']) ? preg_replace('/\s/', '', (string)$row['number']) : '';
      $peg    = !empty($row['peg']) ? 1 : 0;

      if ($number !== '' && $length !== null && $deg !== null) {
        $beaconsArr[] = compact('deg','min','length','number','peg');
      }
    }
  }

  // ---- FIRST PASS: build details + packed beacons + closure values
  foreach ($beaconsArr as $r) {
    $ang = deg2rad($r['deg'] + ($r['min'] / 60.0));
    $north = $north + ($r['length'] * cos($ang));
    $east  = $east  + ($r['length'] * sin($ang));
    // Multiply by unit & format (kept exactly like your guide)
    $north_fmt = sprintf('%01.4f', $units * $north);
    $east_fmt  = sprintf('%01.4f', $units * $east);
    $pegFlag   = $r['peg'] ? '1' : '';

    $details     .= "{$r['number']}:{$r['deg']}:{$r['min']}:{$r['length']}:{$pegFlag}<";
    $beacons_str .= "!" . $r['number'] . "#";
    $last++;
  }

  // Duplicate check (PDO version of your helper)
  //pdoCheckNewPropertyExists($pdo, $beacons_str, $TracingNo);
//die('jjjj');
  // ---- Closure check (same tolerance/flow)
  $margin = sqrt(pow(($start_north - $north), 2) + pow(($start_east - $east), 2));
  if ($margin > 3) {
    $msg = "Closure Error ! Recheck all the beacon parameters <br>Closure error value - {$margin} m";
    header("Location: ../report_view.php?msg=" . urlencode($msg));
    exit;
  } else {
    $lastnorth = ($nunits * $northing + $north) / 2.0;
    $lasteast  = ($eunits * $easting  + $east)  / 2.0;
  }

  // ---- SECOND PASS: write coordinates rows using REPLACE
  $pdo->beginTransaction();

  // Reset to raw signed axes (legacy does this)
  $north = $nunits * $northing;
  $east  = $eunits * $easting;

  // REPLACE start beacon
  $sqlReplaceStart = "REPLACE INTO coordinates
      (BeaconNo, Locality, District, Northing, Easting, PlanNo, Origin)
      VALUES (:bn, :loc, :dist, :n, :e, :pl, :org)";
  $stStart = $pdo->prepare($sqlReplaceStart);
  $stStart->execute([
    ':bn'=>$startbeacon, ':loc'=>$locality, ':dist'=>$district,
    ':n'=>$north, ':e'=>$east, ':pl'=>$PlanNo, ':org'=>$origin
  ]);

  // REPLACE subsequent beacons
  $sqlReplace = "REPLACE INTO coordinates
      (BeaconNo, Locality, District, Northing, Easting, PlanNo, Origin, PegPoint)
      VALUES (:bn, :loc, :dist, :n, :e, :pl, :org, :peg)";
  $st = $pdo->prepare($sqlReplace);

  foreach ($beaconsArr as $r) {
    $ang = deg2rad($r['deg'] + ($r['min'] / 60.0));
    $north = $north + ($r['length'] * cos($ang));
    $east  = $east  + ($r['length'] * sin($ang));
    $north_fmt = sprintf('%01.4f', $units * $north);
    $east_fmt  = sprintf('%01.4f', $units * $east);
    if ($r['number'] === $startbeacon) { // close on start beacon midpoint
      $north_fmt = $lastnorth;
      $east_fmt  = $lasteast;
    }
    $st->execute([
      ':bn'=>$r['number'], ':loc'=>$locality, ':dist'=>$district,
      ':n'=>$north_fmt, ':e'=>$east_fmt, ':pl'=>$PlanNo, ':org'=>$origin,
      ':peg'=>$r['peg'] ? 1 : 0
    ]);
  }

  // ---- Insert property
  $pid = "PRP" . time();
  $sqlProp = "INSERT INTO property
    (PlotNumber, PropertyDesc, DrawingNumber, PropertyParentId, PropertyTypeId, LGACode, LayoutId, PropertyNumber, CreationDate, User)
    VALUES (:plotNumber, :propDesc, :drawing, 0, :ptype, :lga, :layout, :pnum, NOW(), :creator)";
  $stProp = $pdo->prepare($sqlProp);
  $stProp->execute([
    ':plotNumber'=>$plotNumber, ':propDesc'=>$plotDesc, ':drawing'=>$SurveyNo,
    ':ptype'=>$propertyType, ':lga'=>$townPlanZone, ':layout'=>$layout,
    ':pnum'=>$pid, ':creator'=>$creator
  ]);

  // PropertyId
  $propertyId = $pdo->lastInsertId();
  if (!$propertyId) { // fallback (rare)
    $propertyId = (string)$pdo->query("SELECT propertyid FROM property ORDER BY propertyid DESC LIMIT 1")->fetchColumn();
  }

  // ---- Insert survey_details (columns per your guide)
  $sqlSurv = "INSERT INTO survey_details
    (PropertyId, SurveyNo, TracingNo, Benchmark, BeaconNo, Area, Surveyor, Surveyor_Title, Survey_Date, Dummy3, dummy5, Dummy6, Dummy7)
    VALUES
    (:pid, :sno, :tr, :bm, :bn, :area, :svy, :title, :sdate, :d3, :d5, :d6, :d7)";
  $stSurv = $pdo->prepare($sqlSurv);
  $stSurv->execute([
    ':pid'=>$propertyId,
    ':sno'=>$SurveyNo,
    ':tr'=>$TracingNo,
    ':bm'=>$Benchmark,
    ':bn'=>$beacons_str,     // packed beacons string
    ':area'=>$area,
    ':svy'=>$Surveyor,
    ':title'=>$designation,
    ':sdate'=>$date,
    ':d3'=>$details,         // long details string
    ':d5'=>$scale,
    ':d6'=>$approval,
    ':d7'=>$date2
  ]);

  $pdo->commit();

  // ---- Redirect like legacy flow
  header("Location: view_survey_description.php?PropertyId={$propertyId}&select=1");
  exit;
}
?>
