<?php
/* =============================================================================
 * File: leave-request-od.php
 * - Central config include (no passwords here)
 * - Profile card (name • role • today • weekoff if available)
 * - Purpose = Client Meeting / Site Visit → merged dropdown (DST + Broker)
 *     * Label: DST-<name>-<j M> / Broker-<name>-<j M>
 *     * Stored lead_id (VARCHAR) = "DST_<id>" or "Broker_<id>"
 * - Purpose = Other → asks Type/Name/Number; lead_id=NULL
 * - Mobile-first UI, light theme by default, auto dark-mode
 * - Geolocation tip behavior preserved
 * ============================================================================= */

date_default_timezone_set('Asia/Kolkata');

/* ---------- Centralized config ---------- */
$config_path = __DIR__ . '/../../config.php';
if (!is_file($config_path)) { http_response_code(500); exit('Config file not found.'); }
require_once $config_path;

/* ---------- DB handles from config ---------- */
// ONB (leads, broker_leads)
$DB_ONB = isset($conn_onb) && $conn_onb instanceof mysqli ? $conn_onb :
          (isset($conn) && $conn instanceof mysqli ? $conn : null);
// HRD (hr_dump, tracker)
$DB_HRD = isset($conn_hrd) && $conn_hrd instanceof mysqli ? $conn_hrd :
          (isset($hrd) && $hrd instanceof mysqli ? $hrd : null);
// IC (emp_leave)
$DB_IC  = isset($conn_attendance_ic) && $conn_attendance_ic instanceof mysqli ? $conn_attendance_ic :
          (isset($conn_ic) && $conn_ic instanceof mysqli ? $conn_ic : null);

if (!($DB_ONB instanceof mysqli)) { http_response_code(500); exit('ONB DB connection missing.'); }
if (!($DB_HRD instanceof mysqli)) { http_response_code(500); exit('HRD DB connection missing.'); }
if (!($DB_IC  instanceof mysqli)) { http_response_code(500); exit('IC Attendance DB connection missing.'); }

/* ---------- Charset safety ---------- */
@mysqli_set_charset($DB_ONB, 'utf8mb4');
@mysqli_set_charset($DB_HRD, 'utf8mb4');
@mysqli_set_charset($DB_IC,  'utf8mb4');

/* ---------- Session ---------- */
@session_start();
if (!isset($_SESSION['user_id1'])) { header("Location: index.php"); exit; }
/* Keep session fresh */
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), $_COOKIE[session_name()], time() + 60*60*24*365, '/');
}

/* ---------- Helpers ---------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function col_exists($db, $table, $col){
    $t = mysqli_real_escape_string($db, $table);
    $c = mysqli_real_escape_string($db, $col);
    $res = @mysqli_query($db, "SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
    $ok = $res && mysqli_num_rows($res) > 0;
    if ($res) mysqli_free_result($res);
    return $ok;
}
function pick_first_col($db, $table, array $cands){ foreach($cands as $c){ if(col_exists($db,$table,$c)) return $c; } return null; }
function http_get_json($url){
    if(function_exists('curl_init')){
        $ch=curl_init();
        curl_setopt_array($ch,[
            CURLOPT_URL=>$url, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10,
            CURLOPT_SSL_VERIFYPEER=>true, CURLOPT_SSL_VERIFYHOST=>2,
            CURLOPT_USERAGENT=>'OD-Leave-Agent/1.0'
        ]);
        $resp=curl_exec($ch); $code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
        if($resp!==false && $code===200){ $data=json_decode($resp,true); if(json_last_error()===JSON_ERROR_NONE) return $data; }
    }
    if(ini_get('allow_url_fopen')){
        $ctx=stream_context_create(['http'=>['method'=>'GET','timeout'=>10,'header'=>"User-Agent: OD-Leave-Agent/1.0\r\n"]]);
        $resp=@file_get_contents($url,false,$ctx);
        if($resp!==false){ $data=json_decode($resp,true); if(json_last_error()===JSON_ERROR_NONE) return $data; }
    }
    return null;
}
function reverse_geocode_address($lat,$lng){
    if($lat===''||$lng===''||!is_numeric($lat)||!is_numeric($lng)) return '';
    $key = defined('GOOGLE_MAPS_API_KEY') ? (string)GOOGLE_MAPS_API_KEY : '';
    if($key!==''){
        $u='https://maps.googleapis.com/maps/api/geocode/json?latlng='.rawurlencode($lat.','.$lng).'&key='.rawurlencode($key);
        $d=http_get_json($u);
        if(is_array($d)&&($d['status']??'')==='OK'&&!empty($d['results'][0]['formatted_address'])){
            return substr((string)$d['results'][0]['formatted_address'],0,240);
        }
    }
    $u='https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat='.rawurlencode($lat).'&lon='.rawurlencode($lng).'&zoom=16&addressdetails=0';
    $d=http_get_json($u);
    if(is_array($d)&&!empty($d['display_name'])) return substr((string)$d['display_name'],0,240);
    return '';
}

/* ---------- Employee Profile (HRD) ---------- */
$userEmp = mysqli_real_escape_string($DB_HRD, (string)($_SESSION['user_id1'] ?? ''));
$sel1 = @mysqli_query($DB_HRD, "SELECT * FROM hr_dump WHERE empid='{$userEmp}' LIMIT 1");
$fetch1 = $sel1 ? (mysqli_fetch_array($sel1, MYSQLI_ASSOC) ?: []) : [];
$weekoff = trim((string)($fetch1['WeekOff'] ?? $fetch1['Weekoff'] ?? ''));
$empRole = trim((string)($fetch1['Role'] ?? $fetch1['Designation'] ?? ''));
$empName = trim((string)($fetch1['Employee_Full_Name'] ?? $fetch1['EmployeeName'] ?? 'User'));
$todayHuman = date('Y-m-d');

