<?php
/* =============================================================================
 * File   : /mobile/dst.php
 * Goal   : DST Leads list inside Resido theme header/footer (Base/style/base.php)
 * Stack  : Core PHP + MySQLi ONLY (NO PDO). DB link from config.php
 * Charset: utf8mb4 / COLLATE=utf8mb4_general_ci
 * Notes  : Functionality preserved (filters, empid restriction, claim popup,
 *          quick actions, light pending-action beacon). Uses Resido classes.
 * ============================================================================= */

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'");
@mysqli_query($DB, "USE `broriserin_onb`");

/* --------------------------------- Helpers -------------------------------- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
function q($db,$s){ return @mysqli_query($db,$s); }
function row($db,$s){ $r=null; if($res=q($db,$s)){ $r=mysqli_fetch_assoc($res); mysqli_free_result($res);} return $r; }
function all($db,$s){ $o=[]; if($res=q($db,$s)){ while($r=mysqli_fetch_assoc($res)) $o[]=$r; mysqli_free_result($res);} return $o; }
function table_exists($db,$t){ $t=mysqli_real_escape_string($db,$t); $res=q($db,"SHOW TABLES LIKE '{$t}'"); $ok=$res && mysqli_num_rows($res)>0; if($res) mysqli_free_result($res); return $ok; }
function col_exists($db,$t,$c){ $t=mysqli_real_escape_string($db,$t); $c=mysqli_real_escape_string($db,$c); $res=q($db,"SHOW COLUMNS FROM `{$t}` LIKE '{$c}'"); $ok=$res && mysqli_num_rows($res)>0; if($res) mysqli_free_result($res); 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);';
}

/* ---------------------- Ensure leads table availability --------------------- */
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>broriserin_onb</b>.</p>";
  exit;
}

/* ------ 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 = row($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;
    }
  }
}

/* ------------------------------ Inputs / Filters --------------------------- */
$qtxt = trim($_GET['q'] ?? '');
$df   = $_GET['df'] ?? 'today';
if (!in_array($df, ['today','last7','month','all'], true)) $df = 'today';

/* ------------------------------- Build WHERE ------------------------------- */
$W = ["1=1"];

/* STRICT EMPID filter for non-admins */
$empCol = null;
foreach (['empid','employee_id','emp_id'] as $c){ if (col_exists($DB,'leads',$c)) { $empCol=$c; break; } }
if (!in_array($ROLE_NAME, ['superadmin','admin'], true)) {
  if ($ME_EMPID !== '' && $empCol) {
    $W[] = "`{$empCol}`='".mysqli_real_escape_string($DB,$ME_EMPID)."'";
  } else {
    $W[] = "1=0"; // safety
  }
}

/* Search over common columns (only those that exist) */
$searchCols = array_values(array_filter(
  ['contact_name','customer_name','name','mobile','phone','email','project','project_name','lead_source','source','company','tags','remarks','note','comment'],
  fn($c)=>col_exists($DB,'leads',$c)
));
if ($qtxt!=='' && $searchCols){
  $like = "%".mysqli_real_escape_string($DB,$qtxt)."%";
  $parts=[]; foreach($searchCols as $c){ $parts[]="`{$c}` LIKE '{$like}'"; }
  $W[] = '('.implode(' OR ',$parts).')';
}

/* Date filter (created_at / created_on) — Today default */
$dcol = col_exists($DB,'leads','created_at') ? 'created_at'
      : (col_exists($DB,'leads','created_on') ? 'created_on' : null);
if ($dcol) {
  if ($df==='today')        $W[] = "DATE(`{$dcol}`)=CURDATE()";
  elseif ($df==='last7')    $W[] = "`{$dcol}`>=CURDATE()-INTERVAL 7 DAY";
  elseif ($df==='month')    $W[] = "YEAR(`{$dcol}`)=YEAR(CURDATE()) AND MONTH(`{$dcol}`)=MONTH(CURDATE())";
}

