<?php
/* ============================================================================
 * File   : dst.php
 * Goal   : Mobile CRM list (LIGHT) from broriserin_onb.leads + Claim POPUP
 * Auth   : sa_require_auth() via auth_bootstrap.php
 * Notes  : - STRICT filter by leads.empid == logged-in user's empid (non-admins)
 *          - role_id is read from $_SESSION['auth'] (same as footer_mobile.php)
 *          - Date filter: df=today|last7|month|all (default today)
 *          - POPUP rule (fixed): Show when role_id === 4 AND the table has
 *              column `empid` AND there exists ANY row with empid NULL or ''.
 *              (assigned_user column only needs to exist; its value can be NULL)
 * DB      : MySQLi only (NO PDO). Collation utf8mb4_general_ci enforced.
 * ========================================================================== */

@session_start();
date_default_timezone_set('Asia/Kolkata');

require_once __DIR__ . '/auth_bootstrap.php';
sa_require_auth();

/* --------------------------- Current user/session --------------------------- */
/* EXACTLY like footer_mobile.php */
$ME        = $_SESSION['auth'] ?? [];
$ROLE_ID   = isset($ME['role_id']) ? (int)$ME['role_id'] : 0;   // <-- reference pattern
$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())";
  // 'all' => no extra filter
}

$where = 'WHERE '.implode(' AND ', $W);

/* --------------------------------- Fetch rows ------------------------------- */
$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 -------------- */
/* *** FIXED LOGIC ***
 * Show the popup when:
 *  - role_id === 4
 *  - leads has column 'empid'
 *  - there EXISTS any row with empid IS NULL OR TRIM(empid)=''
 * (assigned_user column only needs to exist; its value may be NULL)
 */
