<?php
//dst.php
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'); }
?>

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





<?php
$base_dir = __DIR__ . '/Base';
$static_url = '/brocrm/mobile/assets'; // Ensure this is the correct path

// Include the common navlink content
ob_start();
include "$base_dir/navbar.php"; // This file contains the shared navlink content
$navlink_content = ob_get_clean(); // Capture the navlink content
$page= 'nav';
$fpage= 'foot';

// Optionally define the Hero block content
ob_start();
?>

<!-- ============================ Page Title Start================================== -->
<div class="page-title">
	<div class="container">
		<div class="row">
			<div class="col-lg-12 col-md-12">
				<h2 class="ipt-title">My DST Leads</h2>
				<span class="ipn-subtitle">Lists of My DST Leads</span>
			</div>
		</div>
	</div>
</div>
<!-- ============================ Page Title End ================================== -->

<!-- ============================ Agency List Start ================================== -->
<section>

<div class="container py-4">
  <!-- Search & Filters -->
  <div class="row mb-3">
    <div class="col-12">
      <!-- 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="btn btn-sm btn-outline-secondary me-2'.$active.'" href="'.h($href).'">'.h($label).'</a>';
        };
      ?>
      <div class="mb-3">
        <?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 text-muted fw-bold">Showing <?php echo count($list); ?> of <?php echo (int)$total; ?></div>
    </div>
  </div>

  <!-- CRM Cards Grid -->
  <div class="row g-3">
    <?php if (!$list) { ?>
      <div class="col-12 text-center py-5 text-muted 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['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-12 col-md-6 col-lg-4 col-xl-3">
      <div class="card h-100 shadow-sm">
        <div class="card-body bg-light">
          <a href="dst_crm_view.php?id=<?php echo urlencode($id); ?>" class="text-decoration-none text-dark">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div>
                <div class="text-muted small">Enquiry</div>
                <h5 class="card-title mb-0 fw-bold"><?php echo h($title); ?></h5>
              </div>
              <span class="badge text-white" style="<?php echo h($srcStyle); ?>"><?php echo h($srcText); ?></span>
            </div>

            <div class="row mb-2">
              <div class="col-6">
                <div class="text-muted small">My Status</div>
                <div><?php echo h($status ?: '—'); ?></div>
              </div>
              <div class="col-6">
                <div class="text-muted small">PP Status</div>
                <div><?php echo h($pp ?: '—'); ?></div>
              </div>
            </div>

            <div class="text-muted small">Posted on: <strong><?php echo h($posted); ?></strong></div>
          </a>
        </div>

        <div class="card-footer bg-white border-0 d-flex justify-content-around">
          <a href="<?=h($telHref)?>" class="btn btn-sm btn-primary" data-type="call"><i class="fa fa-phone"></i></a>
          <a href="<?=h($waHref)?>" class="btn btn-sm btn-success" data-type="whatsapp" target="_blank"><i class="fab fa-whatsapp"></i></a>
          <a href="<?=h($smsHref)?>" class="btn btn-sm btn-secondary" data-type="sms"><i class="fa-regular fa-message"></i></a>
          <a href="<?=h($mailHref)?>" class="btn btn-sm btn-dark" data-type="mail"><i class="fa fa-envelope"></i></a>
        </div>
      </div>
    </div>

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

    
    
    
</section>
<!-- ============================ Agency List End ================================== -->

<!-- ============================ Call To Action ================================== -->
<!--<section class="bg-primary call-to-act-wrap">
	<div class="container">
		</?php include "$base_dir/Components/Home/estate-agent.php"; ?>
	</div>
</section> -->
<!-- ============================ Call To Action End ================================== -->


			

<?php
$hero_content = ob_get_clean(); // Capture the hero content

// Include the base template
include "$base_dir/style/base.php";
?>