/* --------------------------------- Fetch rows ------------------------------- */
$where = 'WHERE '.implode(' AND ', $W);
$total = (int)(row($DB, "SELECT COUNT(*) c FROM `leads` {$where}")['c'] ?? 0);
$list  = all($DB, "SELECT * FROM `leads` {$where} ORDER BY id DESC LIMIT 50");

/* ---------------------- Compute "New Lead to Claim" POPUP flag -------------- */
$hasEmpidCol    = col_exists($DB,'leads','empid');
$showClaimPopup = false;
if ($ROLE_ID === 4 && $hasEmpidCol) {
  $chk = row($DB, "SELECT 1 AS ok FROM leads WHERE (empid IS NULL OR TRIM(empid)='') LIMIT 1");
  $showClaimPopup = !empty($chk['ok']);
}

/* ----------------------------- Theme: Base layout --------------------------- */
$base_dir   = __DIR__ . '/Base';
$static_url = '/Resido/assets'; // Adjust if your assets path differs

/* Include the common navlink content (header) */
ob_start();
include $base_dir . '/navbar.php';
$navlink_content = ob_get_clean();
$page  = 'nav';
$fpage = 'foot';

/* ------------------------- Page (hero_content) start ------------------------ */
ob_start();
?>
<link rel="stylesheet" href="<?php echo h($static_url); ?>/css/dst-leads.css"/>

<!-- ============================ Page Title Start ================================== -->
<div class="page-title">
  <div class="container">
    <div class="row"><div class="col-12">
      <h2 class="ipt-title mb-0">My DST Leads</h2>
      <span class="ipn-subtitle">Fast actions • Clean cards • Mobile friendly</span>
    </div></div>
  </div>
</div>
<!-- ============================ Page Title End ==================================== -->