$hasEmpidCol        = col_exists($DB,'leads','empid');
$hasAssignedUserCol = col_exists($DB,'leads','assigned_user'); // only to ensure column exists
$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/UI -------------------------------- */
$ASSETS = 'assets';
$PAGE_TITLE = 'My DST Leads';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, minimal-ui, viewport-fit=cover">
<title><?php echo h($PAGE_TITLE); ?></title>
<link rel="shortcut icon" type="image/x-icon" href="<?php echo h($ASSETS); ?>/images/favicon.png" />
<link rel="stylesheet" href="<?php echo h($ASSETS); ?>/vendor/swiper/swiper-bundle.min.css">
<link rel="stylesheet" href="<?php echo h($ASSETS); ?>/vendor/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.css">
<link rel="stylesheet" href="<?php echo h($ASSETS); ?>/css/style.css">
<style>
:root{
  --crm-bg:#f7fbff; --crm-card:#fff; --crm-line:rgba(0,0,0,.08); --crm-muted:#687083;
  --claim-bg: #0ea5e9;        /* popup main color */
  --claim-accent:#22c55e;     /* gradient accent */
  --claim-text:#fff;
  --claim-shadow: 0 10px 22px rgba(14,165,233,.28);
}
html,body{ background:var(--crm-bg); }
.crm-card{ background:var(--crm-card); border:1px solid var(--crm-line); border-radius:16px; padding:12px; margin-bottom:12px; }
.crm-k{ font-size:12px; color:var(--crm-muted); }
.crm-v{ font-weight:800; }
.badge-src{ color:#fff; border:0; }
.crm-actions{ display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-top:12px; }
.crm-cta{ height:20px; border-radius:14px; display:flex; align-items:center; justify-content:center; color:#fff; border:0; box-shadow:0 2px 0 rgba(0,0,0,.05),0 8px 20px rgba(0,0,0,.06); }
.crm-cta.call{ background:linear-gradient(180deg,#ff6a00,#ff3d00); }
.crm-cta.wa  { background:linear-gradient(180deg,#22c55e,#16a34a); }
.crm-cta.sms { background:linear-gradient(180deg,#25a7ff,#1199f0); }
.crm-cta.mail{ background:linear-gradient(180deg,#27c4ff,#12b2ef); }

.df-bar{ display:flex; gap:8px; flex-wrap:wrap; margin:10px 0 6px; }
.df-btn{ padding:8px 12px; border-radius:999px; border:1px solid var(--crm-line); background:#fff; font-weight:700; }
.df-btn.active{ background:#0ea5e9; color:#fff; border-color:#0ea5e9; }

/* -------------------- Left-bottom POPUP (above footer) --------------------- */
.claim-popup{
  position: fixed;
  left: 14px;
  bottom: 135px; /* above footer */
  z-index: 9999;
  width: min(52vw, 320px);
  background: linear-gradient(135deg, var(--claim-bg) 0%, var(--claim-accent) 100%);
  color: var(--claim-text);
  border-radius: 16px;
  box-shadow: var(--claim-shadow);
  padding: 12px 12px 12px 14px;
  display: none;                /* shown via JS when allowed */
  align-items: center;
  gap: 10px;
}
.claim-popup.show{ display:flex; animation: slidein .28s ease-out; }
@keyframes slidein{ from{ transform: translateX(-10px); opacity:.0; } to{ transform: translateX(0); opacity:1; } }
.claim-popup .dot{
  width: 10px; height: 10px; border-radius: 50%;
  background: #fff; opacity:.95;
  box-shadow: 0 0 0 0 rgba(255,255,255,.7);
  animation: pulse 1.6s infinite;
}
@keyframes pulse{ 0%{ box-shadow:0 0 0 0 rgba(255,255,255,.6);} 70%{ box-shadow:0 0 0 12px rgba(255,255,255,0);} 100%{ box-shadow:0 0 0 0 rgba(255,255,255,0);} }
.claim-popup .text{ font-weight: 800; line-height: 1.1; font-size: 15px; letter-spacing: .2px; }
.claim-popup .cta{
  margin-left: auto; background: rgba(255,255,255,.18);
  border: 1px solid rgba(255,255,255,.28); color: #fff;
  padding: 8px 10px; border-radius: 12px; text-decoration: none;
  font-weight: 800; white-space: nowrap; transition: background .15s ease,border-color .15s ease,transform .12s ease;
}
.claim-popup .cta:active{ transform: scale(.98); }
.claim-popup .close-x{
  position:absolute; right:-10px; top:-14px; width:28px; height:28px; border-radius:50%;
  background: darkred; border:1px solid rgba(255,255,255,.25);
  color:#fff; display:flex; align-items:center; justify-content:center;
  font-weight:900; line-height:1; cursor:pointer;
}
@media (max-width:380px){
  .claim-popup{ left:10px; bottom:135px; border-radius:14px; }
  .claim-popup .text{ font-size:14px; }
}
</style>
</head>
<body>

<div class="page-wraper header-fixed">
  <?php include __DIR__.'/header_mobile.php'; ?>
  <?php include __DIR__.'/sidebar_mobile.php'; ?>

  <div class="page-content">
    <div class="content-inner pt-0">
      <div class="container p-b50">

        <!-- Search -->
        <form class="mb-2" method="get" action="">
          <div class="input-group">
            <input type="hidden" name="df" value="<?php echo h($df); ?>">
            <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>

        <!-- Date Filter Buttons -->
        <?php
          $btn = function($key,$label) use ($df,$qtxt){
            $active = $df===$key ? ' active' : '';
            $href = '?'.http_build_query(['df'=>$key,'q'=>$qtxt]);
            return '<a class="df-btn'.$active.'" href="'.h($href).'">'.h($label).'</a>';
          };
        ?>
        <div class="df-bar">
          <?php echo $btn('today','Today'); ?>
          <?php echo $btn('last7','Last 7 Days'); ?>
          <?php echo $btn('month','This Month'); ?>
          <?php echo $btn('all','All'); ?>
        </div>

        <div class="mb-2 opacity-75 fw-bold">Showing <?php echo count($list); ?> of <?php echo (int)$total; ?></div>

        <?php if(!$list){ ?>
          <div class="text-center py-5 opacity-75 fw-bold">No Records</div>
        <?php } else { 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['mobile'] ?? $r['phone'] ?? '';
          $email   = $r['email'] ?? '';
          $phNum   = preg_replace('/\D+/','',$phone);
          $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="crm-card">
            <a href="dst_crm_view.php?id=<?php echo urlencode($id); ?>" class="text-reset">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <div class="crm-k">Enquiry</div>
                  <div class="h6 mb-0 fw-extrabold"><?php echo h($title); ?></div>
                </div>
                <span class="badge badge-src" style="<?php echo h($srcStyle); ?>"><?php echo h($srcText); ?></span>
              </div>

              <div class="row g-2 my-2">
                <div class="col-6">
                  <div class="crm-k">My Status</div>
                  <div class="crm-v"><?php echo h($status ?: '—'); ?></div>
                </div>
                <div class="col-6">
                  <div class="crm-k">PP Status</div>
                  <div class="crm-v"><?php echo h($pp ?: '—'); ?></div>
                </div>
              </div>

              <div class="d-flex justify-content-between align-items-center">
                <div class="crm-k">Posted on: <strong><?php echo h($posted); ?></strong></div>
              </div>
            </a>

            <div class="crm-actions">
              <a href="<?=h($telHref)?>"  class="crm-cta call qa-out" data-type="call"><i class="fa fa-phone"></i></a>
              <a href="<?=h($waHref)?>"   class="crm-cta wa qa-out"   data-type="whatsapp" target="_blank"><i class="fab fa-whatsapp"></i></a>
              <a href="<?=h($smsHref)?>"  class="crm-cta sms qa-out"  data-type="sms"><i class="fa-regular fa-message"></i></a>
              <a href="<?=h($mailHref)?>" class="crm-cta mail qa-out" data-type="mail"><i class="fa fa-envelope"></i></a>
            </div>

          </div>
        <?php endforeach; } ?>

      </div>
    </div>
  </div>

  <?php include __DIR__.'/footer_mobile.php'; ?>
</div>

<!-- ============================== 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 (optional, silent failure) */
document.querySelectorAll('.qa-out').forEach(a=>{
  a.addEventListener('click', function(){
    const type=this.getAttribute('data-type')||'call';
    const id   = this.closest('.crm-card')?.querySelector('[href*="crm_view.php?id="],[href*="dst_crm_view.php?id="]')?.href.match(/id=(\d+)/)?.[1];
    if(!id) return;
    const payload='ajax=pending&eid='+encodeURIComponent(id)+'&type='+encodeURIComponent(type);
    const url='crm_mobile.php?ajax=pending';
    if(navigator.sendBeacon){
      navigator.sendBeacon(url, new Blob([payload],{type:'application/x-www-form-urlencoded'}));
    } else {
      fetch(url,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:payload}).catch(()=>{});
    }
  }, {passive:true});
});
</script>

<script src="<?php echo h($ASSETS); ?>/js/jquery.js"></script>
<script src="<?php echo h($ASSETS); ?>/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="<?php echo h($ASSETS); ?>/vendor/swiper/swiper-bundle.min.js"></script>
<script src="<?php echo h($ASSETS); ?>/vendor/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.js"></script>
<script src="<?php echo h($ASSETS); ?>/js/dz.carousel.js"></script>
<script src="<?php echo h($ASSETS); ?>/js/settings.js"></script>
<script src="<?php echo h($ASSETS); ?>/js/custom.js"></script>
<?php include __DIR__ . '/dst_focus_helper.php'; ?>
</body>
</html>
