<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/initialize.php'; // $con, csrf_token(), verify_csrf()
require_login();

/* ---------- helpers ---------- */
function clean($v){ return trim((string)$v); }
function keep_params(array $changes = []) {
  $qs = $_GET;
  foreach ($changes as $k=>$v) { if ($v===null) unset($qs[$k]); else $qs[$k]=$v; }
  $q = http_build_query($qs);
  return $q ? ('?'.$q) : '';
}
function col_exists(mysqli $con, $table, $col){
  $c = mysqli_real_escape_string($con,$col);
  $t = mysqli_real_escape_string($con,$table);
  $r = mysqli_query($con,"SHOW COLUMNS FROM `$t` LIKE '$c'");
  return ($r && mysqli_num_rows($r)>0);
}
function ensure_schema(mysqli $con, $table){
  if(!col_exists($con,$table,'status')){
    @mysqli_query($con,"ALTER TABLE `$table` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  }
  if(!col_exists($con,$table,'orderby')){
    @mysqli_query($con,"ALTER TABLE `$table` ADD `orderby` INT NOT NULL DEFAULT 0");
  }
  // Ensure location columns exist (if missing)
  $adds = [
    'country'  => "ADD `country` VARCHAR(120) NULL",
    'state'    => "ADD `state` VARCHAR(120) NULL",
    'district' => "ADD `district` VARCHAR(120) NULL",
    // city_id exists already
  ];
  foreach($adds as $col=>$sql){
    if(!col_exists($con,$table,$col)){
      @mysqli_query($con,"ALTER TABLE `$table` $sql");
    }
  }
}
function back_to_list($msg){
  $q = $_GET; unset($q['add'],$q['edit']); $q['ok']=$msg;
  $self = $_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? '';
  $path = $self . ($q ? ('?'.http_build_query($q)) : '');
  if (session_status() === PHP_SESSION_ACTIVE) @session_write_close();
  while (ob_get_level() > 0) { @ob_end_clean(); }
  if (!headers_sent()) {
    header('Cache-Control: no-store');
    header('Location: '.$path, true, 303);
    exit;
  }
  echo '<script>location.replace('.json_encode($path).');</script>';
  echo '<noscript><meta http-equiv="refresh" content="0;url='.htmlspecialchars($path,ENT_QUOTES,'UTF-8').'"></noscript>';
  $_GET = $q; $GLOBALS['__force_list__'] = true;
}

function generateRandomCode($length = 4){
  $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  return substr(str_shuffle(str_repeat($chars, $length)), 0, $length);
}
function build_my_referral_code($user_id){
  $secretKey = "MySecretKey123";
  $hashPart  = strtoupper(substr(md5($secretKey . $user_id), 0, 8));
  $randomPart = generateRandomCode(4);
  return "REFPAC-$hashPart-$randomPart";
}

/* ---------- config ---------- */
$page_title = 'Create Promoter User';
$TABLE      = 'jos_app_promoter_profile';
$USER_TABLE = 'jos_app_users';
$PT_TABLE   = 'jos_app_profile_types';
$SUB_LOG    = 'jos_app_usersubscriptionlog';
$PLAN_TABLE = 'jos_app_subscription_plans';
$PROMOTER_DEFAULT_PLAN_ID = 10;

ensure_schema($con,$TABLE);

/* ---------- permissions ---------- */
function _session_permissions(){
  if(!empty($_SESSION['admin_permissions']) && is_array($_SESSION['admin_permissions'])) return $_SESSION['admin_permissions'];
  return null;
}
function user_can($cap){
  $perms = _session_permissions();
  if($perms === null) return true;
  return in_array($cap, $perms, true);
}
$can_view   = user_can('promoter.view');
$can_add    = user_can('promoter.add');
$can_edit   = user_can('promoter.edit');
$can_delete = user_can('promoter.delete');

if (!$can_view) {
  http_response_code(403);
  die('<!doctype html><meta charset="utf-8"><title>Forbidden</title>
       <div style="font:14px system-ui;padding:24px;color:#e11d48;background:#0b1220">
         You are not authorized to view this content.
       </div>');
}

/* ---------- AJAX: check mobile (Add flow) ---------- */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['ajax'] ?? '') === 'check_mobile') {
  header('Content-Type: application/json');

  if (function_exists('verify_csrf')) {
    $token = $_POST['csrf'] ?? ($_POST['csrf_token'] ?? null);
    $res = @verify_csrf($token);
    if ($res === false) {
      echo json_encode(["status"=>false,"message"=>"Invalid request."]);
      exit;
    }
  }

  $mobile = preg_replace('/\D+/', '', (string)($_POST['mobile_no'] ?? ''));
  if ($mobile==='' || strlen($mobile) !== 10) {
    echo json_encode(["status"=>false,"message"=>"Mobile must be exactly 10 digits."]);
    exit;
  }

  $stmt = $con->prepare("
    SELECT
      u.id,
      u.mobile_no,
      u.profile_type_id,
      pt.profile_name AS profile_type_name,
      u.myreferral_code,
      u.status_id,
      u.created_at
    FROM `$USER_TABLE` u
    LEFT JOIN `$PT_TABLE` pt ON pt.id = u.profile_type_id
    WHERE u.mobile_no=?
    LIMIT 1
  ");
  $stmt->bind_param("s",$mobile);
  $stmt->execute();
  $user = $stmt->get_result()->fetch_assoc();
  $stmt->close();

  $p = null;
  $st2 = $con->prepare("SELECT id, name, userid, status FROM `$TABLE` WHERE mobile_no=? ORDER BY id DESC LIMIT 1");
  $st2->bind_param("s",$mobile);
  $st2->execute();
  $p = $st2->get_result()->fetch_assoc();
  $st2->close();

  if ($user) {
    echo json_encode([
      "status"=>true,
      "can_create"=>false,
      "message"=>"This mobile is already registered in users. Promoter creation blocked.",
      "user"=>$user,
      "promoter_profile"=>$p
    ]);
    exit;
  }

  echo json_encode([
    "status"=>true,
    "can_create"=>true,
    "message"=>"Mobile is available. You can continue.",
    "promoter_profile"=>$p
  ]);
  exit;
}

/* ---------- POST ---------- */
$err=''; $ok='';
if ($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST['ajax'])){

  if (function_exists('verify_csrf')) {
    $token = $_POST['csrf'] ?? ($_POST['csrf_token'] ?? null);
    $res = @verify_csrf($token);
    if ($res === false) $err = 'Invalid request.';
  }

  if ($err==='') {

    /* ---- SAVE ---- */
    if (isset($_POST['save'])) {

      $id        = (int)($_POST['id'] ?? 0);
      $name      = clean($_POST['name'] ?? '');
      $mobile    = preg_replace('/\D+/', '', (string)($_POST['mobile_no'] ?? ''));
      $pan_no    = clean($_POST['pan_no'] ?? '');
      $country   = clean($_POST['country'] ?? '');
      $state     = clean($_POST['state'] ?? '');
      $district  = clean($_POST['district'] ?? '');
      $city      = clean($_POST['city'] ?? '');
      $status    = (int)($_POST['status'] ?? 1);

      $pass   = (string)($_POST['password'] ?? '');
      $cpass  = (string)($_POST['confirm_password'] ?? '');

      $mobile_verified = (int)($_POST['mobile_verified'] ?? 0);

      if ($id===0 && !$can_add)  { http_response_code(403); die('Forbidden'); }
      if ($id>0  && !$can_edit) { http_response_code(403); die('Forbidden'); }

      if ($mobile==='' || strlen($mobile)!==10) $err='Mobile must be exactly 10 digits.';
      elseif ($id===0 && $mobile_verified !== 1) $err='Please click GO to verify mobile first.';
      elseif ($id===0 && $name==='') $err='Name is required.';
      elseif ($id===0 && $pass==='') $err='Password is required for new promoter.';
      elseif ($pass!=='' && $pass!==$cpass) $err='Passwords do not match.';
      else {
        $con->begin_transaction();
        try {

          /* ---- EDIT ---- */
          if ($id>0){
            if ($name==='') throw new Exception('Name is required.');

            $st = $con->prepare("UPDATE `$TABLE`
              SET name=?, mobile_no=?, pan_no=?, country=?, state=?, district=?, city_id=?, status=?
              WHERE id=?");
            if(!$st) throw new Exception($con->error);

            // ✅ correct binding: last param is $id (NOT orderby)
            $st->bind_param("sssssssii", $name,$mobile,$pan_no,$country,$state,$district,$city,$status,$id);

            $st->execute();
            if($st->errno) throw new Exception($st->error);
            $st->close();

            // Sync linked user + optional password update
            $q = $con->prepare("SELECT userid FROM `$TABLE` WHERE id=? LIMIT 1");
            $q->bind_param("i",$id);
            $q->execute();
            $urow = $q->get_result()->fetch_assoc();
            $q->close();

            $uid = (int)($urow['userid'] ?? 0);
            if ($uid>0){
              $user_status_id = ($status==1) ? 1 : 0;

              $uu = $con->prepare("UPDATE `$USER_TABLE` SET mobile_no=?, city_id=?, status_id=? WHERE id=?");
              if(!$uu) throw new Exception($con->error);
              $uu->bind_param("ssii",$mobile,$city,$user_status_id,$uid);
              $uu->execute();
              if($uu->errno) throw new Exception($uu->error);
              $uu->close();

              if ($pass!==''){
                $hp = password_hash($pass, PASSWORD_BCRYPT);
                $pw = $con->prepare("UPDATE `$USER_TABLE` SET password=? WHERE id=?");
                if(!$pw) throw new Exception($con->error);
                $pw->bind_param("si",$hp,$uid);
                $pw->execute();
                if($pw->errno) throw new Exception($pw->error);
                $pw->close();
              }
            }

            $con->commit();
            back_to_list('Updated successfully');
          }

          /* ---- ADD NEW ---- */

          // Block if already exists in users
          $chk = $con->prepare("SELECT id FROM `$USER_TABLE` WHERE mobile_no=? LIMIT 1");
          if(!$chk) throw new Exception($con->error);
          $chk->bind_param("s",$mobile);
          $chk->execute();
          $ex = $chk->get_result()->fetch_assoc();
          $chk->close();
          if ($ex) throw new Exception("This mobile number is already registered. Cannot create promoter for existing user.");

          // next orderby
          $rb = mysqli_query($con,"SELECT IFNULL(MAX(orderby),0)+1 AS nexto FROM `$TABLE`");
          $orderby = ($rb && ($row=mysqli_fetch_assoc($rb))) ? (int)$row['nexto'] : 1;

          // Insert promoter profile
          $st = $con->prepare("INSERT INTO `$TABLE`
            (name,mobile_no,profile_photo,pan_no,country,state,district,city_id,latitude,longitude,status,orderby)
            VALUES (?,?,'',?,?,?,?,?,NULL,NULL,?,?)");
          if(!$st) throw new Exception($con->error);

          // ✅ correct binding: last param is $orderby (NOT $id)
          $st->bind_param("sssssssii", $name,$mobile,$pan_no,$country,$state,$district,$city,$status,$orderby);

          $st->execute();
          if($st->errno) throw new Exception($st->error);
          $profile_id = (int)$st->insert_id;
          $st->close();

          // Create new user
          $hashed_password = password_hash($pass, PASSWORD_BCRYPT);
          $profile_type_id = 3;
          $referred_by     = 0;
          $referral_code   = '';
          $fcm_token       = '';
          $active_plan_id  = $PROMOTER_DEFAULT_PLAN_ID;
          $user_status_id  = ($status==1) ? 1 : 0;

          $ins = $con->prepare("
            INSERT INTO `$USER_TABLE`
              (mobile_no, password, profile_type_id, profile_id, city_id, latitude, longitude,
               referral_code, referred_by, active_plan_id, fcm_token, status_id, created_at)
            VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, NOW())
          ");
          if(!$ins) throw new Exception($con->error);

          // ✅ correct types (10 params)
          $ins->bind_param(
            "ssiissiisi",
            $mobile,
            $hashed_password,
            $profile_type_id,
            $profile_id,
            $city,
            $referral_code,
            $referred_by,
            $active_plan_id,
            $fcm_token,
            $user_status_id
          );

          $ins->execute();
          if($ins->errno) throw new Exception($ins->error);
          $user_id = (int)$ins->insert_id;
          $ins->close();

          // myreferral_code
          $myref = build_my_referral_code($user_id);
          $upd = $con->prepare("UPDATE `$USER_TABLE` SET myreferral_code=? WHERE id=?");
          $upd->bind_param("si",$myref,$user_id);
          $upd->execute();
          $upd->close();

          // Backfill userid in promoter profile
          $up = $con->prepare("UPDATE `$TABLE` SET userid=? WHERE id=?");
          if(!$up) throw new Exception($con->error);
          $up->bind_param("ii",$user_id,$profile_id);
          $up->execute();
          $up->close();

          // Free subscription log (insert only if not exists)
          $planq = $con->prepare("SELECT validity_months FROM `$PLAN_TABLE` WHERE id=? LIMIT 1");
          $planq->bind_param("i",$PROMOTER_DEFAULT_PLAN_ID);
          $planq->execute();
          $planres = $planq->get_result()->fetch_assoc();
          $planq->close();

          if ($planres){
            $validity_months = (int)$planres['validity_months'];

            $existsSub = $con->prepare("SELECT 1 FROM `$SUB_LOG`
                                        WHERE userid=? AND plan_id=? AND profile_type_id=3 AND profile_id=? AND payment_id='free_signup'
                                        LIMIT 1");
            $existsSub->bind_param("iii",$user_id,$PROMOTER_DEFAULT_PLAN_ID,$profile_id);
            $existsSub->execute();
            $es = $existsSub->get_result()->fetch_assoc();
            $existsSub->close();

            if (!$es){
              $current_year = date('Y');
              $invoice_prefix = 'APP'.$current_year.'-';
              $res = mysqli_query($con,"SELECT MAX(CAST(SUBSTRING(invoiceno, LENGTH('$invoice_prefix')+1) AS UNSIGNED)) AS max_invoice
                                        FROM `$SUB_LOG` WHERE invoiceno LIKE '$invoice_prefix%'");
              $last_invoice = ($res && ($row=mysqli_fetch_assoc($res))) ? (int)$row['max_invoice'] : 0;
              $new_invoiceno = $invoice_prefix . str_pad($last_invoice+1,5,'0',STR_PAD_LEFT);

              $sub = $con->prepare("INSERT INTO `$SUB_LOG`
                (userid,plan_id,start_date,end_date,payment_status,amount_paid,payment_id,invoiceno,profile_type_id,profile_id)
                VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ? MONTH), 'success', 0, 'free_signup', ?, 3, ?)");
              $sub->bind_param("iiisi",$user_id,$PROMOTER_DEFAULT_PLAN_ID,$validity_months,$new_invoiceno,$profile_id);
              $sub->execute();
              $sub->close();
            }
          }

          $con->commit();
          back_to_list('Added successfully');

        } catch (Exception $e){
          $con->rollback();
          $err = 'Save failed: '.$e->getMessage();
        }
      }
    }

    /* ---- DELETE ---- */
    if (isset($_POST['delete'])) {
      if (!$can_delete) { http_response_code(403); die('Forbidden'); }
      $id=(int)($_POST['id'] ?? 0);
      if ($id>0){
        $con->begin_transaction();
        try {
          $g = $con->prepare("SELECT userid FROM `$TABLE` WHERE id=? LIMIT 1");
          $g->bind_param("i",$id);
          $g->execute();
          $urow = $g->get_result()->fetch_assoc();
          $g->close();

          $linked_uid = (int)($urow['userid'] ?? 0);

          if ($linked_uid>0){
            $delSub = $con->prepare("DELETE FROM `$SUB_LOG` WHERE userid=? AND profile_type_id=3 AND profile_id=?");
            $delSub->bind_param("ii",$linked_uid,$id);
            $delSub->execute();
            $delSub->close();

            $delUser = $con->prepare("DELETE FROM `$USER_TABLE` WHERE id=? AND profile_type_id=3 AND profile_id=?");
            $delUser->bind_param("ii",$linked_uid,$id);
            $delUser->execute();
            $delUser->close();
          }

          $delProm = $con->prepare("DELETE FROM `$TABLE` WHERE id=?");
          $delProm->bind_param("i",$id);
          $delProm->execute();
          $delProm->close();

          $con->commit();
          back_to_list('Deleted successfully');
        } catch (Exception $e){
          $con->rollback();
          $err = 'Delete failed: '.$e->getMessage();
        }
      }
    }

  }
}

/* ---------- mode & edit row ---------- */
$mode = (isset($_GET['edit']) || isset($_GET['add'])) ? 'form' : 'list';
if (!empty($GLOBALS['__force_list__'])) $mode = 'list';

$edit=null;
if ($mode==='form' && isset($_GET['edit'])){
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT id,name,mobile_no,pan_no,country,state,district,city_id,status FROM `$TABLE` WHERE id=?");
  $st->bind_param("i",$eid);
  $st->execute();
  $edit = $st->get_result()->fetch_assoc();
  $st->close();
}

/* ---------- filters ---------- */
$q   = clean($_GET['q'] ?? '');
$sfl = isset($_GET['status']) ? (string)$_GET['status'] : '';
$all = isset($_GET['all']); $lim = $all ? 0 : 50;

$where=" WHERE 1=1 ";
$type=''; $bind=[];
if ($q!==''){
  $where.=" AND (name LIKE ? OR mobile_no LIKE ? OR pan_no LIKE ? OR city_id LIKE ? OR country LIKE ? OR state LIKE ? OR district LIKE ?)";
  $like="%$q%";
  $type.='sssssss'; $bind[]=$like; $bind[]=$like; $bind[]=$like; $bind[]=$like; $bind[]=$like; $bind[]=$like; $bind[]=$like;
}
if ($sfl==='1' || $sfl==='0'){
  $where.=" AND status = ?";
  $type.='i'; $bind[]=(int)$sfl;
}

/* ---------- count / list ---------- */
$count_sql="SELECT COUNT(*) c FROM `$TABLE` $where";
$st=$con->prepare($count_sql);
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$total=(int)$st->get_result()->fetch_assoc()['c'];
$st->close();

$list_sql="SELECT id,name,mobile_no,pan_no,country,state,district,city_id,orderby,status
           FROM `$TABLE`
           $where
           ORDER BY orderby ASC, id DESC";
if (!$all) $list_sql.=" LIMIT $lim";

$st=$con->prepare($list_sql);
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$rs=$st->get_result();
$rows=[];
while($r=$rs->fetch_assoc()) $rows[]=$r;
$st->close();

/* ---------- view ---------- */
ob_start(); ?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title><?=htmlspecialchars($page_title)?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <style>
    .pw-wrap{ position:relative; }
    .pw-wrap .inp{ padding-right:44px; }
    .pw-toggle{
      position:absolute; right:10px; top:50%; transform:translateY(-50%);
      width:30px; height:30px; border:0; background:transparent; cursor:pointer;
      display:flex; align-items:center; justify-content:center;
      color:#9ca3af;
    }
    .pw-toggle:hover{ color:#e5e7eb; }
    .pw-toggle svg{ width:18px; height:18px; }

    .table-wrap{ overflow:auto; }
    .table{ min-width: 1100px; }
    dialog::backdrop{ background: rgba(0,0,0,.55); }
    .dlg{ max-width: 760px; width: 92%; border: 1px solid #1f2937; border-radius: 14px; padding: 0; background: #0b1220; color: #e5e7eb; }
    .dlg-head{ padding: 14px 16px; border-bottom: 1px solid #1f2937; display:flex; justify-content:space-between; align-items:center; gap:10px; }
    .dlg-body{ padding: 16px; }
    .kv{ display:grid; grid-template-columns: 1fr 1fr; gap:10px; }
    .kv > div{ padding: 10px; border: 1px solid #1f2937; border-radius: 10px; min-width:0; }
    .kv .k{ color:#9ca3af; font-size:12px; margin-bottom:4px; }
    .kv .v{ font-weight:600; word-break:break-word; }
    @media (max-width:640px){ .kv{ grid-template-columns:1fr; } }
  </style>
</head>
<body>
<div class="master-wrap">
  <div class="headbar"><h2 style="margin:0"><?=htmlspecialchars($page_title)?></h2></div>

  <?php if ($mode==='list'): ?>
    <?php if (!empty($_GET['ok'])): ?>
      <div class="alert ok" style="margin:12px 0"><?=htmlspecialchars($_GET['ok'])?></div>
    <?php endif; ?>
    <?php if ($err): ?>
      <div class="alert err" style="margin:12px 0"><?=htmlspecialchars($err)?></div>
    <?php endif; ?>

    <div class="card">
      <div class="toolbar">
        <form method="get" class="search">
          <input type="text" name="q" class="inp" placeholder="Search..." value="<?=htmlspecialchars($q)?>">
          <select name="status" class="inp">
            <option value="">All status</option>
            <option value="1" <?=$sfl==='1'?'selected':''?>>Active</option>
            <option value="0" <?=$sfl==='0'?'selected':''?>>Inactive</option>
          </select>
          <button class="btn gray" type="submit">Search</button>

          <?php if(!$all && $total>$lim): ?>
            <a class="btn gray" href="<?=htmlspecialchars(keep_params(['all'=>1]))?>">View All (<?=$total?>)</a>
          <?php endif; ?>
          <?php if($all): ?>
            <a class="btn gray" href="<?=htmlspecialchars(keep_params(['all'=>null]))?>">Last 50</a>
          <?php endif; ?>
        </form>

        <?php if ($can_add): ?>
          <a class="btn green" href="<?=htmlspecialchars(keep_params(['add'=>1]))?>">Add Promoter</a>
        <?php endif; ?>
      </div>

      <div style="margin:8px 0;color:#9ca3af">
        Showing <strong><?= !$all ? count($rows) : $total ?></strong> of <strong><?= $total ?></strong>
        <?= $q!=='' ? 'for “'.htmlspecialchars($q).'”' : '' ?>
      </div>

      <div class="table-wrap">
        <table class="table">
          <thead><tr>
            <th>SR</th>
            <th>Name</th>
            <th>Mobile</th>
            <th>PAN</th>
            <th>Country</th>
            <th>State</th>
            <th>District</th>
            <th>City</th>
            <th>Order</th>
            <th>Status</th>
            <th style="min-width:180px">Actions</th>
          </tr></thead>
          <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="11" style="color:#9ca3af">No records</td></tr>
          <?php endif; ?>
          <?php $sr=0; foreach($rows as $r): $sr++; ?>
            <tr>
              <td><?=$sr?></td>
              <td><?=htmlspecialchars($r['name'])?></td>
              <td><?=htmlspecialchars($r['mobile_no'])?></td>
              <td><?=htmlspecialchars($r['pan_no'])?></td>
              <td><?=htmlspecialchars($r['country'] ?? '')?></td>
              <td><?=htmlspecialchars($r['state'] ?? '')?></td>
              <td><?=htmlspecialchars($r['district'] ?? '')?></td>
              <td><?=htmlspecialchars($r['city_id'])?></td>
              <td><?=htmlspecialchars($r['orderby'])?></td>
              <td><span class="badge <?=$r['status']?'on':'off'?>"><?=$r['status']?'Active':'Inactive'?></span></td>
              <td style="white-space:nowrap">
                <?php if ($can_edit): ?>
                  <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>(int)$r['id'], 'add'=>null]))?>">Edit</a>
                <?php endif; ?>
                <?php if ($can_delete): ?>
                  <form method="post" style="display:inline" onsubmit="return confirm('Delete this promoter and all related records?');">
                    <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
                    <input type="hidden" name="id" value="<?=$r['id']?>">
                    <button class="btn red" name="delete" type="submit">Delete</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php else: /* form mode */ ?>

    <div class="card" style="margin-bottom:16px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;gap:10px;flex-wrap:wrap">
        <h3 style="margin:0"><?= $edit ? 'Edit Promoter' : 'Add Promoter' ?></h3>
        <?php
          $backHref = keep_params(['edit'=>null,'add'=>null]);
          if ($backHref === '?' || $backHref === '') $backHref = $_SERVER['SCRIPT_NAME'] ?? '';
        ?>
        <a class="btn gray" href="<?=htmlspecialchars($backHref)?>">Back to List</a>
      </div>

      <?php if($err): ?><div class="alert err" style="margin:8px 0"><?=htmlspecialchars($err)?></div><?php endif; ?>

      <form method="post" id="promoterForm" style="display:grid;grid-template-columns:1fr 1fr;gap:12px" autocomplete="off">
        <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

        <?php if(!$edit): ?>
          <!-- ADD: Mobile + GO (FIXED: single input with id=mobile_no so JS works) -->
          <div style="grid-column:1/-1">
            <label for="mobile_no">Mobile*</label>

            <div style="display:flex;gap:10px;align-items:center;flex-wrap:nowrap;max-width:520px">
              <input
                id="mobile_no"
                name="mobile_no"
                class="inp"
                inputmode="numeric"
                pattern="[0-9]*"
                maxlength="10"
                minlength="10"
                required
                value="<?=htmlspecialchars($_POST['mobile_no'] ?? '')?>"
                style="flex:1;min-width:240px"
                oninput="this.value=this.value.replace(/\D/g,'').slice(0,10);"
              >
              <button class="btn gray" type="button" id="btnGo" style="white-space:nowrap;min-width:56px">GO</button>
            </div>

            <div id="goMsg" style="margin-top:6px;color:#9ca3af;font-size:13px"></div>
            <input type="hidden" name="mobile_verified" id="mobile_verified" value="<?= (int)($_POST['mobile_verified'] ?? 0) ?>">
          </div>

          <div id="moreFields" style="grid-column:1/-1; display:none">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
              <div style="grid-column:1/-1">
                <label>Name*</label>
                <input name="name" class="inp" required value="<?=htmlspecialchars($_POST['name'] ?? '')?>">
              </div>

              <div><label>PAN</label><input name="pan_no" class="inp" value="<?=htmlspecialchars($_POST['pan_no'] ?? '')?>"></div>
              <div><label>Country</label><input name="country" class="inp" value="<?=htmlspecialchars($_POST['country'] ?? '')?>"></div>
              <div><label>State</label><input name="state" class="inp" value="<?=htmlspecialchars($_POST['state'] ?? '')?>"></div>
              <div><label>District</label><input name="district" class="inp" value="<?=htmlspecialchars($_POST['district'] ?? '')?>"></div>
              <div><label>City</label><input name="city" class="inp" value="<?=htmlspecialchars($_POST['city'] ?? '')?>"></div>

              <div>
                <label>Status</label>
                <?php $st = (int)($_POST['status'] ?? 1); ?>
                <select name="status" class="inp">
                  <option value="1" <?=$st===1?'selected':''?>>Active</option>
                  <option value="0" <?=$st===0?'selected':''?>>Inactive</option>
                </select>
              </div>

              <div class="pw-wrap">
                <label>Password*</label>
                <input id="password" name="password" type="password" class="inp" required>
                <button type="button" class="pw-toggle" data-target="password" aria-label="Show/Hide password">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                  </svg>
                </button>
              </div>

              <div class="pw-wrap">
                <label>Confirm Password*</label>
                <input id="confirm_password" name="confirm_password" type="password" class="inp" required>
                <button type="button" class="pw-toggle" data-target="confirm_password" aria-label="Show/Hide confirm password">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                  </svg>
                </button>
              </div>
            </div>

            <div style="margin-top:12px">
              <button class="btn green" name="save" type="submit">Save</button>
            </div>
          </div>

        <?php else: ?>
          <!-- EDIT (unchanged logic) -->
          <div style="grid-column:1/-1">
            <label>Name*</label>
            <input name="name" class="inp" required value="<?=htmlspecialchars($edit['name'] ?? '')?>">
          </div>

          <div>
            <label>Mobile*</label>
            <input name="mobile_no" class="inp" inputmode="numeric" pattern="[0-9]*"
                   maxlength="10" minlength="10" required
                   value="<?= htmlspecialchars($edit['mobile_no'] ?? '') ?>"
                   oninput="this.value=this.value.replace(/\D/g,'').slice(0,10);">
          </div>

          <div><label>PAN</label><input name="pan_no" class="inp" value="<?=htmlspecialchars($edit['pan_no'] ?? '')?>"></div>

          <div><label>Country</label><input name="country" class="inp" value="<?=htmlspecialchars($edit['country'] ?? '')?>"></div>
          <div><label>State</label><input name="state" class="inp" value="<?=htmlspecialchars($edit['state'] ?? '')?>"></div>
          <div><label>District</label><input name="district" class="inp" value="<?=htmlspecialchars($edit['district'] ?? '')?>"></div>
          <div><label>City</label><input name="city" class="inp" value="<?=htmlspecialchars($edit['city_id'] ?? '')?>"></div>

          <div>
            <label>Status</label>
            <?php $st = isset($edit['status']) ? (int)$edit['status'] : 1; ?>
            <select name="status" class="inp">
              <option value="1" <?=$st===1?'selected':''?>>Active</option>
              <option value="0" <?=$st===0?'selected':''?>>Inactive</option>
            </select>
          </div>

          <div class="pw-wrap">
            <label>New Password (optional)</label>
            <input id="password_edit" name="password" type="password" class="inp">
            <button type="button" class="pw-toggle" data-target="password_edit" aria-label="Show/Hide password">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"></path>
                <circle cx="12" cy="12" r="3"></circle>
              </svg>
            </button>
          </div>

          <div class="pw-wrap">
            <label>Confirm New Password</label>
            <input id="confirm_password_edit" name="confirm_password" type="password" class="inp">
            <button type="button" class="pw-toggle" data-target="confirm_password_edit" aria-label="Show/Hide confirm password">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"></path>
                <circle cx="12" cy="12" r="3"></circle>
              </svg>
            </button>
          </div>

          <div style="grid-column:1/-1">
            <button class="btn green" name="save" type="submit">Save</button>
          </div>
        <?php endif; ?>
      </form>
    </div>

    <dialog id="existUserDlg" class="dlg">
      <div class="dlg-head">
        <strong>Existing user found</strong>
        <button type="button" class="btn gray" id="dlgCloseBtn">Close</button>
      </div>
      <div class="dlg-body">
        <div class="alert err" style="margin:0 0 12px 0">
          This mobile number is already registered in users. Promoter creation is blocked for this mobile.
        </div>
        <div id="existUserInfo" class="kv"></div>
        <div style="margin-top:10px;color:#9ca3af;font-size:13px">
          Please use another mobile number to create promoter.
        </div>
      </div>
    </dialog>

    <script>
    (function(){
      const editMode = <?= $edit ? 'true' : 'false' ?>;
      if(editMode) return;

      const btnGo = document.getElementById('btnGo');
      const inp = document.getElementById('mobile_no');
      const msg = document.getElementById('goMsg');
      const verified = document.getElementById('mobile_verified');
      const more = document.getElementById('moreFields');

      const dlg = document.getElementById('existUserDlg');
      const info = document.getElementById('existUserInfo');
      const closeBtn = document.getElementById('dlgCloseBtn');

      function kv(k,v){
        const d = document.createElement('div');
        d.innerHTML = '<div class="k">'+k+'</div><div class="v">'+(v ?? '')+'</div>';
        return d;
      }
      function showDlg(){
        if(dlg && typeof dlg.showModal === 'function') dlg.showModal();
        else alert('Existing user found. Please use another mobile number.');
      }
      function formatDMY(dt){
        if(!dt) return '';
        const t = String(dt).replace(' ', 'T');
        const d = new Date(t);
        if(isNaN(d.getTime())){
          const m = String(dt).match(/^(\d{4})-(\d{2})-(\d{2})/);
          if(m) return `${m[3]}-${m[2]}-${m[1]}`;
          return String(dt);
        }
        const dd = String(d.getDate()).padStart(2,'0');
        const mm = String(d.getMonth()+1).padStart(2,'0');
        const yy = d.getFullYear();
        return `${dd}-${mm}-${yy}`;
      }

      if(closeBtn) closeBtn.onclick = ()=> dlg.close();

      inp.addEventListener('input', ()=>{
        verified.value = '0';
        more.style.display = 'none';
        msg.textContent = '';
      });

      if(verified.value === '1'){
        more.style.display = '';
        msg.textContent = 'Verified';
      }

      btnGo.addEventListener('click', async ()=>{
        const mobile = (inp.value || '').replace(/\D+/g,'').slice(0,10);
        if(mobile.length !== 10){
          msg.textContent = '';
          alert('Enter valid 10 digit mobile');
          inp.focus();
          return;
        }

        msg.textContent = 'Checking...';
        const fd = new FormData();
        fd.append('ajax','check_mobile');
        fd.append('mobile_no', mobile);
        fd.append('csrf', <?= json_encode(csrf_token()) ?>);

        let js;
        try{
          const res = await fetch(window.location.href, {method:'POST', body: fd});
          js = await res.json();
        }catch(e){
          msg.textContent = '';
          alert('Network/Server error');
          return;
        }

        if(!js || js.status !== true){
          msg.textContent = '';
          alert((js && js.message) ? js.message : 'Check failed');
          return;
        }

        if(js.can_create){
          verified.value = '1';
          more.style.display = '';
          msg.textContent = 'Verified. Continue.';
          const first = more.querySelector('input[name="name"]');
          if(first) first.focus();
          return;
        }

        verified.value = '0';
        more.style.display = 'none';
        msg.textContent = 'Already registered';

        info.innerHTML = '';
        const u = js.user || {};
        const statusTxt = (String(u.status_id) === '1') ? 'Active' : 'Inactive';

        info.appendChild(kv('User ID', u.id));
        info.appendChild(kv('Mobile', u.mobile_no));
        info.appendChild(kv('Profile Type', u.profile_type_name || ('ID ' + (u.profile_type_id || ''))));
        info.appendChild(kv('Status', statusTxt));
        info.appendChild(kv('Date of Signup', formatDMY(u.created_at)));
        info.appendChild(kv('My Referral Code', u.myreferral_code));

        const p = js.promoter_profile || null;
        info.appendChild(kv('Promoter Profile Exists', p ? 'Yes' : 'No'));

        showDlg();
      });

      const form = document.getElementById('promoterForm');
      form.addEventListener('submit', (e)=>{
        if(verified.value !== '1'){
          e.preventDefault();
          alert('Please click GO to verify mobile first.');
          return;
        }
      });
    })();
    </script>

    <script>
      document.addEventListener('click', function(e){
        const btn = e.target.closest('.pw-toggle');
        if(!btn) return;

        const id = btn.getAttribute('data-target');
        const input = document.getElementById(id);
        if(!input) return;

        input.type = (input.type === 'password') ? 'text' : 'password';
      });
    </script>

  <?php endif; ?>
</div>
</body>
</html>
<?php
echo ob_get_clean();
