<?php
/* =============================================================================
 * File   : /brocrm/mobile/dst_crm_edit.php
 * Goal   : EDIT a single DST Lead (claimed)
 * Access : Employee (role_id=4/role_name='employee') or admin/superadmin
 * DB     : Core PHP + MySQLi (NO PDO). COLLATE=utf8mb4_general_ci
 * Tables : broriserin_onb.leads (read/update)
 *          projects are discovered dynamically (any schema that has `projects`)
 * Theme  : Base template (same as dst.php & dst_crm_view.php)
 * Rules  : 1) Full code from first to last line  2) Has file name
 *          3) DB connection only via config.php  4) utf8mb4_general_ci  5) no PDO
 * ============================================================================= */

if (session_status() === PHP_SESSION_NONE) { session_start(); }
date_default_timezone_set('Asia/Kolkata');

/* ------------------------- Centralized config ------------------------- */
$cfgs = [
  __DIR__ . '/config.php',
  __DIR__ . '/../config.php',
  __DIR__ . '/../../config.php'
];
$cfgFound = false;
foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; $cfgFound = true; break; } }
if (!$cfgFound) { http_response_code(500); exit('config.php not found'); }

/* ------------------------- Resolve ONB connection --------------------- */
$DB = null; // ONB for leads
if (isset($conn) && $conn instanceof mysqli)                    { $DB = $conn; }
elseif (isset($conn_crm) && $conn_crm instanceof mysqli)         { $DB = $conn_crm; }
elseif (isset($conn_crmplus) && $conn_crmplus instanceof mysqli) { $DB = $conn_crmplus; }
elseif (isset($conn_sa) && $conn_sa instanceof mysqli)           { $DB = $conn_sa; }
if (!($DB instanceof mysqli)) { http_response_code(500); exit('DB connection missing.'); }