/* Also tracker (kept for compatibility with footer/includes) */
$empNum = (string)($fetch1['Employee_Number'] ?? '');
$qFR = @mysqli_query($DB_HRD, "SELECT * FROM tracker WHERE Functional_Reporting='" . mysqli_real_escape_string($DB_HRD, $empNum) . "' LIMIT 1");
$dataFR = $qFR ? (mysqli_fetch_array($qFR, MYSQLI_ASSOC) ?: []) : [];

/* ---------- Build merged dropdown (ONB) ---------- */
$prospectOptions = []; // ['type'=>'DST'|'BROKER','id'=>int,'label'=>string]

// LEADS (DST)
$leadsTbl = 'leads';
$leadIdCol   = col_exists($DB_ONB,$leadsTbl,'lead_id') ? 'lead_id' : (col_exists($DB_ONB,$leadsTbl,'id') ? 'id' : null);
$leadNameCol = pick_first_col($DB_ONB,$leadsTbl,['contact_name','customer_name','name','full_name','lead_name']);
$leadDateCol = pick_first_col($DB_ONB,$leadsTbl,['created_at','created_on','added_on','date_created','dt_created']);
if ($leadIdCol && $leadNameCol) {
    $cols = "`{$leadIdCol}` AS rec_id, TRIM(`{$leadNameCol}`) AS nm";
    $cols .= $leadDateCol ? ", `{$leadDateCol}` AS dt" : ", NULL AS dt";
    $sql = "SELECT {$cols} FROM `{$leadsTbl}` ORDER BY ".($leadDateCol?"`{$leadDateCol}` DESC":"`{$leadIdCol}` DESC")." LIMIT 500";
    if ($res=@mysqli_query($DB_ONB,$sql)) {
        while($r=mysqli_fetch_assoc($res)){
            $nm = trim((string)($r['nm'] ?? '')); if($nm==='') continue;
            $dt = !empty($r['dt']) ? date('j M', strtotime($r['dt'])) : date('j M');
            $prospectOptions[] = ['type'=>'DST','id'=>(int)$r['rec_id'],'label'=>"DST-{$nm}-{$dt}"];
        }
        mysqli_free_result($res);
    }
}
// BROKER_LEADS
$broTbl = 'broker_leads';
$broIdCol   = col_exists($DB_ONB,$broTbl,'broker_id') ? 'broker_id' : (col_exists($DB_ONB,$broTbl,'id') ? 'id' : null);
$broNameCol = pick_first_col($DB_ONB,$broTbl,['contact_name','broker_name','name','full_name']);
$broDateCol = pick_first_col($DB_ONB,$broTbl,['created_at','created_on','added_on','date_created','dt_created']);
if ($broIdCol && $broNameCol) {
    $cols = "`{$broIdCol}` AS rec_id, TRIM(`{$broNameCol}`) AS nm";
    $cols .= $broDateCol ? ", `{$broDateCol}` AS dt" : ", NULL AS dt";
    $sql = "SELECT {$cols} FROM `{$broTbl}` ORDER BY ".($broDateCol?"`{$broDateCol}` DESC":"`{$broIdCol}` DESC")." LIMIT 500";
    if ($res=@mysqli_query($DB_ONB,$sql)) {
        while($r=mysqli_fetch_assoc($res)){
            $nm = trim((string)($r['nm'] ?? '')); if($nm==='') continue;
            $dt = !empty($r['dt']) ? date('j M', strtotime($r['dt'])) : date('j M');
            $prospectOptions[] = ['type'=>'BROKER','id'=>(int)$r['rec_id'],'label'=>"Broker-{$nm}-{$dt}"];
        }
        mysqli_free_result($res);
    }
}
// unique
$seen=[]; $merged=[];
foreach($prospectOptions as $row){ $k=$row['type'].'|'.$row['id']; if(isset($seen[$k])) continue; $seen[$k]=1; $merged[]=$row; }
$prospectOptions = $merged;

