<?php
/* =============================================================================
 * File   : /brocrm/mobile/dst_crm_view.php
 * Goal   : View a single DST Lead with quick actions (Call/Mail/Task/Meeting),
 *          activity logger (offcanvas), and recent activity list.
 * Stack  : Core PHP + MySQLi (NO PDO). DB link from config.php
 * Charset: utf8mb4 / COLLATE=utf8mb4_general_ci
 * Notes  : Keeps existing UI/flow. Adds fields: location_id, budget_id, project_id, lead_type.
 *          For Call/Mail tiles: open native app + insert crm_pending_actions; tile blinks
 *          until an activity is logged (then resolved).
 *          ADDED (non-destructive): "Change Status" button + sheet to update
 *          pp_status (Pending/In Process/Recycled/Prospect/Dead) or opp_stage
 *          (Prospecting/Qualification/Proposal/Negotiation/Closed Won/Closed Lost).
 * ============================================================================= */

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'); }

/* --------------------------- 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'] ?? ''));

/* ------------------------- DB pick & force ONB schema ---------------------- */
$DB = null;
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; }

if (!($DB instanceof mysqli)) { http_response_code(500); exit('DB connection missing.'); }

/* charset/collation */
@mysqli_query($DB, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_set_charset($DB, 'utf8mb4');
@mysqli_query($DB, "SET collation_connection='utf8mb4_general_ci'");

/* Prefer `broriserin_onb`, fallback to `broriser_onb` */
if (!@mysqli_query($DB, "USE `broriserin_onb`")) {
  @mysqli_query($DB, "USE `broriser_onb`");
}

/* --------------------------------- 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; }
function table_exists($db,$t){ $t=mysqli_real_escape_string($db,$t); $rs=@mysqli_query($db,"SHOW TABLES LIKE '{$t}'"); $ok=$rs && mysqli_num_rows($rs)>0; if($rs) @mysqli_free_result($rs); return $ok; }
function source_badge_style($src){
  $s=strtolower(trim((string)$src));
  $map=['walk'=>'linear-gradient(135deg,#4ea6ff,#1bb0b3);','ref'=>'linear-gradient(135deg,#8b5cf6,#6366f1);','broker'=>'linear-gradient(135deg,#f97316,#ef4444);','web'=>'linear-gradient(135deg,#06b6d4,#3b82f6);','whats'=>'linear-gradient(135deg,#22c55e,#16a34a);','facebook'=>'linear-gradient(135deg,#08f,#0670e8);','insta'=>'linear-gradient(135deg,#f43f5e,#f97316);','google'=>'linear-gradient(135deg,#22d3ee,#818cf8);'];
  foreach($map as $k=>$g){ if (strpos($s,$k)!==false) return $g; }
  return 'linear-gradient(135deg,#0ea5e9,#22c55e);';
}

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

if (!table_exists($DB,'leads')) {
  http_response_code(200);
  echo "<p style='font:16px/1.4 system-ui;padding:20px'>No <b>leads</b> table found in <b>ONB</b> schema.</p>";
  exit;
}

/* If EMPID missing in session, try to resolve from superadmin.users */
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 broriserin_superadmin.users WHERE {$cond} LIMIT 1");
    if (!empty($u['empid'])) {
      $ME_EMPID = trim($u['empid']);
      $_SESSION['auth']['empid'] = $ME_EMPID;
    }
  }
}

/* Visibility guard */
$vis = "1=1";
if (!in_array($ROLE_NAME,['superadmin','admin'],true)) {
  $checks = [];
  if (col_exists($DB,'leads','assigned_user') && $ME_MAIL!=='') {
    $checks[] = "assigned_user = '".mysqli_real_escape_string($DB,$ME_MAIL)."'";
  }
  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 = $checks ? '('.implode(' OR ',$checks).')' : '0';
}

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

/* Flexible columns */
$contact_name = $rec['contact_name'] ?? ($rec['customer_name'] ?? ($rec['name'] ?? ''));
$project      = $rec['project'] ?? ($rec['project_name'] ?? '');
$phone        = $rec['mobile'] ?? ($rec['phone'] ?? '');
$email        = $rec['email'] ?? '';
$lead_source  = $rec['lead_source'] ?? ($rec['source'] ?? '');
$my_status    = $rec['tags'] ?? '';
$pp_status    = $rec['pp_status'] ?? ($rec['pipeline_stage'] ?? ($rec['stage'] ?? ''));
$comment      = $rec['remarks'] ?? ($rec['note'] ?? ($rec['comment'] ?? ''));
$created_at   = $rec['created_on'] ?? ($rec['created_at'] ?? null);