/* charset/collation (utf8mb4_general_ci) + ensure ONB schema */
@mysqli_query($DB, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_set_charset($DB, 'utf8mb4');
@mysqli_query($DB, "SET collation_connection='utf8mb4_general_ci'");
@mysqli_query($DB, "USE `broriserin_onb`"); // leads live here

/* --------------------------------- Helpers -------------------------------- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
function q_one($db,$sql){ $rs=@mysqli_query($db,$sql); if($rs && ($r=mysqli_fetch_assoc($rs))){ @mysqli_free_result($rs); return $r; } return null; }
function q_all($db,$sql){ $o=[]; if($rs=@mysqli_query($db,$sql)){ while($r=mysqli_fetch_assoc($rs)) $o[]=$r; @mysqli_free_result($rs);} return $o; }
function col_exists($db,$t,$c){
  $t=mysqli_real_escape_string($db,$t); $c=mysqli_real_escape_string($db,$c);
  $rs=@mysqli_query($db,"SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
  $ok=$rs && mysqli_num_rows($rs)>0; if($rs) @mysqli_free_result($rs); return $ok;
}

/* --------------------------- Current user/session --------------------------- */
$ME        = $_SESSION['auth'] ?? [];
$ROLE_ID   = isset($ME['role_id']) ? (int)$ME['role_id'] : 0;
$ROLE_NAME = strtolower($ME['role_name'] ?? 'user');
$ME_ID     = (int)($ME['id'] ?? 0);
$ME_MAIL   = trim((string)($ME['email'] ?? ''));
$ME_EMPID  = trim((string)($ME['empid'] ?? ''));
$ME_NAME   = trim((string)($ME['name'] ?? ($ME['full_name'] ?? ($ME['first_name'] ?? ''))));

/* --------------------- ACCESS CONTROL (same pattern as dst.php) ------------- */
$is_employee = ($ROLE_ID === 4) || ($ROLE_NAME === 'employee');
$is_admin    = in_array($ROLE_NAME, ['superadmin','admin'], true);
if (!$is_employee && !$is_admin) {
  header("Location: /brocrm/login.php?tab=employee&err=only-employee");
  exit;
}

/* ----- Input ----- */
$id = (int)($_GET['id'] ?? 0);
if ($id<=0) { http_response_code(400); exit('Missing id'); }

/* ------ Resolve EMPID from superadmin if missing in session (failsafe) ------ */
if ($ME_EMPID === '') {
  $cond = '';
  if ($ME_ID)            $cond = "id=".(int)$ME_ID;
  elseif ($ME_MAIL!=='') $cond = "email='".mysqli_real_escape_string($DB,$ME_MAIL)."'";
  if ($cond) {
    $u = q_one($DB, "SELECT empid FROM broriser_superadmin.users WHERE {$cond} LIMIT 1");
    if (!empty($u['empid'])) {
      $ME_EMPID = trim($u['empid']);
      $_SESSION['auth']['empid'] = $ME_EMPID;
      $_SESSION['user_id1']      = $ME_EMPID; // legacy key
    }
  }
}

/* ---------------- Visibility by assigned_user + empid ----------------------- */
$checks=[];
if (col_exists($DB,'leads','assigned_user')) {
  $cands = array_values(array_unique(array_filter([$ME_MAIL,$ME_NAME],'strlen')));
  if ($cands) {
    $esc = array_map(fn($v)=>"'".mysqli_real_escape_string($DB,$v)."'", $cands);
    $checks[] = "assigned_user IN (".implode(',', $esc).")";
  }
}
foreach(['empid','employee_id','emp_id'] as $c){
  if ($ME_EMPID!=='' && col_exists($DB,'leads',$c)) { $checks[] = "`{$c}`='".mysqli_real_escape_string($DB,$ME_EMPID)."'"; break; }
}
$vis = $is_admin ? '1=1' : ($checks ? '('.implode(' OR ',$checks).')' : '0');

/* ---------------- Load lead (enforce visibility) ---------------------------- */
$lead = q_one($DB,"SELECT * FROM `leads` WHERE id={$id} AND {$vis} LIMIT 1");
if (!$lead) { http_response_code(404); exit('Lead not found or not visible.'); }

/* ----- Current values ----- */
$name      = $lead['contact_name'] ?? ($lead['customer_name'] ?? ($lead['name'] ?? ''));
$tags      = trim((string)($lead['tags'] ?? '')); // My Status
$pp_raw    = $lead['pp_status'] ?? ($lead['pipeline_stage'] ?? ($lead['stage'] ?? ''));
$source    = $lead['lead_source'] ?? ($lead['source'] ?? '');
$project   = $lead['project'] ?? ($lead['title'] ?? '');
$projectId = isset($lead['project_id']) ? (int)$lead['project_id'] : 0;
$comment   = $lead['remarks'] ?? ($lead['note'] ?? ($lead['comment'] ?? ''));

/* optional columns */
$has_pp      = col_exists($DB,'leads','pp_status');
$has_pipe    = col_exists($DB,'leads','pipeline_stage');
$has_amount1 = col_exists($DB,'leads','opp_amount');
$has_amount2 = col_exists($DB,'leads','deal_value');
$has_prob1   = col_exists($DB,'leads','probability');
$has_prob2   = col_exists($DB,'leads','opp_probability');
$has_closed1 = col_exists($DB,'leads','closed_date');
$has_closed2 = col_exists($DB,'leads','closed_on');
$has_proj_id = col_exists($DB,'leads','project_id');

/* Display rule: New→Prospecting only when My Status=Prospect */
$opp_display = (strcasecmp($tags,'Prospect')===0 && (strcasecmp($pp_raw,'New')===0 || $pp_raw==='')) ? 'Prospecting' : $pp_raw;

/* Amount/Probability/Closed fetched if columns exist */
$amount = null;
if ($has_amount1)      $amount = $lead['opp_amount'];
elseif ($has_amount2)  $amount = $lead['deal_value'];

$prob = null;
if ($has_prob1)        $prob = $lead['probability'];
elseif ($has_prob2)    $prob = $lead['opp_probability'];

$closed_dt = null;
if ($has_closed1)      $closed_dt = $lead['closed_date'];
elseif ($has_closed2)  $closed_dt = $lead['closed_on'];

/* ---------------------------------------------------------------------------
 * PROJECTS DROPDOWN — robust discovery
 * 1) Try preferred schemas (wider net)
 * 2) If not found, scan information_schema for any schema having `projects`
 * 3) Fallback: DISTINCT project names from leads/title if still nothing
 * ------------------------------------------------------------------------- */
$projects = [];            // array of ['id'=>int, 'pname'=>string]
$projects_error = '';      // diagnostic string (shown small under dropdown)
$PROJ_DB = null;           // mysqli link to use for projects SELECT
$PROJ_SCHEMA = null;       // chosen schema name for projects table
$PROJ_HAS_ID = true;       // assume `id` exists
$PROJ_DISP_COLS = [];      // display column candidates (name/title/slug/etc.)

/* Choose a mysqli handle to run discovery against (any working link) */
function first_link_for_scan() {
  foreach (['conn_crmplus','conn','conn_sa','conn_crm'] as $v) {
    if (isset($GLOBALS[$v]) && $GLOBALS[$v] instanceof mysqli) return $GLOBALS[$v];
  }
  return null;
}

/* Try a wider preferred list explicitly (many installs use these prefixes) */
function try_preferred_schemas(&$link,&$schema,&$err) {
  $err = '';
  $cands = [];
  if (isset($GLOBALS['conn_crmplus']) && $GLOBALS['conn_crmplus'] instanceof mysqli) {
    $cands[] = [$GLOBALS['conn_crmplus'], 'broriserin_brorisercom'];
    $cands[] = [$GLOBALS['conn_crmplus'], 'broriser_brorisercom'];
  }
  if (isset($GLOBALS['conn']) && $GLOBALS['conn'] instanceof mysqli) {
    $cands[] = [$GLOBALS['conn'], 'broriserin_broriserin'];
    $cands[] = [$GLOBALS['conn'], 'broriserin_onb'];
    $cands[] = [$GLOBALS['conn'], 'broriser_onb'];
  }
  if (isset($GLOBALS['conn_sa']) && $GLOBALS['conn_sa'] instanceof mysqli) {
    $cands[] = [$GLOBALS['conn_sa'], 'broriserin_superadmin'];
    $cands[] = [$GLOBALS['conn_sa'], 'broriser_superadmin'];
  }
  foreach ($cands as [$lnk,$sch]) {
    $rs = @mysqli_query($lnk, "SELECT 1 FROM `{$sch}`.`projects` LIMIT 1");
    if ($rs !== false) { if($rs) @mysqli_free_result($rs); $link=$lnk; $schema=$sch; return true; }
    $err = mysqli_error($lnk);
  }
  return false;
}

/* Scan information_schema as a generic fallback */
function scan_information_schema_for_projects(&$link,&$schema,&$err){
  $err = '';
  $lnk = first_link_for_scan();
  if (!($lnk instanceof mysqli)) { $err='No link to scan'; return false; }
  $sql = "SELECT table_schema
          FROM information_schema.tables
          WHERE table_name='projects'
            AND table_schema NOT IN ('information_schema','mysql','performance_schema','sys')
          ORDER BY (CASE WHEN table_schema LIKE 'broriser%' OR table_schema LIKE 'broriserin%' THEN 0 ELSE 1 END),
                   table_schema
          LIMIT 1";
  $row = q_one($lnk,$sql);
  if ($row && !empty($row['table_schema'])) { $link=$lnk; $schema=$row['table_schema']; return true; }
  $err = mysqli_error($lnk);
  return false;
}

/* Decide chosen schema */
$pick_err = '';
if (try_preferred_schemas($PROJ_DB,$PROJ_SCHEMA,$pick_err) === false) {
  if (scan_information_schema_for_projects($PROJ_DB,$PROJ_SCHEMA,$pick_err) === false) {
    $projects_error = "Could not find a `projects` table (tried known schemas & info_schema). MySQL: ".h($pick_err);
    $PROJ_DB = null; $PROJ_SCHEMA = null;
  }
}

/* If a schema is chosen, fetch projects */
if ($PROJ_DB && $PROJ_SCHEMA) {
  // detect display columns safely
  $dispCandidates = ['project_name','title','name','project_title','slug'];
  $cols = [];
  foreach ($dispCandidates as $dc) {
    $rs = @mysqli_query($PROJ_DB,"SHOW COLUMNS FROM `{$PROJ_SCHEMA}`.`projects` LIKE '".mysqli_real_escape_string($PROJ_DB,$dc)."'");
    if ($rs && mysqli_num_rows($rs)>0) { $cols[] = $dc; }
    if ($rs) @mysqli_free_result($rs);
  }
  if (!$cols) { $cols = ['id']; } // fallback

  $coalesceParts = [];
  foreach ($cols as $c) { if ($c!=='id') $coalesceParts[] = "NULLIF(TRIM(`{$c}`),'')"; }
  $dispExpr = $coalesceParts ? ("COALESCE(".implode(',',$coalesceParts).", CONCAT('Project #',id))")
                             : "CONCAT('Project #',id)";

  // try to skip archived/blocked if project_tag exists
  $has_tag = q_one($PROJ_DB,"SHOW COLUMNS FROM `{$PROJ_SCHEMA}`.`projects` LIKE 'project_tag'") ? true : false;
  $where   = $has_tag ? "WHERE (project_tag IS NULL OR project_tag NOT LIKE '%Archived%')" : "";

  $sql = "SELECT id, {$dispExpr} AS pname
          FROM `{$PROJ_SCHEMA}`.`projects`
          {$where}
          ORDER BY id DESC
          LIMIT 1000";
  $rows = q_all($PROJ_DB,$sql);
  if (is_array($rows) && count($rows)) { $projects = $rows; }
  else {
    $projects_error = "No rows in {$PROJ_SCHEMA}.projects. MySQL: ".h(mysqli_error($PROJ_DB));
  }
}

/* FINAL FALLBACK: if still empty, pull distinct names from leads/title */
if (!count($projects)) {
  $alts = [];
  if (col_exists($DB,'leads','project')) {
    $alts = q_all($DB,"SELECT NULLIF(TRIM(project),'') AS pname FROM `leads` WHERE TRIM(project)<>'' GROUP BY pname ORDER BY MAX(id) DESC LIMIT 200");
  } elseif (col_exists($DB,'leads','title')) {
    $alts = q_all($DB,"SELECT NULLIF(TRIM(title),'') AS pname FROM `leads` WHERE TRIM(title)<>'' GROUP BY pname ORDER BY MAX(id) DESC LIMIT 200");
  }
  foreach ($alts as $r) {
    if (!empty($r['pname'])) $projects[] = ['id'=>0, 'pname'=>$r['pname']];
  }
  if (!count($projects) && $projects_error==='') {
    $projects_error = "No projects found (neither `projects` table nor prior lead projects).";
  }
}

/* -------------------------- POST save (enforce vis) ------------------------- */
$err = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $tags_in = trim((string)($_POST['tags'] ?? ''));
  $opp_in  = trim((string)($_POST['opp_status'] ?? ''));
  $src_in  = trim((string)($_POST['lead_source'] ?? ''));
  $proj_in = trim((string)($_POST['project'] ?? ''));
  $proj_id_in = (int)($_POST['project_id'] ?? 0);
  $cmt_in  = trim((string)($_POST['comment'] ?? ''));

  $amount_in = trim((string)($_POST['amount'] ?? ''));
  $prob_in   = trim((string)($_POST['prob'] ?? ''));
  $closed_in = trim((string)($_POST['closed_date'] ?? ''));

  // store New internally if Prospect+Prospecting
  $opp_to_store = $opp_in;
  if (strcasecmp($tags_in,'Prospect')===0 && strcasecmp($opp_in,'Prospecting')===0) {
    $opp_to_store = 'New';
  }

  // auto closed date if closed status chosen
  $is_closing = in_array(strtolower($opp_in), ['closed won','closed lost'], true);
  if ($is_closing && $closed_in==='') { $closed_in = date('Y-m-d H:i:s'); }

  $sets=[];
  if (col_exists($DB,'leads','tags'))            $sets[]="`tags`='".mysqli_real_escape_string($DB,$tags_in)."'";
  if     ($has_pp)    $sets[]="`pp_status`='".mysqli_real_escape_string($DB,$opp_to_store)."'";
  elseif ($has_pipe)  $sets[]="`pipeline_stage`='".mysqli_real_escape_string($DB,$opp_to_store)."'";
  if (col_exists($DB,'leads','lead_source'))     $sets[]="`lead_source`='".mysqli_real_escape_string($DB,$src_in)."'";

  // prefer numeric project_id if column exists and we have a valid numeric ID from dropdown
  if ($has_proj_id) {
    $sets[]="`project_id`=".(int)$proj_id_in;
    // also write human name into `project` or `title` if present
    if (col_exists($DB,'leads','project')) {
      $sets[]="`project`='".mysqli_real_escape_string($DB,$proj_in)."'";
    } elseif (col_exists($DB,'leads','title')) {
      $sets[]="`title`='".mysqli_real_escape_string($DB,$proj_in)."'";
    }
  } else {
    // legacy: store just the name
    if (col_exists($DB,'leads','project'))         $sets[]="`project`='".mysqli_real_escape_string($DB,$proj_in)."'";
    elseif (col_exists($DB,'leads','title'))       $sets[]="`title`='".mysqli_real_escape_string($DB,$proj_in)."'";
  }

  if (col_exists($DB,'leads','remarks'))         $sets[]="`remarks`='".mysqli_real_escape_string($DB,$cmt_in)."'";
  elseif (col_exists($DB,'leads','note'))        $sets[]="`note`='".mysqli_real_escape_string($DB,$cmt_in)."'";
  elseif (col_exists($DB,'leads','comment'))     $sets[]="`comment`='".mysqli_real_escape_string($DB,$cmt_in)."'";

  if ($amount_in !== '') {
    $val = is_numeric($amount_in) ? (float)$amount_in : 0;
    if ($has_amount1)      $sets[]="`opp_amount`={$val}";
    elseif ($has_amount2)  $sets[]="`deal_value`={$val}";
  }
  if ($prob_in !== '') {
    $p = max(0,min(100,(int)$prob_in));
    if     ($has_prob1)    $sets[]="`probability`={$p}";
    elseif ($has_prob2)    $sets[]="`opp_probability`={$p}";
  }
  if ($closed_in !== '') {
    $dt = date('Y-m-d H:i:s', strtotime($closed_in));
    if     ($has_closed1)  $sets[]="`closed_date`='".mysqli_real_escape_string($DB,$dt)."'";
    elseif ($has_closed2)  $sets[]="`closed_on`='".mysqli_real_escape_string($DB,$dt)."'";
  }

  if ($sets) {
    $sql_up = "UPDATE `leads` SET ".implode(',',$sets)." WHERE id={$id} AND {$vis} LIMIT 1";
    $ok = @mysqli_query($DB,$sql_up);
    if ($ok){
      header('Location: /brocrm/mobile/dst_crm_view.php?id='.$id); exit;
    } else {
      $err = 'Database error. '.h(mysqli_error($DB));
    }
  } else {
    header('Location: /brocrm/mobile/dst_crm_view.php?id='.$id); exit;
  }
}