/* ---------- Submit ---------- */
$errMsg = '';
if(isset($_POST['submit'])){
    $empid                 = trim((string)($_POST['empid'] ?? ''));
    $Employee_Full_Name    = trim((string)($_POST['Employee_Full_Name'] ?? ''));
    $Department            = trim((string)($_POST['Department'] ?? ''));
    $Team_Name             = trim((string)($_POST['Team_Name'] ?? ''));
    $Role                  = trim((string)($_POST['Role'] ?? ''));
    $LQTY                  = trim((string)($_POST['LQTY'] ?? '1'));
    $DateFrom              = trim((string)($_POST['DateFrom'] ?? ''));
    $Remarks               = trim((string)($_POST['Remarks'] ?? ''));
    $Functional_Reporting  = trim((string)($_POST['Functional_Reporting'] ?? ''));
    $Reporting_Head_Code   = trim((string)($_POST['Reporting_Head_Code'] ?? ''));
    $Team_Head_Code        = trim((string)($_POST['Team_Head_Code'] ?? ''));
    $Status                = trim((string)($_POST['Status'] ?? 'Pending'));
    $purpose               = trim((string)($_POST['purpose'] ?? ''));

    $lat        = isset($_POST['lat']) ? trim((string)$_POST['lat']) : '';
    $longt      = isset($_POST['longt']) ? trim((string)$_POST['longt']) : '';

    $prospect_select = trim((string)($_POST['prospect_select'] ?? '')); // "DST|123|Label" | "BROKER|45|Label" | "OTHER"
    $client_type     = trim((string)($_POST['client_type'] ?? ''));
    $client_name     = trim((string)($_POST['client_name'] ?? ''));
    $client_phone    = trim((string)($_POST['client_phone'] ?? ''));
    $other_detail    = trim((string)($_POST['other_detail'] ?? ''));

    $ProspectID = 'NA';
    $lead_id = null; // VARCHAR, format DST_2 or Broker_2

    if ($purpose === 'Client Meeting' || $purpose === 'Site Visit') {
        if ($prospect_select === '') {
            $errMsg = 'Please select a name or choose Other.';
        } elseif ($prospect_select === 'OTHER') {
            if ($client_type!=='DST' && $client_type!=='Broker') { $errMsg = 'Select Client Type (DST/Broker).'; }
            if ($client_name==='')  { $errMsg = 'Client Name is required.'; }
            if ($client_phone===''){ $errMsg = 'Client Number is required.'; }
            if ($errMsg==='') { $ProspectID = $client_type.'-'.$client_name.'-'.$client_phone; $lead_id = null; }
        } else {
            $parts = explode('|', $prospect_select, 3);
            $ptype = $parts[0] ?? '';     // DST or BROKER
            $pid   = isset($parts[1]) ? (int)$parts[1] : 0;
            $plab  = $parts[2] ?? '';
            if ($pid > 0 && ($ptype==='DST' || $ptype==='BROKER')) {
                $lead_id   = ($ptype==='DST' ? 'DST_' : 'Broker_') . $pid; // <- requested format
                $ProspectID= $plab !== '' ? $plab : ($ptype.'-#'.$pid);
            } else {
                $errMsg = 'Invalid selection.';
            }
        }
    } elseif ($purpose === 'Other') {
        if($other_detail === ''){ $errMsg = 'Please describe the purpose.'; }
        $ProspectID = $other_detail;
        $lead_id = null;
    } else {
        $errMsg = 'Please select a purpose.';
    }

    if($lat === '' || $longt === '' || !is_numeric($lat) || !is_numeric($longt)){
        $errMsg = 'Location is required. Allow location for this site, then refresh the page.';
    }

    $LeaveCategory = 'OD';
    $LeaveType     = $LQTY . '-' . $LeaveCategory;

    $LocationAddress = '';
    if($errMsg === ''){
        $LocationAddress = reverse_geocode_address($lat, $longt);
        if($LocationAddress === '') $LocationAddress = 'NO-LOCATION: ADDR-NOT-FOUND';
    }

    if($errMsg === ''){
        // Ensure emp_leave.lead_id is VARCHAR(32) NULL
        $sql = "INSERT INTO emp_leave
                (empid, Employee_Full_Name, Department, Team_Name, LeaveCategory, ProspectID, lead_id,
                 lat, longt, LocationAddress, LeaveType, LQTY, DateFrom, Remarks,
                 Functional_Reporting, Reporting_Head_Code, Team_Head_Code, Status)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt = mysqli_prepare($DB_IC, $sql);
        if(!$stmt){
            $errMsg = 'Error preparing statement: ' . mysqli_error($DB_IC);
        } else {
            mysqli_stmt_bind_param(
                $stmt,
                "sssssss"."sssssssssss", // 7s + 10s = 17 params (lead_id is s and may be NULL)
                $empid, $Employee_Full_Name, $Department, $Team_Name, $LeaveCategory, $ProspectID, $lead_id,
                $lat, $longt, $LocationAddress, $LeaveType, $LQTY, $DateFrom, $Remarks,
                $Functional_Reporting, $Reporting_Head_Code, $Team_Head_Code, $Status
            );
            if(!mysqli_stmt_execute($stmt)){ $errMsg = 'Error executing statement: ' . mysqli_stmt_error($stmt); }
            mysqli_stmt_close($stmt);
        }
    }

    if($errMsg === ''){
        echo "<script>location.href='leave-view-current.php';</script>";
        exit;
    } else {
        echo "<script>alert(".json_encode($errMsg, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP).");</script>";
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>OD Leave Request</title>

<!-- Modern, mobile-first, light/dark theme -->
<style>
:root{
  --bg:#f7f9fc; --card:#ffffff; --text:#0f172a; --muted:#64748b;
  --brand:#1a73e8; --brand2:#2dd4bf; --danger:#ef4444; --ok:#16a34a;
  --line:rgba(2,6,23,.08); --field:#f1f5f9; --field-b:#e2e8f0;
}
@media (prefers-color-scheme: dark){
  :root{
    --bg:#0b1020; --card:#111827; --text:#e5e7eb; --muted:#94a3b8;
    --brand:#60a5fa; --brand2:#34d399; --danger:#f87171; --ok:#4ade80;
    --line:rgba(255,255,255,.08); --field:#0f172a; --field-b:#223045;
  }
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.4 system-ui,-apple-system,Segoe UI,Roboto,Inter,Arial}
.container{padding:14px 12px;max-width:820px;margin:0 auto}
.card{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:14px;box-shadow:0 10px 28px rgba(2,6,23,.05)}
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.brand{font-weight:900;letter-spacing:.3px}
.badge{padding:6px 10px;border-radius:999px;background:linear-gradient(135deg,var(--brand),var(--brand2));color:#fff;font-weight:800;font-size:11px;border:0}
.profile{display:flex;align-items:center;gap:12px;background:linear-gradient(180deg,rgba(26,115,232,.06),rgba(45,212,191,.06));border:1px solid var(--line);border-radius:16px;padding:10px 12px;margin-bottom:12px}
.avatar{width:44px;height:44px;border-radius:12px;background:var(--field);display:flex;align-items:center;justify-content:center;font-weight:900}
.p-name{font-weight:800}
.p-meta{font-size:12px;color:var(--muted)}
.row{display:grid;grid-template-columns:1fr;gap:12px}
@media (min-width:560px){ .row.split{grid-template-columns:1fr 1fr} }
label{font-weight:700;font-size:12px;margin:6px 2px;display:block;color:var(--muted)}
input,select{width:100%;padding:12px;border-radius:12px;border:1px solid var(--field-b);background:var(--field);color:var(--text);outline:none}
input::placeholder{color:var(--muted)}
/* Date input cosmetics */
input[type="date"]{appearance:none;-webkit-appearance:none;background:var(--field)}
/* Searchable select block */
.select-wrap{border:1px solid var(--field-b);background:var(--field);border-radius:12px;padding:6px}
.select-wrap input[type="search"]{width:100%;border:0;background:transparent;padding:8px 8px 6px 8px;}
.select-wrap select{width:100%;border:0;background:transparent;padding:6px 8px 10px 8px}
.select-wrap .hint{font-size:11px;color:var(--muted);padding:0 8px 6px}
.btn{width:100%;padding:12px;border-radius:14px;border:0;background:linear-gradient(135deg,var(--brand),var(--brand2));color:#fff;font-weight:900;box-shadow:0 8px 24px rgba(26,115,232,.22)}
.btn[disabled]{opacity:.6;filter:grayscale(.2)}
.small{font-size:12px;color:var(--muted)}
.tip{display:none;gap:8px;align-items:center;background:#fff3cd;border:1px solid #facc15;color:#7a5c00;border-radius:12px;padding:8px 10px;margin-top:6px}
hr{border:0;border-top:1px dashed var(--line);margin:10px 0}
</style>

<?php /* If you have a site-wide header include, keep it here: */ ?>
<?php // include('header.php'); ?>
</head>
<body>
<div class="container">
  <div class="card">

    <!-- Profile Card -->
    <div class="profile">
      <div class="avatar"><?php echo strtoupper(substr($empName,0,1)); ?></div>
      <div>
        <div class="p-name"><?php echo h($empName); ?></div>
        <div class="p-meta">
          <?php echo h($empRole ?: 'Employee'); ?> • <?php echo h($todayHuman); ?>
          <?php if($weekoff!==''){ echo ' • Weekoff - '.h($weekoff); } ?>
        </div>
      </div>
      <div style="margin-left:auto"><span class="badge">AMS</span></div>
    </div>

    <div class="header">
      <div class="brand">Apply OD</div>
      <span class="small">Apply OD within three days</span>
    </div>

    <form id="leavereq" action="" method="post" autocomplete="off">
      <input type="hidden" name="empid" value="<?php echo h($fetch1['empid'] ?? ''); ?>" />
      <input type="hidden" name="Employee_Full_Name" value="<?php echo h($fetch1['Employee_Full_Name'] ?? ''); ?>">
      <input type="hidden" name="Department" value="<?php echo h($fetch1['Department'] ?? ''); ?>">
      <input type="hidden" name="Team_Name" value="<?php echo h($fetch1['Team_Name'] ?? ''); ?>">
      <input type="hidden" name="Role" value="<?php echo h($fetch1['Role'] ?? ''); ?>">
      <input type="hidden" name="LeaveCategory" value="OD">

      <?php
        $datelast = date('Y-m-d', strtotime('-1 day'));
        $doj = $fetch1['Date_of_Joining'] ?? $datelast;
        $datemin = ($datelast >= $doj) ? $datelast : $doj;
      ?>

      <div class="row split">
        <div>
          <label>Day Type *</label>
          <select name="LQTY" required>
            <option value="0.5">Half Day</option>
            <option value="1">Full Day</option>
          </select>
        </div>
        <div>
          <label>Date For *</label>
          <input type="date" name="DateFrom" min="<?php echo h($datemin); ?>" max="<?php echo date('Y-m-d'); ?>" required>
        </div>
      </div>

      <div class="row">
        <div>
          <label>Purpose of OD *</label>
          <select name="purpose" id="purpose" required>
            <option value="" selected disabled>Select purpose</option>
            <option>Client Meeting</option>
            <option>Site Visit</option>
            <option>Other</option>
          </select>
        </div>
      </div>

      <!-- Dynamic area -->
      <div class="row" id="purposeFields" style="display:none;"></div>

      <input type="hidden" name="lat" id="lat">
      <input type="hidden" name="longt" id="longt">

      <div class="small" id="locStatusText">Checking location permission…</div>
      <div class="tip" id="helpBlock">
        Tip: If you don’t see a popup, tap the <b>lock/location</b> icon near the URL → set <b>Location: Allow</b>, then refresh.
      </div>

      <div class="row">
        <div>
          <label>Remarks *</label>
          <input type="text" name="Remarks" maxlength="120" required placeholder="Add a short note (e.g., Meeting at client office)">
        </div>
      </div>

      <!-- Hidden mappings -->
      <input type="hidden" name="Functional_Reporting" value="<?php echo h($fetch1['Functional_Reporting'] ?? ''); ?>">
      <input type="hidden" name="Reporting_Head_Code" value="<?php echo h($fetch1['Reporting_Head_Code'] ?? ''); ?>">
      <input type="hidden" name="Team_Head_Code" value="<?php echo h($fetch1['Team_Head_Code'] ?? ''); ?>">
      <input type="hidden" name="Status" value="Pending">

      <div style="margin-top:6px">
        <button type="submit" name="submit" id="saveBtn" class="btn" disabled>Save</button>
        <div class="small" id="saveHint">Location required to save.</div>
      </div>
    </form>
  </div>
</div>

<?php // include('footer.php'); ?>

<script>
/* Prospect list → JS */
window.__PROSPECT_LIST__ = <?php echo json_encode($prospectOptions, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); ?>;

(function(){
  const purpose   = document.getElementById('purpose');
  const pBox      = document.getElementById('purposeFields');
  const latEl     = document.getElementById('lat');
  const lngEl     = document.getElementById('longt');
  const statusTxt = document.getElementById('locStatusText');
  const saveBtn   = document.getElementById('saveBtn');
  const saveHint  = document.getElementById('saveHint');
  const helpBlock = document.getElementById('helpBlock');

  function setSaveEnabled(ok, hint){
    if(saveBtn) saveBtn.disabled = !ok;
    if(saveHint) saveHint.textContent = hint || (ok ? 'Ready to save.' : 'Location required to save.');
  }
  function esc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

  // Searchable select (input + select in one block)
  function renderProspectChooser(){
    const list = Array.isArray(window.__PROSPECT_LIST__) ? window.__PROSPECT_LIST__ : [];
    const opts = ['<option value="" selected disabled>Select Name (DST/Broker)</option>']
      .concat(list.map(row => {
        const val = `${row.type}|${row.id}|${row.label}`;
        return `<option value="${esc(val)}" data-type="${esc(row.type)}" data-id="${esc(row.id)}">${esc(row.label)}</option>`;
      }))
      .concat(['<option value="OTHER">Other (Enter manually)</option>'])
      .join('');
    return `
      <div>
        <label>Select Prospect *</label>
        <div class="select-wrap">
          <input type="search" id="prospect_search" placeholder="Search name or label…">
          <div class="hint">Type to filter, then select below</div>
          <select name="prospect_select" id="prospect_select" required>
            ${opts}
          </select>
        </div>
      </div>
      <div id="otherFields" style="display:none;">
        <div class="row">
          <div>
            <label>Client Type *</label>
            <select name="client_type" id="client_type">
              <option value="" selected disabled>Select</option>
              <option value="DST">DST</option>
              <option value="Broker">Broker</option>
            </select>
          </div>
          <div>
            <label>Client Name *</label>
            <input name="client_name" id="client_name" maxlength="80" />
          </div>
          <div>
            <label>Client Number *</label>
            <input name="client_phone" id="client_phone" pattern="^[0-9+\\-\\s]{7,13}$" placeholder="+91XXXXXXXXXX" />
          </div>
        </div>
      </div>
    `;
  }

  function renderPurposeFields(){
    const v = purpose.value || '';
    if(!v){ pBox.style.display='none'; pBox.innerHTML=''; return; }
    pBox.style.display='block';

    if(v === 'Client Meeting' || v === 'Site Visit'){
      pBox.innerHTML = renderProspectChooser();

      // search & filter
      const search = document.getElementById('prospect_search');
      const select = document.getElementById('prospect_select');
      const other  = document.getElementById('otherFields');

      function filterOptions(){
        const q = (search.value || '').toLowerCase().trim();
        for (const opt of select.options) {
          if (!opt.value || opt.value === 'OTHER') { opt.hidden = false; continue; }
          const txt = opt.textContent.toLowerCase();
          opt.hidden = q && !txt.includes(q);
        }
      }
      search.addEventListener('input', filterOptions);
      filterOptions();

      select.addEventListener('change', function(){
        if (select.value === 'OTHER') {
          other.style.display = 'block';
          document.getElementById('client_type')?.setAttribute('required','required');
          document.getElementById('client_name')?.setAttribute('required','required');
          document.getElementById('client_phone')?.setAttribute('required','required');
        } else {
          other.style.display = 'none';
          document.getElementById('client_type')?.removeAttribute('required');
          document.getElementById('client_name')?.removeAttribute('required');
          document.getElementById('client_phone')?.removeAttribute('required');
        }
      });

    } else if(v === 'Other'){
      pBox.innerHTML = '<div><label>Describe Purpose *</label><input name="other_detail" id="other_detail" required maxlength="80"></div>';
    } else {
      pBox.innerHTML = '';
    }
  }

  function hideTip(){ helpBlock && (helpBlock.style.display='none'); }
  function showTip(){ helpBlock && (helpBlock.style.display='flex'); }

  function markOk(lat, lng){
    document.getElementById('lat').value = lat;
    document.getElementById('longt').value = lng;
    statusTxt && (statusTxt.textContent = 'Location captured.');
    hideTip();
    setSaveEnabled(true, 'Location captured. You can Save.');
  }
  function markTemp(text){
    statusTxt && (statusTxt.textContent = text || 'Requesting location…');
    hideTip();
    setSaveEnabled(false, 'Location required to save.');
  }
  function markBlocked(){
    statusTxt && (statusTxt.textContent = 'Location blocked. Allow it via site settings, then refresh.');
    showTip();
    setSaveEnabled(false, 'Location required to save.');
  }

  function getCurrentPositionAttempt(){
    navigator.geolocation.getCurrentPosition(
      pos => {
        const c = pos.coords || {};
        if(typeof c.latitude !== 'undefined' && typeof c.longitude !== 'undefined'){
          markOk(String(c.latitude), String(c.longitude));
        } else {
          markTemp('Location unavailable. Move to an open area and try again.');
        }
      },
      err => {
        if(!err || typeof err.code === 'undefined'){ markTemp('Could not access location.'); return; }
        if(err.code === 1)      { markBlocked(); }
        else if(err.code === 2) { markTemp('Location unavailable. Try again in an open area.'); }
        else if(err.code === 3) { markTemp('Location timed out. Try again in an open area.'); }
        else                    { markTemp('Could not access location.'); }
      },
      { enableHighAccuracy:true, timeout:10000, maximumAge:0 }
    );
  }

  async function checkPermission(){
    setSaveEnabled(false);
    hideTip();
    if(!navigator.geolocation){ markTemp('Geolocation not supported on this device.'); return; }
    if(navigator.permissions && navigator.permissions.query){
      try{
        const p = await navigator.permissions.query({name:'geolocation'});
        if(p.state==='granted'){ statusTxt&&(statusTxt.textContent='Capturing location…'); getCurrentPositionAttempt(); }
        else if(p.state==='prompt'){ statusTxt&&(statusTxt.textContent='Requesting location…'); getCurrentPositionAttempt(); }
        else { markBlocked(); }
        try{ p.onchange = () => { location.reload(); }; } catch(e){}
        return;
      }catch(e){}
    }
    statusTxt&&(statusTxt.textContent='Requesting location…');
    getCurrentPositionAttempt();
  }

  purpose && purpose.addEventListener('change', renderPurposeFields);
  renderPurposeFields();
  checkPermission();
})();
</script>
</body>
</html>