/* (ADDED) read opp_stage & current pp_status raw for chooser logic (no UI change) */
$pp_status_now = trim((string)($rec['pp_status'] ?? '')); // raw pp_status
$opp_stage_now = trim((string)($rec['opp_stage'] ?? '')); // may be empty

/* ------------------------ AJAX: update pp_status / stage -------------------- */
if (($_POST['ajax'] ?? '') === 'update_status') {
  header('Content-Type: application/json');
  $which = $_POST['which'] ?? ''; // 'pp' or 'stage'
  $value = trim((string)($_POST['value'] ?? ''));

  $ok = false; $msg = '';
  if ($which === 'pp') {
    $allowed = ['Pending','In Process','Recycled','Prospect','Dead'];
    if (!in_array($value, $allowed, true)) { echo json_encode(['ok'=>false,'msg'=>'Invalid status']); exit; }
    if ($value === 'Prospect') {
      // set pp_status, seed opp_stage if empty
      $ok = @mysqli_query($DB, "UPDATE `leads`
                                SET `pp_status`='Prospect',
                                    `opp_stage`=COALESCE(NULLIF(`opp_stage`,''),'Prospecting')
                                WHERE id=".(int)$ID." LIMIT 1");
    } else {
      $ok = @mysqli_query($DB, "UPDATE `leads` SET `pp_status`='".mysqli_real_escape_string($DB,$value)."' WHERE id=".(int)$ID." LIMIT 1");
    }
  } elseif ($which === 'stage') {
    $allowed = ['Prospecting','Qualification','Proposal','Negotiation','Closed Won','Closed Lost'];
    if (!in_array($value, $allowed, true)) { echo json_encode(['ok'=>false,'msg'=>'Invalid stage']); exit; }
    $ok = @mysqli_query($DB, "UPDATE `leads` SET `opp_stage`='".mysqli_real_escape_string($DB,$value)."' WHERE id=".(int)$ID." AND `pp_status`='Prospect' LIMIT 1");
  } else {
    $msg = 'Bad request';
  }

  echo json_encode(['ok'=>$ok?true:false, 'msg'=>$msg]);
  exit;
}

/* Compute comms hrefs once (used for tiles too) */
$ph = preg_replace('/\D+/','', (string)$phone);
if (strlen($ph)===10) $ph = '91'.$ph;
$telHref  = $ph ? "tel:{$ph}" : 'javascript:void(0)';
$mailHref = $email ? ('mailto:'.rawurlencode($email)) : 'javascript:void(0)';

/* Ensure activity/pending tables (and auto-migrate new columns) */
@mysqli_query($DB, "CREATE TABLE IF NOT EXISTS `crm_activities` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `enquiry_id` INT UNSIGNED NOT NULL,
  `activity_type` ENUM('call','meeting','task','email') NOT NULL DEFAULT 'task',
  `status` ENUM('Planned','Held','Not Held','Completed','Cancelled') NOT NULL DEFAULT 'Planned',
  `direction` ENUM('Inbound','Outbound','N/A') NOT NULL DEFAULT 'N/A',
  `title` VARCHAR(200) DEFAULT NULL,
  `description` TEXT,
  `date_start` DATETIME DEFAULT NULL,
  `date_end` DATETIME DEFAULT NULL,
  `duration_minutes` INT DEFAULT NULL,
  `assigned_user` VARCHAR(100) DEFAULT NULL,
  `created_by` VARCHAR(100) DEFAULT NULL,
  `remind` TINYINT(1) NOT NULL DEFAULT 0,
  `reminder_at` DATETIME DEFAULT NULL,
  `saved_from` VARCHAR(100) DEFAULT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY `idx_enquiry_id` (`enquiry_id`)
) ENGINE=InnoDB COLLATE=utf8mb4_general_ci");

@mysqli_query($DB,"CREATE TABLE IF NOT EXISTS `crm_pending_actions`(
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `enquiry_id` INT NOT NULL,
  `type` ENUM('call','sms','whatsapp','mail') NOT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `resolved` TINYINT(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `idx_eid_resolved` (`enquiry_id`,`resolved`)
) ENGINE=InnoDB COLLATE=utf8mb4_general_ci");

/* Auto-migrate: add columns if missing */
$toAdd = [];
if (!col_exists($DB,'crm_activities','location_id')) $toAdd[] = "ADD COLUMN `location_id` INT NULL";
if (!col_exists($DB,'crm_activities','budget_id'))   $toAdd[] = "ADD COLUMN `budget_id` INT NULL";
if (!col_exists($DB,'crm_activities','project_id'))  $toAdd[] = "ADD COLUMN `project_id` INT NULL";
if (!col_exists($DB,'crm_activities','lead_type'))   $toAdd[] = "ADD COLUMN `lead_type` VARCHAR(20) NULL";
if (!col_exists($DB,'crm_activities','page_url'))    $toAdd[] = "ADD COLUMN `page_url` VARCHAR(255) NULL";
if ($toAdd) { @mysqli_query($DB, "ALTER TABLE `crm_activities` ".implode(', ', $toAdd)); }

/* ------------------ AJAX: save_activity (and resolve pending) --------------- */
if (($_POST['ajax'] ?? '') === 'save_activity') {
  header('Content-Type: application/json');
  $enquiry_id = (int)($_POST['id'] ?? 0);
  if ($enquiry_id !== $ID) { echo json_encode(['ok'=>false,'msg'=>'Invalid context']); exit; }

  $type = strtolower(trim($_POST['type'] ?? 'task'));
  if(!in_array($type,['call','meeting','task','email'],true)) $type='task';

  $status = trim($_POST['status'] ?? 'Planned');
  if(!in_array($status,['Planned','Held','Not Held','Completed','Cancelled'],true)) $status='Planned';

  $direction = trim($_POST['direction'] ?? 'N/A');
  if(!in_array($direction,['Inbound','Outbound','N/A'],true)) $direction='N/A';

  $duration_minutes = max(0,(int)$_POST['duration_minutes'] ?? 5);
  $date_end_raw = trim($_POST['date_end'] ?? '');
  $date_end  = $date_end_raw ? date('Y-m-d H:i:00', strtotime($date_end_raw)) : date('Y-m-d H:i:00');
  $date_start= date('Y-m-d H:i:00', strtotime($date_end) - ($duration_minutes*60));
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');

  /* >>> Added fields <<< */
  $location_id = isset($_POST['location_id']) ? (int)$_POST['location_id'] : null;
  $budget_id   = isset($_POST['budget_id'])   ? (int)$_POST['budget_id']   : null;
  $project_id  = isset($_POST['project_id'])  ? (int)$_POST['project_id']  : null;
  $lead_type   = trim($_POST['lead_type'] ?? '');
  $page_url    = basename($_SERVER['PHP_SELF']);

  $remind = isset($_POST['remind']) ? (int)$_POST['remind'] : 0;
  $reminder_at_raw = trim($_POST['reminder_at'] ?? '');
  $reminder_at = ($remind && $reminder_at_raw) ? date('Y-m-d H:i:00', strtotime($reminder_at_raw)) : NULL;

  $assigned_user = $rec['assigned_user'] ?? NULL;
  $created_by = $ME_MAIL ?: ($ME_ID ?: null);
  if($title===''){ $title = ucfirst($type).' - '.($email ?: ($contact_name ?: '')); }

  $sql = "INSERT INTO `crm_activities`
    (`enquiry_id`,`activity_type`,`status`,`direction`,`title`,`description`,`date_start`,`date_end`,`duration_minutes`,
     `assigned_user`,`created_by`,`remind`,`reminder_at`,`saved_from`,`location_id`,`budget_id`,`project_id`,`lead_type`,`page_url`)
    VALUES (".(int)$enquiry_id.",
     '".mysqli_real_escape_string($DB,$type)."','".mysqli_real_escape_string($DB,$status)."','".mysqli_real_escape_string($DB,$direction)."',
     '".mysqli_real_escape_string($DB,$title)."','".mysqli_real_escape_string($DB,$description)."',
     '".mysqli_real_escape_string($DB,$date_start)."','".mysqli_real_escape_string($DB,$date_end)."',".(int)$duration_minutes.","
    .($assigned_user===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,$assigned_user)."'").","
    .($created_by===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,(string)$created_by)."'").","
    .(int)$remind.",".
     ($reminder_at===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,$reminder_at)."'").",'CRM Lead',".
     ($location_id===null ? "NULL" : (int)$location_id).",".
     ($budget_id===null   ? "NULL" : (int)$budget_id).",".
     ($project_id===null  ? "NULL" : (int)$project_id).",".
     ($lead_type!=='' ? "'".mysqli_real_escape_string($DB,$lead_type)."'" : "NULL").",".
     "'".mysqli_real_escape_string($DB,$page_url)."'"
    .")";

  $ok = @mysqli_query($DB,$sql);

  if ($ok) {
    $ptype = ($type==='email') ? 'mail' : $type; // pending types: mail/sms/whatsapp/call
    @mysqli_query($DB,"UPDATE crm_pending_actions
                       SET resolved=1
                       WHERE enquiry_id={$ID}
                         AND type='".mysqli_real_escape_string($DB,$ptype)."'
                         AND resolved=0");
  }

  echo json_encode(['ok'=>$ok?true:false]);
  exit;
}

/* ---------------- AJAX: add_pending (created on tile click) ----------------- */
if (($_POST['ajax'] ?? '') === 'add_pending') {
  header('Content-Type: application/json');
  $ptype = strtolower(trim($_POST['ptype'] ?? ''));
  if (!in_array($ptype, ['call','mail','sms','whatsapp'], true)) {
    echo json_encode(['ok'=>false,'msg'=>'bad type']); exit;
  }
  $exists = q_one($DB,"SELECT id FROM crm_pending_actions WHERE enquiry_id=".(int)$ID." AND type='".mysqli_real_escape_string($DB,$ptype)."' AND resolved=0 LIMIT 1");
  if (!$exists) {
    @mysqli_query($DB,"INSERT INTO crm_pending_actions (enquiry_id,type) VALUES (".(int)$ID.",'".mysqli_real_escape_string($DB,$ptype)."')");
  }
  echo json_encode(['ok'=>true]); exit;
}

/* --------------------- Recent activities & pending prompt ------------------- */
$acts = q_all($DB,"SELECT * FROM `crm_activities` WHERE `enquiry_id`={$ID} ORDER BY `date_end` DESC, `id` DESC LIMIT 30");

$pending     = q_one($DB,"SELECT * FROM crm_pending_actions WHERE enquiry_id={$ID} AND resolved=0 ORDER BY id DESC LIMIT 1");
$pendingType = $pending ? strtolower($pending['type']) : '';
$recentCut   = date('Y-m-d H:i:s', time()-1200); // 20 min window
$recent      = q_one($DB,"SELECT 1 FROM crm_activities WHERE enquiry_id={$ID} AND date_end>='{$recentCut}' ORDER BY id DESC LIMIT 1");
$autoPromptType = '';
if($pending && !$recent){
  $map = ['call'=>'call','mail'=>'mail','sms'=>'task','whatsapp'=>'task'];
  $autoPromptType = $map[$pendingType] ?? '';
}

/* Contact links (also duplicated in header card buttons) */
$phoneDigits = preg_replace('/\D+/','', $phone);
$tel  = $phoneDigits ? "tel:{$phoneDigits}" : 'javascript:void(0)';
$wa   = $phoneDigits ? "https://wa.me/{$phoneDigits}" : 'javascript:void(0)';
$sms  = $phoneDigits ? "sms:{$phoneDigits}" : 'javascript:void(0)';
$mail = $email ? ('mailto:'.rawurlencode($email)) : 'javascript:void(0)';

/* ---------------------- Dropdown data for logger (new) ---------------------- */
$locations = [];
if (table_exists($DB,'ic_location')) {
  $locations = q_all($DB, "SELECT id, Location_of_Work AS location_name FROM ic_location WHERE status='active' ORDER BY Location_of_Work ASC");
}
$budgets = [];
if (table_exists($DB,'budgets')) {
  $budgets = q_all($DB, "SELECT id, budget_range FROM budgets WHERE status='active' ORDER BY id ASC");
}
/* Projects come from broriserin_broriserin.projects (fallback to current DB) */
$projects = [];
$projLink = $DB;
if (isset($conn_crm) && $conn_crm instanceof mysqli) { $projLink = $conn_crm; }
@mysqli_query($projLink, "USE `broriserin_broriserin`");
$projects = q_all($projLink , "SELECT id, title FROM projects ORDER BY title ASC");
/* Switch back to ONB after reading projects */
if ($projLink === $DB) {
  @mysqli_query($DB, "USE `broriserin_onb`");
} else {
  @mysqli_query($DB, "USE `broriserin_onb`");
}

/* ------------------------------ Theme scaffolding --------------------------- */
$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 = 'View DST Lead';
$srcStyle   = 'background:'.source_badge_style($lead_source).';color:#fff;border:0;';
$blinkTile = [
  'call'     => ($pendingType==='call' && !$recent) ? ' blink' : '',
  'mail'     => ($pendingType==='mail' && !$recent) ? ' blink' : '',
  'task'     => (($pendingType==='sms' || $pendingType==='whatsapp') && !$recent) ? ' blink' : '',
  'meeting'  => '',
];
?>
<style>
:root{
  --bg:#fff9f5; --card:#ffffff; --muted:#667084; --text:#0f172a; --line:#e9edf5;
  --tile:#fff; --tile-line:#e9edf5; --tile-ring:#4f7cff;
}
body.theme-dark{
  --bg:#0d1117; --card:#141a1f; --muted:#aab2c0; --text:#e9eef7; --line:#242c3b;
  --tile:#1a2230; --tile-line:#273142; --tile-ring:#5b8dff;
}
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}
.top-back{background:#fff; border:1px solid var(--line); border-radius:10px; padding:.35rem .7rem; font-weight:700}
.tile-rail{display:grid;grid-template-columns:repeat(4,1fr);gap:18px}
.tile{background:var(--tile); border:1px solid var(--tile-line); border-radius:18px; padding:18px 8px; text-align:center; transition:box-shadow .15s,border-color .15s; font-weight:700}
.tile:focus,.tile.active{outline:0; border-color:var(--tile-ring); box-shadow:0 0 0 3px color-mix(in srgb, var(--tile-ring) 25%, transparent)}
@keyframes blink{0%,100%{box-shadow:0 0 0 0 rgba(79,124,255,0);}50%{box-shadow:0 0 0 6px rgba(79,124,255,.28);} }
.blink{animation:blink 1.2s linear infinite; border-color:var(--tile-ring)!important}
.tile .tcap{font-weight:800}
.btn-big{background:#4f7cff; color:#fff; border:0; height:50px; border-radius:12px; font-weight:800}
.section{padding:10px 0}
.badge-source{padding:.4rem .6rem; border-radius:10px; font-weight:800; letter-spacing:.2px}
.offcanvas .form-select,.offcanvas .form-control{border-radius:10px}
.tile-rail .tile[href] {color: black !important;}
/* Added: subtle style for status chooser buttons uses Bootstrap defaults */
</style>

<!-- ============================ Page Title Start ============================ -->
<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">Quick actions and timeline</span>
      </div>
    </div>
  </div>
</div>
<!-- ============================ Page Title End ============================== -->

<section>
  <div class="container py-3">

    <div class="my-2">
      <a href="/brocrm/mobile/dst.php" class="top-back"><i class="fa-solid fa-arrow-left"></i> Back</a>
    </div>

    <!-- Header Card -->
    <div class="card mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <div class="small">LEAD<?=str_pad((string)$ID,6,'0',STR_PAD_LEFT)?></div>
            <h5 class="mb-1 fw-extrabold">
              <?=h(trim(($contact_name ?: '—').($project ? ' – '.$project : '')));?>
            </h5>
            <div class="small">
              <?php if($created_at): ?>
                Created on: <?=h(date('d M Y', strtotime($created_at)));?>
              <?php endif; ?>
            </div>
          </div>
          <span class="badge badge-source" style="<?=h($srcStyle)?>"><?=h($lead_source ?: 'Source N/A');?></span>
        </div>
      </div>
    </div>

    <!-- Tiles -->
    <div class="tile-rail mb-3">
      <!-- data-href used to launch native app + create pending; still opens logger -->
      <button class="tile qa<?=$blinkTile['call'];?>" data-action="call" data-href="<?=h($telHref);?>" title="Log Call & Dial">
        <div class="mb-1"><i class="fa-solid fa-phone"></i></div><div class="tcap">Call</div>
      </button>
      <button class="tile qa<?=$blinkTile['mail'];?>" data-action="mail" data-href="<?=h($mailHref);?>" title="Log Mail & Compose">
        <div class="mb-1"><i class="fa-solid fa-envelope"></i></div><div class="tcap">Mail</div>
      </button>
      <button class="tile qa<?=$blinkTile['task'];?>" data-action="task" title="Log Task">
        <div class="mb-1"><i class="fa-solid fa-clipboard-check"></i></div><div class="tcap">Task</div>
      </button>
      <button class="tile qa<?=$blinkTile['meeting'];?>" data-action="meeting" title="Log Meeting">
        <div class="mb-1"><i class="fa-regular fa-calendar"></i></div><div class="tcap">Meeting</div>
      </button>
    </div>

    <!-- Status block -->
    <div class="card section">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-12 col-md-6">
            <div class="small">My Status</div>
            <div class="fw-bold"><?=h($my_status ?: '—');?></div>
          </div>
          <div class="col-12 col-md-6">
            <div class="small">Opportunity Status</div>
            <?php
              $opp = $pp_status;
              if (strcasecmp($my_status,'Prospect')===0 && (strcasecmp($opp,'New')===0 || $opp==='')) $opp='Prospecting';
            ?>
            <div class="fw-bold"><?=h($opp ?: '—');?></div>
          </div>
          <div class="col-12">
            <div class="small">Comment</div>
            <div class="fw-bold"><?=($comment!=='') ? nl2br(h($comment)) : '—';?></div>
          </div>
        </div>

        <div class="d-flex gap-2 mt-3">
          <!--<a class="btn btn-big flex-grow-1" href="/brocrm/mobile/dst_crm_edit.php?id=<?=$ID?>">Edit</a> -->
          <!-- ADDED: Change Status button (non-destructive) -->
          <button class="btn btn-outline-primary" id="btnChangeStatus" title="Change Status">Change Status</button>
          <?php
            $ph2 = preg_replace('/\D+/','', $phone);
            if (strlen($ph2)===10) $ph2 = '91'.$ph2;
            $telB  = $ph2 ? "tel:{$ph2}" : 'javascript:void(0)';
            $wa    = $ph2 ? "https://wa.me/{$ph2}" : 'javascript:void(0)';
            $sms   = $ph2 ? "sms:{$ph2}" : 'javascript:void(0)';
            $mailB = $email ? ('mailto:'.rawurlencode($email)) : 'javascript:void(0)';
          ?>
          <a class="btn btn-outline-primary" href="<?=h($telB)?>" title="Call"><i class="fa fa-phone"></i></a>
          <a class="btn btn-outline-success" href="<?=h($wa)?>" target="_blank" title="WhatsApp"><i class="fab fa-whatsapp"></i></a>
          <a class="btn btn-outline-secondary" href="<?=h($sms)?>" title="SMS"><i class="fa-regular fa-message"></i></a>
          <a class="btn btn-outline-dark" href="<?=h($mailB)?>" title="Mail"><i class="fa fa-envelope"></i></a>
        </div>
      </div>
    </div>

    <!-- Activities -->
    <div class="card mb-5">
      <div class="card-header d-block"><h5 class="card-title mb-0">Recent Activities</h5></div>
      <div class="card-body">
        <?php if(!$acts){ ?>
          <div class="small">No activities yet.</div>
        <?php } else { foreach($acts as $a){ ?>
          <div class="d-flex justify-content-between align-items-start py-2 border-bottom">
            <div>
              <div class="fw-bold text-capitalize"><?=h($a['activity_type']);?></div>
              <div class="small"><?=h($a['title'] ?: '—');?></div>
              <div class="small">
                <?=h(date('d M Y, h:i A', strtotime($a['date_end'])));?> •
                <?=h($a['status']);?>
                <?php if($a['direction'] && $a['direction']!=='N/A') echo ' • '.h($a['direction']); ?>
              </div>
            </div>
            <div class="small"><?=(int)$a['duration_minutes'];?>m</div>
          </div>
        <?php } } ?>
      </div>
    </div>

  </div>
</section>

<!-- Log Activity bottom sheet -->
<div class="offcanvas offcanvas-bottom" tabindex="-1" id="actSheet" style="height:80vh;">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="actTitle">Log Activity</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <div class="card"><div class="card-body">
      <div class="row g-2">
        <div class="col-6">
          <label class="small">Status
            <select id="f-status" class="form-select">
              <option>Planned</option><option>Held</option><option>Not Held</option><option>Completed</option><option>Cancelled</option>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Direction
            <select id="f-direction" class="form-select">
              <option>Outbound</option><option>Inbound</option><option selected>N/A</option>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Duration (mins)
            <select id="f-duration" class="form-select"><option>5</option><option>15</option><option>30</option><option>45</option><option>60</option><option>90</option><option>120</option></select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Date End *
            <input id="f-dateend" type="datetime-local" class="form-control">
          </label>
        </div>

        <!-- NEW: extra fields -->
        <div class="col-6">
          <label class="small">Location
            <select id="f-location" class="form-select">
              <option value="">Select Location</option>
              <?php foreach($locations as $loc): ?>
                <option value="<?= h($loc['id']) ?>"><?= h($loc['location_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Budget
            <select id="f-budget" class="form-select">
              <option value="">Select Budget</option>
              <?php foreach($budgets as $bud): ?>
                <option value="<?= h($bud['id']) ?>"><?= h($bud['budget_range']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Project
            <select id="f-projects" class="form-select">
              <option value="">Select Project</option>
              <?php foreach($projects as $proj): ?>
                <option value="<?= h($proj['id']) ?>"><?= h($proj['title']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Lead Type
            <select id="f-leadtype" class="form-select">
              <option value="">Select</option>
              <option value="hot">Hot</option>
              <option value="warm">Warm</option>
              <option value="cold">Cold</option>
            </select>
          </label>
        </div>

        <div class="col-12">
          <label class="small">Title
            <input id="f-title" type="text" class="form-control" placeholder="Title">
          </label>
        </div>
        <div class="col-12">
          <label class="small">Description
            <textarea id="f-desc" rows="4" class="form-control" placeholder="Notes"></textarea>
          </label>
        </div>
        <div class="col-6 d-flex align-items-center">
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="f-remind">
            <label class="form-check-label small" for="f-remind">Set Reminder</label>
          </div>
        </div>
        <div class="col-6">
          <label class="small">Reminder At
            <input id="f-remindat" type="datetime-local" class="form-control" disabled>
          </label>
        </div>
        <div class="col-6">
          <button class="btn btn-big w-100" id="saveAct">Save</button>
        </div>
        <div class="col-6">
          <button class="btn btn-secondary w-100" data-bs-dismiss="offcanvas">Close</button>
        </div>
      </div>
    </div></div>
  </div>
</div>

<!-- ADDED: Change Status bottom sheet -->
<div class="offcanvas offcanvas-bottom" tabindex="-1" id="statusSheet" style="height:70vh;">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="statusTitle">Change Status</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <!-- Primary Status (pp_status) list -->
    <div id="ppList" class="list-group mb-3" style="display:none;">
      <button type="button" class="list-group-item list-group-item-action" data-which="pp" data-value="Pending">Pending</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="pp" data-value="In Process">In Process</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="pp" data-value="Recycled">Recycled</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="pp" data-value="Prospect">Prospect</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="pp" data-value="Dead">Dead</button>
    </div>
    <!-- Opportunity Stage (opp_stage) list -->
    <div id="stageList" class="list-group" style="display:none;">
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Prospecting">Prospecting</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Qualification">Qualification</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Proposal">Proposal</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Negotiation">Negotiation</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Closed Won">Closed Won</button>
      <button type="button" class="list-group-item list-group-item-action" data-which="stage" data-value="Closed Lost">Closed Lost</button>
    </div>
  </div>
</div>

<script src="<?=h($static_url.'/old/js/jquery.js');?>"></script>
<script src="<?=h($static_url.'/old/vendor/bootstrap/js/bootstrap.bundle.min.js');?>"></script>
<script src="<?=h($static_url.'/old/vendor/swiper/swiper-bundle.min.js');?>"></script>
<script src="<?=h($static_url.'/old/js/custom.js');?>"></script>
<script>
/* Logger sheet */
const sheetEl=document.getElementById('actSheet');
const sheet = sheetEl ? new bootstrap.Offcanvas(sheetEl) : null;
const titleEl=document.getElementById('actTitle');
const endEl=document.getElementById('f-dateend');
const remindCb=document.getElementById('f-remind');
const remindAt=document.getElementById('f-remindat');

function openSheet(kind){
  titleEl.textContent='Log '+(kind==='call'?'Call':kind==='meeting'?'Meeting':kind==='mail'?'Email':'Task');
  const dir=document.getElementById('f-direction');
  dir.disabled=(kind!=='call');
  dir.value=(kind==='call'?'Outbound':'N/A');
  const d=new Date(Date.now()+5*60000);
  const iso=new Date(d.getTime()-d.getTimezoneOffset()*60000).toISOString().slice(0,16);
  endEl.value=iso;
  sheet?.show();
}
remindCb.addEventListener('change',()=>{remindAt.disabled=!remindCb.checked; if(remindCb.checked && !remindAt.value){remindAt.value=endEl.value;}});

let actType='task';

/* Tile click: open logger; for Call/Mail also fire pending + launch native app */
document.querySelectorAll('.qa').forEach(b=>{
  b.addEventListener('click', async ()=>{
    actType=b.getAttribute('data-action')||'task';
    const href=b.getAttribute('data-href')||'';
    if (actType==='call' || actType==='mail') {
      try {
        await fetch(location.href, {
          method:'POST',
          headers:{'Content-Type':'application/x-www-form-urlencoded'},
          body: new URLSearchParams({ajax:'add_pending', ptype:(actType==='mail'?'mail':'call')}).toString()
        });
      } catch(e) {}
      if (href && href!=='javascript:void(0)') {
        setTimeout(()=>{ window.location.href = href; }, 80);
      }
    }
    openSheet(actType);
  });
});

/* Auto-open if a pending action exists and no recent activity */
<?php if($autoPromptType){ ?>
document.addEventListener('DOMContentLoaded', function(){
  actType = '<?=h($autoPromptType)?>';
  openSheet(actType);
});
<?php } ?>

/* Save activity (resolve pending on server) */
document.getElementById('saveAct').addEventListener('click',(e)=>{
  e.preventDefault();
  const data=new URLSearchParams();
  data.append('ajax','save_activity');
  data.append('id','<?= (int)$ID; ?>');
  data.append('type',actType);
  data.append('status',document.getElementById('f-status').value);
  const dirEl=document.getElementById('f-direction');
  data.append('direction',dirEl.disabled?'N/A':dirEl.value);
  data.append('duration_minutes',document.getElementById('f-duration').value||'5');
  data.append('date_end',(document.getElementById('f-dateend').value||'').replace('T',' '));
  data.append('title',document.getElementById('f-title').value||'');
  data.append('description',document.getElementById('f-desc').value||'');
  data.append('remind',document.getElementById('f-remind').checked?'1':'0');
  data.append('reminder_at',(document.getElementById('f-remindat').value||'').replace('T',' '));

  /* >>> send new fields <<< */
  data.append('location_id', document.getElementById('f-location').value || '');
  data.append('budget_id',   document.getElementById('f-budget').value   || '');
  data.append('project_id',  document.getElementById('f-projects').value || '');
  data.append('lead_type',   document.getElementById('f-leadtype').value || '');

  fetch(location.href,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:data.toString()})
    .then(r=>r.json()).then(j=>{ if(j&&j.ok){ alert('Activity saved'); location.reload(); } else { alert('Failed'); }});
});

/* Visual active ring on tiles */
document.querySelectorAll('.tile-rail .tile').forEach(el=>{
  el.addEventListener('focus',()=>{ el.classList.add('active'); },true);
  el.addEventListener('blur',()=>{ el.classList.remove('active'); },true);
  el.addEventListener('click',()=>{ document.querySelectorAll('.tile-rail .tile').forEach(x=>x.classList.remove('active')); el.classList.add('active'); });
});

/* ===== ADDED: Change Status logic (keeps everything else the same) ===== */
const statusSheetEl = document.getElementById('statusSheet');
const statusSheet = statusSheetEl ? new bootstrap.Offcanvas(statusSheetEl) : null;
const ppList = document.getElementById('ppList');
const stageList = document.getElementById('stageList');
const statusTitle = document.getElementById('statusTitle');
const ppStatusNow = <?= json_encode($pp_status_now) ?>; // raw pp_status

document.getElementById('btnChangeStatus').addEventListener('click', ()=>{
  const isProspect = (ppStatusNow === 'Prospect');
  statusTitle.textContent = isProspect ? 'Change Opportunity Stage' : 'Change Primary Status';
  ppList.style.display = isProspect ? 'none' : 'block';
  stageList.style.display = isProspect ? 'block' : 'none';
  statusSheet?.show();
});

document.querySelectorAll('#ppList .list-group-item, #stageList .list-group-item').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const which = btn.getAttribute('data-which'); // 'pp' or 'stage'
    const value = btn.getAttribute('data-value');
    const data=new URLSearchParams();
    data.append('ajax','update_status');
    data.append('which',which);
    data.append('value',value);
    fetch(location.href,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:data.toString()})
      .then(r=>r.json()).then(j=>{ if(j&&j.ok){ location.reload(); } else { alert(j.msg || 'Update failed'); }});
  });
});
</script>
<?php
$hero_content = ob_get_clean();

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