/* ----- Options ----- */
$myStatusOpts = ['Pending','In Process','Recycled','Prospect','Dead'];
$oppOpts      = ['Prospecting','Qualification','Proposal','Negotiation','Closed Won','Closed Lost'];

/* ------------------------------ THEME (Base) -------------------------------- */
$base_dir   = __DIR__ . '/Base';
$static_url = '/brocrm/mobile/assets';

/* Shared nav content */
ob_start();
include "$base_dir/navbar.php";
$navlink_content = ob_get_clean();
$page  = 'nav';
$fpage = 'foot';

/* ---------------------------- Page (hero) content -------------------------- */
ob_start();
$PAGE_TITLE = 'Edit DST Lead';
?>
<style>
:root{
  --bg:#fff9f5; --card:#ffffff; --muted:#667084; --text:#0f172a; --line:#e9edf5;
  --btn:#4f7cff; --btn-t:#fff;
}
body.theme-dark{
  --bg:#0d1117; --card:#141a1f; --muted:#aab2c0; --text:#e9eef7; --line:#242c3b;
  --btn:#5b8dff; --btn-t:#0b1220;
}
html,body{background:var(--bg); color:var(--text);}
.card{background:var(--card); border:1px solid var(--line); border-radius:16px;}
.small{color:var(--muted)!important}
.btn-big{background:var(--btn); color:var(--btn-t); border:0; height:50px; border-radius:12px; font-weight:800}
.form-select,.form-control{border-radius:12px;}
.top-back{background:#fff; border:1px solid var(--line); border-radius:10px; padding:.35rem .7rem; font-weight:700}
</style>

<!-- ============================ Page Title ============================ -->
<div class="page-title">
  <div class="container">
    <div class="row">
      <div class="col-12">
        <h2 class="ipt-title"><?=h($PAGE_TITLE)?></h2>
        <span class="ipn-subtitle">Update status, project &amp; notes</span>
      </div>
    </div>
  </div>
</div>

<section>
  <div class="container py-3">
    <div class="my-2">
      <a href="/brocrm/mobile/dst_crm_view.php?id=<?= (int)$id; ?>" class="top-back"><i class="fa-solid fa-arrow-left"></i> Back</a>
    </div>

    <div class="card">
      <div class="card-body">
        <h5 class="fw-extrabold mb-2">Edit • <?= h($name ?: ('Lead #'.$id)); ?></h5>
        <?php if($err): ?><div class="alert alert-danger py-2"><?= h($err); ?></div><?php endif; ?>

        <form method="post" action="">
          <div class="mb-3">
            <label class="small">My Status</label>
            <select name="tags" class="form-select">
              <?php foreach($myStatusOpts as $s){ ?>
                <option <?= (strcasecmp($tags,$s)===0?'selected':''); ?>><?= h($s); ?></option>
              <?php } ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="small">Opportunity Status</label>
            <select name="opp_status" id="opp_status" class="form-select">
              <?php
                $pre = $opp_display ?: '';
                foreach($oppOpts as $s){
                  $sel = (strcasecmp($pre,$s)===0) ? 'selected' : '';
                  echo '<option '.$sel.'>'.h($s).'</option>';
                }
              ?>
            </select>
            <div class="small mt-1">If “My Status” is <strong>Prospect</strong> and you pick <strong>Prospecting</strong>, it stores internally as <em>New</em>.</div>
          </div>

          <div class="mb-3">
            <label class="small d-flex justify-content-between align-items-center">
              <span>Project</span>
              <?php if($PROJ_SCHEMA): ?>
                <span class="small">Using <code><?=h($PROJ_SCHEMA)?>.projects</code></span>
              <?php endif; ?>
            </label>

            <?php
              // When leads has project_id, use an <input type=hidden> for name and a <select> for id (with label)
              $use_id = $has_proj_id;
            ?>

            <?php if ($use_id): ?>
              <select name="project_id" class="form-select" id="project_id">
                <option value="0">— Select —</option>
                <?php if(is_array($projects) && count($projects)): ?>
                  <?php foreach($projects as $p):
                    $pid  = (int)($p['id'] ?? 0);
                    $pnm  = trim($p['pname'] ?? ($pid ? ('Project #'.$pid) : ''));
                    $sel  = ($projectId>0 && $pid === $projectId) ? 'selected' : '';
                    echo '<option value="'.(int)$pid.'" '.$sel.'>'.h($pnm).'</option>';
                  endforeach; ?>
                <?php endif; ?>
              </select>
              <!-- Keep a synced name for readability in leads if such column exists -->
              <input type="hidden" name="project" id="project_name_hidden" value="<?= h($project); ?>">
              <script>
              (function(){
                const sel=document.getElementById('project_id');
                const hid=document.getElementById('project_name_hidden');
                sel?.addEventListener('change',function(){
                  const opt=this.options[this.selectedIndex];
                  hid.value = opt ? (opt.text || '') : '';
                });
              })();
              </script>
            <?php else: ?>
              <select name="project" class="form-select">
                <option value="">— Select —</option>
                <?php if(is_array($projects) && count($projects)): ?>
                  <?php foreach($projects as $p):
                    $nm  = trim($p['pname'] ?? '');
                    if($nm===''){ $nm = 'Project #'.(int)($p['id'] ?? 0); }
                    $sel = (trim($project) !== '' && strcasecmp($project,$nm)===0) ? 'selected' : '';
                    echo '<option value="'.h($nm).'" '.$sel.'>'.h($nm).'</option>';
                  endforeach; ?>
                <?php endif; ?>
              </select>
            <?php endif; ?>

            <?php if($projects_error): ?>
              <div class="small mt-1"><?= h($projects_error); ?></div>
            <?php endif; ?>
          </div>

          <div class="mb-3">
            <label class="small">Source</label>
            <input name="lead_source" class="form-control" value="<?= h($source); ?>" placeholder="Lead source">
          </div>

          <div class="row g-2">
            <div class="col-12 col-md-4">
              <label class="small">Amount</label>
              <input name="amount" type="number" step="0.01" class="form-control" value="<?= h($amount ?? ''); ?>" placeholder="0.00">
            </div>
            <div class="col-12 col-md-4">
              <label class="small">Probability %</label>
              <input name="prob" type="number" min="0" max="100" class="form-control" value="<?= h($prob ?? ''); ?>" placeholder="0-100">
            </div>
            <div class="col-12 col-md-4">
              <label class="small">Closed Date</label>
              <input name="closed_date" id="closed_date" type="datetime-local" class="form-control"
                     value="<?= $closed_dt ? h(date('Y-m-d\TH:i', strtotime($closed_dt))) : ''; ?>">
            </div>
          </div>

          <div class="mb-3 mt-2">
            <label class="small">Comment</label>
            <textarea name="comment" rows="4" class="form-control" placeholder="Notes"><?= h($comment); ?></textarea>
          </div>

          <button class="btn btn-big w-100">Save</button>
        </form>
      </div>
    </div>

  </div>
</section>

<script src="<?=h($static_url.'/js/jquery.js');?>"></script>
<script src="<?=h($static_url.'/vendor/bootstrap/js/bootstrap.bundle.min.js');?>"></script>
<script src="<?=h($static_url.'/js/custom.js');?>"></script>
<script>
/* Auto-set Closed Date when switching to a Closed status (if empty) */
const oppSel=document.getElementById('opp_status');
const closedEl=document.getElementById('closed_date');
function ensureClosedDate(){
  const v=(oppSel?.value||'').toLowerCase();
  if((v==='closed won' || v==='closed lost') && closedEl && !closedEl.value){
    const d=new Date(); d.setMinutes(d.getMinutes()-d.getTimezoneOffset());
    closedEl.value=d.toISOString().slice(0,16);
  }
}
oppSel?.addEventListener('change', ensureClosedDate);
</script>
<?php
$hero_content = ob_get_clean();

/* ------------------------------ Render via base ----------------------------- */
include "$base_dir/style/base.php";
