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

/* --------------------------- Current user/session --------------------------- */
/* EXACTLY like footer_mobile.php / dst.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 `broriser_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,'ex_broker_leads')) {
  http_response_code(200);
  echo "<p style='font:16px/1.4 system-ui;padding:20px'>No <b>leads</b> table found in <b>broriser_onb</b>.</p>";
  exit;
}
if (!col_exists($DB,'ex_broker_leads','assigned_user')) {
  q($DB,"ALTER TABLE `ex_broker_leads` ADD COLUMN `assigned_user` varchar(191) NULL DEFAULT NULL COLLATE utf8mb4_general_ci");
}
if (!col_exists($DB,'ex_broker_leads','empid')) {
  q($DB,"ALTER TABLE `ex_broker_leads` ADD COLUMN `empid` varchar(64) NULL DEFAULT NULL COLLATE utf8mb4_general_ci");
}

/* ------ Resolve EMPID from superadmin if missing in session (failsafe) ------ */
if ($ME_MAIL === '') {
  $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 email FROM broriser_superadmin.users WHERE {$cond} LIMIT 1");
    if (!empty($u['email'])) {
      $ME_MAIL = trim($u['email']);
      $_SESSION['auth']['email'] = $ME_MAIL;
    }
  }
}

/* ------------------------ ACCESS: Employee only (role_id=4) ---------------- */
if ($ROLE_ID !== 4 && $ROLE_NAME !== 'employee') {
  header("Location: /brocrm/login.php?tab=employee&err=only-employee");
  exit;
}
if ($ME_MAIL === '') {
  http_response_code(200);
  echo "<p style='font:16px/1.5 system-ui;padding:20px'>
          Your <b>EMPMAIL</b> is not set. Please contact admin to map your EMPMAIL before claiming leads.
        </p>";
  exit;
}

/* ---------------------------- AJAX: Claim lead ------------------------------ */
if (($_POST['action'] ?? '') === 'claim') {
  header('Content-Type: application/json; charset=utf-8');

  $lead_id = (int)($_POST['id'] ?? 0);
  if ($lead_id <= 0) { echo json_encode(['ok'=>false,'msg'=>'Invalid lead id']); exit; }

  $assignee = $ME_MAIL !== '' ? $ME_MAIL : ('user_'.$ME_ID);
  $sql = "UPDATE `ex_broker_leads`
            SET assigned_user = ?, empid = ?
          WHERE id = ?
            AND (assigned_user IS NULL OR assigned_user = '')";
  $stmt = mysqli_prepare($DB, $sql);
  if (!$stmt) { echo json_encode(['ok'=>false,'msg'=>'Prepare failed: '.mysqli_error($DB)]); exit; }
  mysqli_stmt_bind_param($stmt, "ssi", $assignee, $ME_MAIL, $lead_id);
  $ok = mysqli_stmt_execute($stmt);
  $aff = mysqli_stmt_affected_rows($stmt);
  mysqli_stmt_close($stmt);

  if (!$ok) { echo json_encode(['ok'=>false,'msg'=>'DB error: '.mysqli_error($DB)]); exit; }

  if ($aff > 0) {
    echo json_encode(['ok'=>true,'msg'=>'Lead claimed','redirect'=>'dst.php?focus='.$lead_id.'#lead-'.$lead_id]);
  } else {
    $cur = row($DB, "SELECT assigned_user FROM `ex_broker_leads` WHERE id=".$lead_id." LIMIT 1");
    if ($cur) echo json_encode(['ok'=>false,'msg'=>'Already claimed by '.$cur['assigned_user']]); else echo json_encode(['ok'=>false,'msg'=>'Lead not found']);
  }
  exit;
}

