<?php
// add_property_file.php
require_once __DIR__ . '/../../includes/connect.php'; // defines $pdo

// ===== AJAX search endpoint =====
if (isset($_GET['action']) && $_GET['action'] === 'search_property') {
    header('Content-Type: application/json; charset=utf-8');
    $q = trim($_GET['q'] ?? '');
    if ($q === '') { echo json_encode(['ok'=>true,'items'=>[]]); exit; }
    try {
        $stmt = $pdo->prepare("
            SELECT propertyid, propertynumber, propertydesc, lgacode
            FROM property
            WHERE propertynumber LIKE :q
            ORDER BY propertynumber
            LIMIT 25
        ");
        $like = "%{$q}%";
        $stmt->bindParam(':q', $like, PDO::PARAM_STR);
        $stmt->execute();
        echo json_encode(['ok'=>true,'items'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    } catch (Throwable $e) {
        http_response_code(500);
        echo json_encode(['ok'=>false,'error'=>'DB error']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
<title>Add Property File</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root{
    --bg:#0f172a; --panel:#111827; --muted:#64748b; --text:#e5e7eb;
    --accent:#06b6d4; --accent-2:#22c55e; --danger:#dc2626; --ring: rgba(6,182,212,.35);
    --card:#0b1220; --input:#0b1220; --thead:rgba(255,255,255,.04); --row-border:rgba(255,255,255,.06);
    --hover:rgba(6,182,212,.08); --shadow: rgba(0,0,0,.35); --overlay: rgba(2,6,23,.78);
    --soft-border:#334155; --soft-bg:rgba(255,255,255,.02); --soft-placeholder:#cbd5e1;
  }
  [data-theme="light"]{
    --bg:#f3f4f6; --panel:#ffffff; --muted:#6b7280; --text:#0f172a;
    --accent:#0891b2; --accent-2:#16a34a; --danger:#dc2626; --ring: rgba(8,145,178,.28);
    --card:#ffffff; --input:#ffffff; --thead:#f1f5f9; --row-border:#e5e7eb;
    --hover:#e0f2fe; --shadow: rgba(0,0,0,.08);
    --soft-border:#dbeafe; --soft-bg:#ffffff; --soft-placeholder:#94a3b8;
  }

  *{box-sizing:border-box}
  html,body{height:100%}
  body{margin:0;font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,"Helvetica Neue";background:var(--bg);color:var(--text)}
  .container{max-width:1100px;margin:32px auto 96px;padding:0 16px}
  .header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}
  .title{font-size:28px;font-weight:700;display:flex;align-items:center;gap:12px}
  .badge{font-size:12px;font-weight:700;color:#022c22;background:linear-gradient(90deg,#34d399,#10b981);padding:4px 10px;border-radius:999px}

  .card{background:var(--card);border:1px solid rgba(0,0,0,.05);box-shadow:0 10px 30px var(--shadow), inset 0 1px 0 rgba(255,255,255,.03);border-radius:16px;padding:20px;margin-bottom:18px}
  [data-theme="dark"] .card{border-color:rgba(255,255,255,.08)}

  /* --- Screenshot-like "soft" inputs (top labels, rounded, soft blue border) --- */
  .soft-card{background:var(--soft-bg)}
  .soft-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}
  .soft-group{display:flex;flex-direction:column;gap:8px}
  .soft-group label{font-weight:600;color:var(--muted)}
  .soft-input, .soft-select{
    width:100%;background:var(--input);color:var(--text);
    border:2px solid var(--soft-border); border-radius:14px; padding:14px 14px; outline:none;
    transition: box-shadow .2s, border-color .2s
  }
  .soft-select{appearance:none}
  .soft-input::placeholder{color:var(--soft-placeholder)}
  .soft-input:focus, .soft-select:focus{border-color:var(--accent);box-shadow:0 0 0 4px var(--ring)}

  /* General form pieces used elsewhere */
  .grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
  .section-title{font-weight:800;margin:8px 0 14px;font-size:16px;display:flex;align-items:center;gap:10px}
  .dot{width:8px;height:8px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 4px rgba(6,182,212,.15)}
  .hint{font-size:12px;color:var(--muted);margin-top:6px}
  .pill{background:rgba(0,0,0,.04);padding:2px 8px;border-radius:999px;border:1px solid rgba(0,0,0,.06);font-size:12px}
  [data-theme="dark"] .pill{background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.08)}

  .actions{display:flex;gap:10px;justify-content:flex-end;margin-top:18px}
  .btn{appearance:none;border:none;cursor:pointer;padding:12px 16px;border-radius:12px;font-weight:800;background:transparent;color:var(--text);border:1px solid rgba(0,0,0,.12);transition: transform .06s ease, background .2s, border-color .2s}
  [data-theme="dark"] .btn{border-color:rgba(255,255,255,.08)}
  .btn:hover{transform:translateY(-1px)}
  .btn:active{transform:translateY(1px)}
  .btn-accent{background:linear-gradient(90deg,var(--accent),#22d3ee);color:#06202a;border-color:transparent}
  .btn-ghost{background:transparent}
  .btn-sm{padding:8px 12px;border-radius:10px;font-size:13px}
  .btn-icon{display:inline-flex;gap:8px;align-items:center}

  /* Modal */
  .overlay{position:fixed;inset:0;background:var(--overlay);backdrop-filter:blur(6px);display:flex;align-items:center;justify-content:center;z-index:9999}
  .modal{width:min(900px,96vw);background:var(--card);border:1px solid rgba(0,0,0,.08);border-radius:18px;box-shadow:0 30px 60px var(--shadow);padding:18px}
  [data-theme="dark"] .modal{border-color:rgba(255,255,255,.08)}
  .modal-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
  .modal-title{font-weight:800;font-size:18px;display:flex;align-items:center;gap:10px}
  .modal-body{margin-top:8px}
  .searchbar{display:flex;gap:10px}.searchbar input{flex:1}
  .result{margin-top:14px;border:1px solid rgba(0,0,0,.08);border-radius:12px;overflow:hidden}
  [data-theme="dark"] .result{border-color:rgba(255,255,255,.08)}
  table{width:100%;border-collapse:collapse}
  th,td{padding:12px 10px;text-align:left}
  thead{background:var(--thead)}
  tbody tr{border-top:1px solid var(--row-border);cursor:pointer}
  tbody tr:hover{background:var(--hover)}
  .empty{padding:28px;text-align:center;color:var(--muted)}

  /* People cards + uploads */
  .person-card{background:rgba(0,0,0,.03);border:1px solid rgba(0,0,0,.08);border-radius:12px;padding:12px;margin-top:12px}
  [data-theme="dark"] .person-card{background:rgba(255,255,255,.03);border-color:rgba(255,255,255,.08)}
  .person-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
  .subtle{color:var(--muted);font-size:12px}
  .remove{color:#ef9a9a;cursor:pointer}

  .row-uploads{display:grid;grid-template-columns:1fr 1fr;gap:18px}
  .upload-field{display:flex;flex-direction:column;gap:8px}
  .upload-field label{font-weight:600;color:var(--muted)}
  .passbox{display:flex;gap:12px;align-items:center}
  .passbox img{width:64px;height:64px;object-fit:cover;border-radius:10px;border:1px solid rgba(0,0,0,.12)}
  [data-theme="dark"] .passbox img{border-color:rgba(255,255,255,.08)}
</style>
</head>
<body>
<script>
  // Theme init
  (function(){
    try{
      const saved = localStorage.getItem('theme');
      const theme = (saved === 'light' || saved === 'dark') ? saved : 'dark';
      document.documentElement.setAttribute('data-theme', theme);
    }catch(e){}
  })();
</script>

<div class="container">
  <div class="header">
    <div class="title">📁 Add Property File <span class="badge">Lands IMS</span></div>
    <div class="inline">
      <span class="pill">Step 1: Select Property</span>
      <span class="pill">Step 2: File & Parcel</span>
      <span class="pill">Step 3: Ownership</span>
    </div>
  </div>

  <!-- Selected property summary -->
  <div class="card" id="propSummary" style="display:none">
    <div class="section-title"><span class="dot"></span> Selected Property</div>
    <div class="grid-3">
      <div><div class="subtle">Property Number</div><div id="v_propertynumber" style="font-weight:700"></div></div>
      <div><div class="subtle">Plot Description</div><div id="v_propertydesc" style="font-weight:700"></div></div>
      <div><div class="subtle">LGA</div><div id="v_lga" style="font-weight:700"></div></div>
    </div>
  </div>

  <!-- ===== FORM START ===== -->
  <form action="process_form_P.php" method="post" id="fileForm" enctype="multipart/form-data">

    <!-- Step 2: File & Parcel (styled like your screenshot) -->
    <div class="card soft-card">
      <div class="section-title"><span class="dot"></span> File & Parcel</div>

      <div class="soft-grid">
        <!-- Property Type -->
        <div class="soft-group">
          <label>Property Type</label>
          <select name="propertyType" id="propertyType" class="soft-select" required>
            <option value="">— Select —</option>
            <option value="private">Private Acquired Land</option>
            <option value="govt">Government Acquired Land</option>
          </select>
        </div>

        <!-- File Number (Prefix + Number) -->
        <div class="soft-group">
          <label>File Number</label>
          <div style="display:flex;gap:10px">
            <input type="text" id="Prefix" name="Prefix" class="soft-input" style="max-width:110px" readonly placeholder="PAL/"/>
            <input type="text" id="fileNumber" name="fileNumber" class="soft-input" required placeholder="Enter file number" />
          </div>
        </div>

        <!-- Instrument Type -->
        <div class="soft-group">
          <label>Instrument Type</label>
          <select name="instrumentType" id="instrumentType" class="soft-select" required>
            <option value="">— Select —</option>
            <option>AGREEMENT</option><option>ASSIGNMENT OF LEASE</option><option>BUILDING LEASE</option>
            <option>Certificate Of Occupancy</option><option>CUSTOMARY RIGHT OF OCCUPANCY</option>
            <option>Deed of Assignment</option><option>Deed of Conveyance</option><option>DEED OF GIFT</option>
            <option>Deed of Lease</option><option>DEED OF MORTGAGE DBENTURE</option><option>DEED OF RECTIFICATION</option>
            <option>DEED OF RELEASE</option><option>Deed of Sublease</option><option>Deed of Surrender</option>
            <option>EXCHANGE OF LETTERS</option><option>Legal Mortgage</option><option>Memorandum of Understanding</option>
            <option>Power of Attorney</option><option>Tripartite Legal Mortgage</option>
          </select>
        </div>

        <!-- Land Use -->
        <div class="soft-group">
          <label>Land Use</label>
          <select name="landUse" id="landUse" class="soft-select" required>
            <option value="">— Select —</option>
            <option value="residential">Residential</option>
            <option value="commercial">Commercial</option>
            <option value="industrial">Industrial</option>
            <option value="agricultural">Agricultural</option>
            <option value="institutional">Institutional</option>
            <option value="mixed">Mixed Use</option>
          </select>
        </div>
      </div>

      <div class="hint" style="margin-top:8px">Prefix auto-fills based on Property Type (PAL/ or GAL/).</div>
    </div>

    <!-- Step 3: Ownership (TOP-LEVEL CARD) -->
    <div class="card">
      <div class="section-title"><span class="dot"></span> Ownership</div>
      <div class="soft-grid">
        <div class="soft-group" style="grid-column:1 / -1">
          <label>Ownership Type</label>
          <select name="ownershipType" id="ownershipType" class="soft-select" required>
            <option value="">— Select —</option>
            <option value="individual">Individual</option>
            <option value="corporate">Corporate/Commercial</option>
            <option value="joint">Joint Ownership</option>
          </select>
        </div>
      </div>
    </div>

    <!-- Individual Owner -->
    <div id="individualBox" class="card" style="display:none">
      <div class="section-title"><span class="dot"></span> Individual Owner</div>

      <!-- Uploads row: Passport & ID (each with own label) -->
      <div class="row-uploads">
        <div class="upload-field">
          <label>Upload Passport</label>
          <div class="passbox">
            <img src="" alt="Passport Preview" style="display:none">
            <input type="file" name="individual_passport" accept="image/*" onchange="previewSibling(this)">
          </div>
        </div>
        <div class="upload-field">
          <label>Upload ID</label>
          <div class="passbox">
            <img src="" alt="ID Preview" style="display:none">
            <input type="file" name="individual_idcard" accept="image/*" onchange="previewSibling(this)">
          </div>
        </div>
      </div>

      <div class="grid-3" style="margin-top:6px">
        <div><label class="subtle">Title</label>
          <select name="title" class="soft-select"><option value="">—</option><option>Mr</option><option>Mrs</option><option>Miss</option><option>Dr.</option><option>Engr.</option><option>Chief</option></select>
        </div>
        <div><label class="subtle">Surname</label><input type="text" name="surname" class="soft-input"/></div>
        <div><label class="subtle">First Name</label><input type="text" name="firstname" class="soft-input"/></div>
      </div>
      <div class="grid-3">
        <div><label class="subtle">Other Names</label><input type="text" name="middlename" class="soft-input"/></div>
        <div><label class="subtle">Sex</label><select name="sex" class="soft-select"><option value="">—</option><option>Male</option><option>Female</option></select></div>
        <div><label class="subtle">Phone</label><input type="text" name="phone" class="soft-input"/></div>
      </div>
      <div class="grid-3">
        <div><label class="subtle">Email</label><input type="email" name="email" class="soft-input"/></div>
        <div><label class="subtle">Date of Birth</label><input type="date" name="dob" class="soft-input"/></div>
        <div>
          <label class="subtle">NIN</label>
          <input type="text" name="nin" inputmode="numeric" maxlength="11" pattern="\d{11}" placeholder="11-digit NIN" class="soft-input"/>
          <div class="hint">Enter 11 digits (e.g., 12345678901).</div>
        </div>
      </div>
    </div>

    <!-- Corporate Owner -->
    <div id="corporateBox" class="card" style="display:none">
      <div class="section-title"><span class="dot"></span> Corporate Owner</div>
      <div class="grid-3">
        <div><label class="subtle">Company Name</label><input type="text" name="companyName" class="soft-input"/></div>
        <div><label class="subtle">Registration No.</label><input type="text" name="registrationNo" class="soft-input"/></div>
        <div><label class="subtle">Company Email</label><input type="email" name="companyEmail" class="soft-input"/></div>
      </div>

      <!-- Director 1 -->
      <div class="person-card">
        <div class="person-head"><strong>Director 1</strong><span class="subtle">Required</span></div>

        <div class="row-uploads">
          <div class="upload-field">
            <label>Upload Passport</label>
            <div class="passbox">
              <img src="" alt="Passport Preview" style="display:none">
              <input type="file" name="corp_director1_passport" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
          <div class="upload-field">
            <label>Upload ID</label>
            <div class="passbox">
              <img src="" alt="ID Preview" style="display:none">
              <input type="file" name="corp_director1_idcard" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
        </div>

        <div class="grid-3" style="margin-top:6px">
          <div><label class="subtle">Title</label>
            <select name="d1_title" class="soft-select"><option value="">—</option><option>Mr</option><option>Mrs</option><option>Miss</option><option>Dr.</option><option>Engr.</option><option>Chief</option></select>
          </div>
          <div><label class="subtle">Surname</label><input type="text" name="d1_surname" class="soft-input"/></div>
          <div><label class="subtle">First Name</label><input type="text" name="d1_firstname" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Other Names</label><input type="text" name="d1_middlename" class="soft-input"/></div>
          <div><label class="subtle">Sex</label><select name="d1_sex" class="soft-select"><option value="">—</option><option>Male</option><option>Female</option></select></div>
          <div><label class="subtle">Phone</label><input type="text" name="d1_phone" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Email</label><input type="email" name="d1_email" class="soft-input"/></div>
          <div><label class="subtle">Date of Birth</label><input type="date" name="d1_dob" class="soft-input"/></div>
          <div>
            <label class="subtle">NIN</label>
            <input type="text" name="d1_nin" inputmode="numeric" maxlength="11" pattern="\d{11}" placeholder="11-digit NIN" class="soft-input"/>
            <div class="hint">11 digits.</div>
          </div>
        </div>
      </div>

      <!-- Director 2 -->
      <div class="person-card">
        <div class="person-head"><strong>Director 2</strong><span class="subtle">Required</span></div>

        <div class="row-uploads">
          <div class="upload-field">
            <label>Upload Passport</label>
            <div class="passbox">
              <img src="" alt="Passport Preview" style="display:none">
              <input type="file" name="corp_director2_passport" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
          <div class="upload-field">
            <label>Upload ID</label>
            <div class="passbox">
              <img src="" alt="ID Preview" style="display:none">
              <input type="file" name="corp_director2_idcard" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
        </div>

        <div class="grid-3" style="margin-top:6px">
          <div><label class="subtle">Title</label>
            <select name="d2_title" class="soft-select"><option value="">—</option><option>Mr</option><option>Mrs</option><option>Miss</option><option>Dr.</option><option>Engr.</option><option>Chief</option></select>
          </div>
          <div><label class="subtle">Surname</label><input type="text" name="d2_surname" class="soft-input"/></div>
          <div><label class="subtle">First Name</label><input type="text" name="d2_firstname" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Other Names</label><input type="text" name="d2_middlename" class="soft-input"/></div>
          <div><label class="subtle">Sex</label><select name="d2_sex" class="soft-select"><option value="">—</option><option>Male</option><option>Female</option></select></div>
          <div><label class="subtle">Phone</label><input type="text" name="d2_phone" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Email</label><input type="email" name="d2_email" class="soft-input"/></div>
          <div><label class="subtle">Date of Birth</label><input type="date" name="d2_dob" class="soft-input"/></div>
          <div>
            <label class="subtle">NIN</label>
            <input type="text" name="d2_nin" inputmode="numeric" maxlength="11" pattern="\d{11}" placeholder="11-digit NIN" class="soft-input"/>
            <div class="hint">11 digits.</div>
          </div>
        </div>
      </div>

      <!-- Company Secretary -->
      <div class="person-card">
        <div class="person-head"><strong>Company Secretary</strong><span class="subtle">Required</span></div>

        <div class="row-uploads">
          <div class="upload-field">
            <label>Upload Passport</label>
            <div class="passbox">
              <img src="" alt="Passport Preview" style="display:none">
              <input type="file" name="corp_secretary_passport" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
          <div class="upload-field">
            <label>Upload ID</label>
            <div class="passbox">
              <img src="" alt="ID Preview" style="display:none">
              <input type="file" name="corp_secretary_idcard" accept="image/*" onchange="previewSibling(this)">
            </div>
          </div>
        </div>

        <div class="grid-3" style="margin-top:6px">
          <div><label class="subtle">Title</label>
            <select name="sec_title" class="soft-select"><option value="">—</option><option>Mr</option><option>Mrs</option><option>Miss</option><option>Dr.</option><option>Engr.</option><option>Chief</option></select>
          </div>
          <div><label class="subtle">Surname</label><input type="text" name="sec_surname" class="soft-input"/></div>
          <div><label class="subtle">First Name</label><input type="text" name="sec_firstname" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Other Names</label><input type="text" name="sec_middlename" class="soft-input"/></div>
          <div><label class="subtle">Sex</label><select name="sec_sex" class="soft-select"><option value="">—</option><option>Male</option><option>Female</option></select></div>
          <div><label class="subtle">Phone</label><input type="text" name="sec_phone" class="soft-input"/></div>
        </div>
        <div class="grid-3">
          <div><label class="subtle">Email</label><input type="email" name="sec_email" class="soft-input"/></div>
          <div><label class="subtle">Date of Birth</label><input type="date" name="sec_dob" class="soft-input"/></div>
          <div>
            <label class="subtle">NIN</label>
            <input type="text" name="sec_nin" inputmode="numeric" maxlength="11" pattern="\d{11}" placeholder="11-digit NIN" class="soft-input"/>
            <div class="hint">11 digits.</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Joint Owners -->
    <div id="jointBox" class="card" style="display:none">
      <div class="section-title"><span class="dot"></span> Joint Owners</div>

      <div class="soft-group" style="margin-bottom:8px">
        <label>Joint Name</label>
        <input type="text" name="joint_name" id="joint_name" class="soft-input" placeholder="e.g., John Doe & Jane Doe" />
      </div>

      <p class="hint">Add two or more individuals who jointly own this property. Each entry includes a passport, ID and NIN.</p>
      <div id="jointList" class="person-card" style="border-style:dashed"></div>
      <div class="actions" style="justify-content:flex-start">
        <button type="button" class="btn btn-sm btn-accent btn-icon" id="addIndividual">➕ Add Individual</button>
      </div>
    </div>

    <!-- Contact -->
    <div class="card">
      <div class="section-title"><span class="dot"></span> Contact Address</div>
      <div class="grid-3">
        <div><label class="subtle">Street</label><input type="text" name="street" class="soft-input"/></div>
        <div><label class="subtle">City</label><input type="text" name="city" class="soft-input"/></div>
        <div><label class="subtle">State</label><input type="text" name="state" class="soft-input"/></div>
      </div>
      <div class="grid-3" style="margin-top:10px">
        <div><label class="subtle">Country</label><input type="text" name="country" class="soft-input"/></div>
        <div><label class="subtle">Alt. Phone</label><input type="text" name="phone2" class="soft-input"/></div>
        <div><label class="subtle">Alt. Email</label><input type="email" name="email2" class="soft-input"/></div>
      </div>
    </div>

    <!-- Hidden fields populated from property selection -->
    <input type="hidden" name="propertyid" id="propertyid" />
    <input type="hidden" name="propertynumber" id="propertynumber" />
    <input type="hidden" name="plotDesc" id="plotDesc" />
    <input type="hidden" name="lgacode" id="lgacode" />
    <input type="hidden" name="link_submit" value="link_submit" />

    <div class="actions">
      <button type="reset" class="btn btn-ghost">Reset</button>
      <button type="submit" class="btn btn-accent btn-icon">✅ Submit</button>
    </div>
  </form>
</div>

<!-- Property Lookup Modal (non-dismissible until selection) -->
<div class="overlay" id="propOverlay" aria-modal="true" role="dialog">
  <div class="modal" role="document" id="propModal">
    <div class="modal-header"><div class="modal-title">🔎 Lookup Property</div></div>
    <div class="modal-body">
      <div class="searchbar">
        <input type="text" id="searchBox" placeholder="Search by Property Number (e.g., PRP1749950290)" />
        <button class="btn btn-accent btn-icon" id="btnSearch" type="button">Search</button>
      </div>
      <div class="result" id="resultBox"><div class="empty">Type a property number and click Search.</div></div>
      <div class="hint">Click a result row to select the property. The dialog will close and the form will be populated.</div>
    </div>
  </div>
</div>

<!-- Templates -->
<template id="tblTemplate">
  <table>
    <thead><tr><th style="width:30%">Property Number</th><th style="width:45%">Description</th><th style="width:25%">LGA</th></tr></thead>
    <tbody></tbody>
  </table>
</template>

<template id="jointPersonTemplate">
  <div class="person-card">
    <div class="person-head">
      <strong>Joint Individual <span class="idx"></span></strong>
      <div class="remove">Remove ✖</div>
    </div>

    <!-- Uploads row -->
    <div class="row-uploads">
      <div class="upload-field">
        <label>Upload Passport</label>
        <div class="passbox">
          <img src="" alt="Passport Preview" class="joint_pass_preview" style="display:none">
          <input type="file" name="joint[{{i}}][passport]" accept="image/*" onchange="previewSibling(this)">
        </div>
      </div>
      <div class="upload-field">
        <label>Upload ID</label>
        <div class="passbox">
          <img src="" alt="ID Preview" class="joint_id_preview" style="display:none">
          <input type="file" name="joint[{{i}}][idcard]" accept="image/*" onchange="previewSibling(this)">
        </div>
      </div>
    </div>

    <div class="grid-3" style="margin-top:6px">
      <div><label class="subtle">Title</label>
        <select name="joint[{{i}}][title]" class="soft-select">
          <option value="">—</option><option>Mr</option><option>Mrs</option><option>Miss</option><option>Dr.</option><option>Engr.</option><option>Chief</option>
        </select>
      </div>
      <div><label class="subtle">Surname</label><input type="text" name="joint[{{i}}][surname]" class="soft-input"/></div>
      <div><label class="subtle">First Name</label><input type="text" name="joint[{{i}}][firstname]" class="soft-input"/></div>
    </div>
    <div class="grid-3">
      <div><label class="subtle">Other Names</label><input type="text" name="joint[{{i}}][middlename]" class="soft-input"/></div>
      <div><label class="subtle">Sex</label><select name="joint[{{i}}][sex]" class="soft-select"><option value="">—</option><option>Male</option><option>Female</option></select></div>
      <div><label class="subtle">Phone</label><input type="text" name="joint[{{i}}][phone]" class="soft-input"/></div>
    </div>
    <div class="grid-3">
      <div><label class="subtle">Email</label><input type="email" name="joint[{{i}}][email]" class="soft-input"/></div>
      <div><label class="subtle">Date of Birth</label><input type="date" name="joint[{{i}}][dob]" class="soft-input"/></div>
      <div>
        <label class="subtle">NIN</label>
        <input type="text" name="joint[{{i}}][nin]" inputmode="numeric" maxlength="11" pattern="\d{11}" placeholder="11-digit NIN" class="soft-input"/>
        <div class="hint">11 digits.</div>
      </div>
    </div>
  </div>
</template>

<script>
  // Prevent dismiss (ESC / backdrop) until a row is picked
  (function(){
    const overlay = document.getElementById('propOverlay');
    overlay.addEventListener('click', (e)=>{ if (e.target === overlay){ e.stopPropagation(); } });
    window.addEventListener('keydown', (e)=>{ if (e.key === 'Escape') e.preventDefault(); });
  })();

  // DOM Ready
  document.addEventListener('DOMContentLoaded', () => {
    if (!document.getElementById('propertyid').value) {
      document.getElementById('propOverlay').style.display = 'flex';
      document.getElementById('searchBox').focus();
    }

    // Search handlers
    document.getElementById('btnSearch').addEventListener('click', doSearch);
    document.getElementById('searchBox').addEventListener('keydown', (e)=>{
      if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
    });

    // Ownership toggles
    const ownership = document.getElementById('ownershipType');
    const individualBox = document.getElementById('individualBox');
    const corporateBox  = document.getElementById('corporateBox');
    const jointBox      = document.getElementById('jointBox');
    const jointName     = document.getElementById('joint_name');

    function toggleRequired(el, on){ if(!el) return; on ? el.setAttribute('required','required') : el.removeAttribute('required'); }

    ownership.addEventListener('change', ()=>{
      const v = ownership.value;
      individualBox.style.display = (v==='individual') ? '' : 'none';
      corporateBox.style.display  = (v==='corporate') ? '' : 'none';
      jointBox.style.display      = (v==='joint')     ? '' : 'none';
      toggleRequired(jointName, v==='joint');
      if (v === 'joint' && document.getElementById('jointList').childElementCount === 0){
        addJointPerson(); addJointPerson();
      }
    });

    // Property type -> prefix
    const propertyType = document.getElementById('propertyType');
    const prefix = document.getElementById('Prefix');
    propertyType.addEventListener('change', ()=>{
      prefix.value = propertyType.value === 'private' ? 'PAL/' : (propertyType.value === 'govt' ? 'GAL/' : '');
    });

    // Form must have selected property
    document.getElementById('fileForm').addEventListener('submit', (e)=>{
      if (!document.getElementById('propertyid').value) {
        e.preventDefault();
        document.getElementById('propOverlay').style.display = 'flex';
        document.getElementById('searchBox').focus();
      }
    });

    // Add joint person
    document.getElementById('addIndividual').addEventListener('click', addJointPerson);
  });

  // SEARCH
  async function doSearch(){
    const input = document.getElementById('searchBox');
    const box = document.getElementById('resultBox');
    const btn = document.getElementById('btnSearch');
    const q = (input.value || '').trim();
    if (!q){ box.innerHTML = '<div class="empty">Please enter a property number.</div>'; input.focus(); return; }
    btn.disabled = true; const old = btn.textContent; btn.textContent = 'Searching…';
    box.innerHTML = '<div class="empty">Searching…</div>';
    try{
      const url = new URL(location.pathname, location.origin);
      url.searchParams.set('action','search_property');
      url.searchParams.set('q', q);
      const res = await fetch(url.toString(), {headers:{'Accept':'application/json'}});
      const data = await res.json();
      if (!data.ok) throw new Error('Search failed');
      const items = data.items || [];
      if (!items.length){ box.innerHTML = '<div class="empty">No results. Try a different number.</div>'; return; }
      const tpl = document.getElementById('tblTemplate').content.cloneNode(true);
      const tbody = tpl.querySelector('tbody');
      items.forEach(r=>{
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${escapeHtml(r.propertynumber||'')}</td>
                        <td>${escapeHtml(r.propertydesc||'')}</td>
                        <td>${escapeHtml(r.lgacode||'')}</td>`;
        tr.addEventListener('click', ()=> selectPropertyFromRow(r));
        tbody.appendChild(tr);
      });
      box.innerHTML = ''; box.appendChild(tpl);
    }catch(e){
      box.innerHTML = '<div class="empty">Error searching. Please try again.</div>';
    }finally{
      btn.disabled = false; btn.textContent = old;
    }
  }

  function escapeHtml(s){ return String(s).replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[m])); }

  function selectPropertyFromRow(r){
    document.getElementById('propertyid').value = r.propertyid || '';
    document.getElementById('propertynumber').value = r.propertynumber || '';
    document.getElementById('plotDesc').value = r.propertydesc || '';
    document.getElementById('lgacode').value = r.lgacode || '';
    document.getElementById('v_propertynumber').textContent = r.propertynumber || '';
    document.getElementById('v_propertydesc').textContent = r.propertydesc || '';
    document.getElementById('v_lga').textContent = r.lgacode || '';
    document.getElementById('propSummary').style.display = '';
    document.getElementById('propOverlay').style.display = 'none';
  }

  // Joint owners dynamic list (with passport + ID + NIN)
  let jointIndex = 0;
  function addJointPerson(){
    const raw = document.getElementById('jointPersonTemplate').innerHTML;
    const html = raw.replaceAll('{{i}}', String(jointIndex));
    const wrap = document.createElement('div'); wrap.innerHTML = html.trim();
    const card = wrap.firstElementChild;
    card.querySelector('.idx').textContent = (jointIndex + 1);
    card.querySelector('.remove').addEventListener('click', ()=>{ card.remove(); renumberJointCards(); });
    document.getElementById('jointList').appendChild(card);
    jointIndex++;
  }
  function renumberJointCards(){
    document.querySelectorAll('#jointList .person-card .idx').forEach((el,i)=> el.textContent = (i+1));
  }

  // Image preview (works for Passport and ID passboxes)
  function previewSibling(input){
    const img = input.closest('.passbox').querySelector('img');
    if (!input.files || !input.files[0]){ img.style.display='none'; img.src=''; return; }
    const r = new FileReader();
    r.onload = e => { img.src = e.target.result; img.style.display = 'block'; };
    r.readAsDataURL(input.files[0]);
  }
</script>
</body>
</html>