<section class="bg-light">
  <div class="container">

    <!-- Filters -->
    <div class="row align-items-center g-2 mb-3">
      <div class="col-lg-8 col-md-7">
        <?php
          $mk = function($k,$t) use ($df,$qtxt){
            $active = $df===$k ? ' active' : '';
            $href   = '?'.http_build_query(['df'=>$k,'q'=>$qtxt]);
            return '<a class="dst-pill'.$active.'" href="'.h($href).'">'.h($t).'</a>';
          };
        ?>
        <div class="dst-pills">
          <?php echo $mk('today','Today'); ?>
          <?php echo $mk('last7','Last 7 Days'); ?>
          <?php echo $mk('month','This Month'); ?>
          <?php echo $mk('all','All'); ?>
        </div>
      </div>
      <div class="col-lg-4 col-md-5">
        <form method="get" action="" class="dst-search">
          <input type="hidden" name="df" value="<?php echo h($df); ?>">
          <div class="input-group">
            <input type="search" class="form-control" name="q" value="<?php echo h($qtxt); ?>" placeholder="Search name, phone, email, project, source">
            <button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
          </div>
        </form>
      </div>
    </div>

    <div class="row"><div class="col-12">
      <div class="dst-count">Showing <?php echo count($list); ?> of <?php echo (int)$total; ?></div>
    </div></div>

    <?php if(!$list){ ?>
      <div class="row"><div class="col-12">
        <div class="dst-empty">No Records</div>
      </div></div>
    <?php } else { ?>
      <div class="row">
        <?php foreach($list as $r):
          $id      = (int)$r['id'];
          $name    = $r['contact_name'] ?? $r['customer_name'] ?? $r['name'] ?? '—';
          $project = $r['project'] ?? $r['project_name'] ?? '';
          $title   = trim($name) !== '' ? trim($name.($project ? ' – '.$project : '')) : ($project ?: 'Enquiry');
          $status  = $r['tags'] ?? '—';
          $pp      = $r['pp_status'] ?? ($r['pipeline_stage'] ?? $r['stage'] ?? '—');
          $posted  = $r['created_on'] ?? $r['created_at'] ?? '';
          $posted  = $posted ? date('d M Y', strtotime($posted)) : '—';
          $source  = $r['lead_source'] ?? ($r['source'] ?? '');
          $srcText = $source !== '' ? $source : 'Source N/A';
          $srcStyle = 'background:' . source_badge_style($source);
          $phone   = $r['phone_number'] ?? $r['mobile'] ?? $r['phone'] ?? '';
          $email   = $r['email'] ?? '';
          $phNum   = preg_replace('/\D+/', '', $phone);
          if (strlen($phNum) === 10) { $phNum = '91' . $phNum; }
          $telHref  = $phNum ? "tel:{$phNum}" : 'javascript:void(0)';
          $smsHref  = $phNum ? "sms:{$phNum}" : 'javascript:void(0)';
          $waHref   = $phNum ? "https://wa.me/{$phNum}" : 'javascript:void(0)';
          $mailHref = $email ? ('mailto:' . rawurlencode($email)) : 'javascript:void(0)';
        ?>
        <div class="col-xl-4 col-lg-6 col-md-6">
          <div class="property-listing card dst-card">
            <div class="dst-card-head">
              <div>
                <div class="dst-eyebrow">Enquiry</div>
                <h5 class="dst-title">
                  <a class="text-dark" href="dst_crm_view.php?id=<?php echo urlencode($id); ?>"><?php echo h($title); ?></a>
                </h5>
              </div>
              <span class="badge dst-src" style="<?php echo h($srcStyle); ?>"><?php echo h($srcText); ?></span>
            </div>

            <div class="dst-grid">
              <div>
                <div class="dst-k">My Status</div>
                <div class="dst-chip"><?php echo h($status ?: '—'); ?></div>
              </div>
              <div>
                <div class="dst-k">PP Status</div>
                <div class="dst-chip"><?php echo h($pp ?: '—'); ?></div>
              </div>
            </div>

            <div class="dst-meta"><span class="text-muted">Posted on</span>&nbsp;<strong><?php echo h($posted); ?></strong></div>

            <div class="dst-actions">
              <a href="<?=h($telHref)?>"  class="btn btn-sm dst-btn dst-call qa-out"  data-type="call"      aria-label="Call"><i class="fa fa-phone"></i></a>
              <a href="<?=h($waHref)?>"   class="btn btn-sm dst-btn dst-wa qa-out"    data-type="whatsapp" target="_blank" rel="noopener" aria-label="WhatsApp"><i class="fab fa-whatsapp"></i></a>
              <a href="<?=h($smsHref)?>"  class="btn btn-sm dst-btn dst-sms qa-out"   data-type="sms"       aria-label="SMS"><i class="fa-regular fa-message"></i></a>
              <a href="<?=h($mailHref)?>" class="btn btn-sm dst-btn dst-mail qa-out"  data-type="mail"      aria-label="Email"><i class="fa fa-envelope"></i></a>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    <?php } ?>

  </div>
</section>

<!-- ============================== CLAIM POPUP ============================== -->
<?php if ($showClaimPopup): ?>
<div class="claim-popup" id="claimPopup" role="dialog" aria-live="polite" aria-label="New Lead to Claim">
  <span class="dot" aria-hidden="true"></span>
  <div class="text">New Lead to Claim</div>
  <a class="cta" href="/mobile/dst_claim.php">Open</a>
  <button type="button" class="close-x" id="claimCloseBtn" aria-label="Dismiss">×</button>
</div>
<script>
(function(){
  const pop = document.getElementById('claimPopup');
  const closeBtn = document.getElementById('claimCloseBtn');
  if(pop){
    const KEY='claim_pop_dismissed';
    if(!sessionStorage.getItem(KEY)){ pop.classList.add('show'); }
    closeBtn?.addEventListener('click', ()=>{ pop.classList.remove('show'); sessionStorage.setItem(KEY,'1'); });
  }
})();
</script>
<?php endif; ?>

<script>
/* Lightweight activity logger (silent failure OK) */
document.query