/* ------------------------------ 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", "(assigned_user IS NULL OR assigned_user='')"]; // UNCLAIMED only on claim page

/* 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,'ex_broker_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 */
$dcol = col_exists($DB,'ex_broker_leads','created_at') ? 'created_at'
      : (col_exists($DB,'ex_broker_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 `ex_broker_leads` {$where}")['c'] ?? 0);
$list  = all($DB, "SELECT * FROM `ex_broker_leads` {$where} ORDER BY id DESC LIMIT 50");

/* --------------------------------- Theme/UI -------------------------------- */
?>
<!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>Claim Leads • DST</title>
<style>
:root{
  --bg:#f7fbff; --card:#ffffff; --line:rgba(0,0,0,.08); --muted:#687083; --pri:#2aa5ff; --pri2:#16c5b8;
  --radius:16px;
}
*{box-sizing:border-box}
html,body{margin:0;background:var(--bg);font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial,sans-serif;color:#0b1220}
.container{max-width:1100px;margin:0 auto;padding:16px}
.header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:8px 0 14px}
.h1{font-size:clamp(18px,2.4vw,22px);font-weight:800;margin:0}
.searchbar{display:flex;gap:8px;margin:6px 0 10px}
.searchbar input[type="search"]{flex:1;height:44px;border:1px solid var(--line);border-radius:12px;padding:0 12px;font-size:15px;background:#fff}
.searchbar button{height:44px;border:0;border-radius:12px;padding:0 16px;background:linear-gradient(135deg,var(--pri),var(--pri2));color:#fff;font-weight:800}
.pills{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
.pill{padding:8px 12px;border-radius:999px;border:1px solid var(--line);background:#fff;font-weight:700;font-size:13px;text-decoration:none;color:#0b1220}
.pill.active{background:linear-gradient(135deg,var(--pri),var(--pri2));color:#fff;border-color:transparent}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px}
.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:12px;display:flex;flex-direction:column;gap:10px;box-shadow:0 10px 30px rgba(0,0,0,.06)}
.badge{color:#fff;border-radius:999px;padding:6px 10px;font-weight:700;font-size:12px}
.k{font-size:12px;color:var(--muted)}
.v{font-weight:800}
.row2{display:flex;gap:10px}
.row2>div{flex:1}
.footer{display:flex;align-items:center;justify-content:space-between;gap:10px}
.btn-claim{height:36px;padding:0 14px;border-radius:999px;border:0;font-weight:800;color:#fff;background:linear-gradient(180deg,#06b6d4,#3b82f6);box-shadow:0 4px 14px rgba(59,130,246,.25);cursor:pointer}
.note{font-size:12px;opacity:.8}
.count{font-size:13px;color:#3b4a66;margin:6px 0 12px}
@media (prefers-color-scheme: dark){
  :root{--bg:#0b0e12;--card:#0e1319;--line:rgba(255,255,255,.08);--muted:#9aa3af}
  body{color:#e6e6e6}
  .searchbar input[type="search"], .pill{background:#0f141a;color:#e6e6e6}
}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1 class="h1">Claim Leads (Employee)</h1>
    <div class="k">Logged in as: <b><?php echo h($ME_MAIL ?: $ME_EMPID ?: 'Employee'); ?></b></div>
  </div>

  <form class="searchbar" method="get" action="">
    <input type="hidden" name="df" value="<?php echo h($df); ?>">
    <input type="search" name="q" value="<?php echo h($qtxt); ?>" placeholder="Search name, phone, email, project, source">
    <button type="submit">Search</button>
  </form>

  <?php
    $btn = function($key,$label) use ($df,$qtxt){
      $active = $df===$key ? ' active' : '';
      $href = '?'.http_build_query(['df'=>$key,'q'=>$qtxt]);
      return '<a class="pill'.$active.'" href="'.h($href).'">'.h($label).'</a>';
    };
  ?>
  <div class="pills">
    <?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="count">Showing <?php echo count($list); ?> of <?php echo (int)$total; ?> unclaimed lead(s)</div>

  <?php if (!$list) { ?>
    <div class="card"><div class="k">No unclaimed leads found for the selected filter.</div></div>
  <?php } ?>

  <div class="grid">
    <?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);
    ?>
    <div class="card" id="lead-<?php echo $id; ?>">
      <div style="display:flex;align-items:center;justify-content:space-between;gap:10px">
        <div>
          <div class="k">Enquiry</div>
          <div class="v" style="font-size:16px"><?php echo h($title); ?></div>
        </div>
        <span class="badge" style="<?php echo h($srcStyle); ?>"><?php echo h($srcText); ?></span>
      </div>

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

      <div class="k">Posted on: <b><?php echo h($posted); ?></b></div>

      <div class="footer">
        <button class="btn-claim" data-id="<?php echo $id; ?>">Claim</button>
        <div class="note">Claim to unlock call / WhatsApp / SMS / Mail</div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<script>
(function(){
  function claim(btn){
    var id = btn.getAttribute('data-id');
    if(!id) return;
    btn.disabled = true; btn.textContent = 'Claiming...';
    fetch(location.pathname, {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
      body: new URLSearchParams({action:'claim', id:id})
    }).then(r=>r.json()).then(function(j){
      if(j && j.ok){
        window.location.href = j.redirect || ('dst.php?focus='+id+'#lead-'+id);
      }else{
        alert((j && j.msg) ? j.msg : 'Failed to claim.');
        btn.disabled = false; btn.textContent = 'Claim';
      }
    }).catch(function(){
      alert('Network error');
      btn.disabled = false; btn.textContent = 'Claim';
    });
  }
  document.addEventListener('click', function(e){
    var t = e.target.closest('.btn-claim');
    if(t) claim(t);
  }, {passive:true});
})();
</script>
</body>
</html>
