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

require_once __DIR__ . '/../includes/auth.php';  require_login();
require_once __DIR__ . '/../includes/initialize.php'; // $con (mysqli)

/* ===========================================================
  Coupon Codes Master (Enhanced)
  Table: jos_app_couponcodes
  Fields used here:
    - coupon_code (unique label)
    - discount_type (percentage|flat)
    - discount_value (decimal)
    - expiry_date (YYYY-MM-DD)
    - profile_type_id (FK -> jos_app_profile_types.id)
    - max_usage_limit (int)
    - used_count (int, read-only on UI)
    - user_id (int, nullable)  <-- user-specific coupons (jos_app_users.id)
    - status (1/0)
    - created_by_userid, created_at, updated_at (auto)

  User / profile mapping:
    jos_app_users.profile_type_id:
      1 => Recruiter       -> jos_app_recruiter_profile (organization_name, mobile_no)
      2 => Candidate       -> jos_app_candidate_profile (candidate_name, mobile_no)
      3 => Promoter        -> jos_app_promoter_profile  (name, mobile_no)
   =========================================================== */

$DEFAULT_PAGE_TITLE = 'Coupon Codes';
$TABLE      = 'jos_app_couponcodes';
$LABEL_COL  = 'coupon_code';
$STATUS_COL = 'status';
$ORDER_COL  = 'id'; // keep id as order for consistency

/* ---------- helpers ---------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
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 clean($v){ return trim((string)$v); }

/* SHOW COLUMNS cannot be prepared; escape and run directly. */
function col_exists(mysqli $con, string $table, string $col): bool {
  $table = preg_replace('/[^a-zA-Z0-9_]/','', $table);
  $col   = $con->real_escape_string($col);
  $sql   = "SHOW COLUMNS FROM `{$table}` LIKE '{$col}'";
  $res   = $con->query($sql);
  return ($res && $res->fetch_assoc()) ? true : false;
}

/* ensure schema (status/order columns) — safe if they already exist */
function ensure_schema(mysqli $con, string $table, string $statusCol, string $orderCol){
  if (!col_exists($con,$table,$statusCol))  {
    $con->query("ALTER TABLE `{$table}` ADD `{$statusCol}` TINYINT DEFAULT 1");
  }
  if (!col_exists($con,$table,$orderCol) && strtolower($orderCol)!=='id'){
    $con->query("ALTER TABLE `{$table}` ADD `{$orderCol}` INT DEFAULT 0");
    $con->query("ALTER TABLE `{$table}` MODIFY `{$orderCol}` INT DEFAULT 0");
  }
}

/* ensure user column (user-specific coupons) */
function ensure_user_column(mysqli $con, string $table, string $userCol = 'user_id'){
  if (!col_exists($con,$table,$userCol)) {
    $con->query("ALTER TABLE `{$table}` ADD `{$userCol}` INT NULL DEFAULT 0");
  }
}

/* CSRF helpers (define if missing) */
if (!function_exists('csrf_token')) {
  function csrf_token(){
    if (session_status()!==PHP_SESSION_ACTIVE) session_start();
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
    return $_SESSION['csrf'];
  }
}
if (!function_exists('verify_csrf')) {
  function verify_csrf($t){
    return (session_status()===PHP_SESSION_ACTIVE
            && !empty($_SESSION['csrf'])
            && hash_equals($_SESSION['csrf'], (string)$t));
  }
}

/* flash redirect */
function flash_redirect(string $msg='Saved', string $type='ok'){
  $qs = $_GET; unset($qs['add'], $qs['edit']);
  $qs[$type] = $msg;
  header('Location: ?'.http_build_query($qs)); exit;
}

ensure_schema($con, $TABLE, $STATUS_COL, $ORDER_COL);
ensure_user_column($con, $TABLE, 'user_id');

/* ---------- lookups: profile types ---------- */
$PROFILE_TABLE = 'jos_app_profile_types'; // id, profile_name
$profiles = [];
$qr = $con->query("SELECT id, profile_name AS name FROM `$PROFILE_TABLE` ORDER BY profile_name ASC");
if ($qr) while ($r = $qr->fetch_assoc()) { $profiles[(int)$r['id']] = $r['name'] ?: ('#'.$r['id']); }

/* ---------- load users + names from profile tables ----------
   Base table: jos_app_users (id, mobile_no, profile_type_id, profile_id, ...)
   Joins:
     - profile_type_id = 2 -> jos_app_candidate_profile (userid)
     - profile_type_id = 1 -> jos_app_recruiter_profile (userid)
     - profile_type_id = 3 -> jos_app_promoter_profile  (userid)
---------------------------------------------------------------- */
$USER_TABLE              = 'jos_app_users';
$CANDIDATE_PROFILE_TABLE = 'jos_app_candidate_profile';
$RECRUITER_PROFILE_TABLE = 'jos_app_recruiter_profile';
$PROMOTER_PROFILE_TABLE  = 'jos_app_promoter_profile';

$users         = []; // by id
$users_for_js  = [];

$userSql = "
  SELECT 
    u.id,
    u.profile_type_id,
    u.mobile_no,
    CASE 
      WHEN u.profile_type_id = 2 THEN c.candidate_name
      WHEN u.profile_type_id = 1 THEN r.organization_name
      WHEN u.profile_type_id = 3 THEN p.name
      ELSE NULL
    END AS display_name
  FROM `$USER_TABLE` u
  LEFT JOIN `$CANDIDATE_PROFILE_TABLE` c ON c.userid = u.id
  LEFT JOIN `$RECRUITER_PROFILE_TABLE` r ON r.userid = u.id
  LEFT JOIN `$PROMOTER_PROFILE_TABLE` p  ON p.userid = u.id
  ORDER BY display_name IS NULL, display_name ASC, u.mobile_no ASC
";

if ($ur = $con->query($userSql)) {
  while($u = $ur->fetch_assoc()){
    $id     = (int)$u['id'];
    $ptype  = (int)$u['profile_type_id'];
    $mobile = trim((string)($u['mobile_no'] ?? ''));
    $name   = trim((string)($u['display_name'] ?? ''));

    $labelParts = [];
    if ($name !== '')   $labelParts[] = $name;
    if ($mobile !== '') $labelParts[] = $mobile;
    $label = $labelParts ? implode(' | ', $labelParts) : ('User #'.$id);

    $users[$id] = [
      'id'             => $id,
      'profile_type_id'=> $ptype,
      'label'          => $label,
    ];
    $users_for_js[] = [
      'id'             => $id,
      'profile_type_id'=> $ptype,
      'label'          => $label,
    ];
  }
}

/* ---------- Access control helpers ---------- */
function current_module_key(): string {
  return 'coupon_codes';
}
function has_access(string $action): bool {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  $admin = $_SESSION['admin_user'] ?? null;
  if (!$admin) return true; // no admin info -> do not block (compat)

  $flag = 'can_'.$action.'_'.current_module_key();
  if (isset($admin[$flag])) return (bool)$admin[$flag];

  if (isset($admin['can_'.$action])) return (bool)$admin['can_'.$action];

  if (!empty($admin['permissions']) && is_array($admin['permissions'])) {
    $needleA = current_module_key().'.'.$action;
    $needleB = current_module_key().'_'.$action;
    if (in_array($needleA, $admin['permissions'], true) || in_array($needleB, $admin['permissions'], true)) {
      return true;
    }
    if (in_array($action, $admin['permissions'], true)) return true;
  }

  if (!empty($admin['access']) && is_array($admin['access'])) {
    $mod = current_module_key();
    if (isset($admin['access'][$mod]) && is_array($admin['access'][$mod]) && isset($admin['access'][$mod][$action])) {
      return (bool)$admin['access'][$mod][$action];
    }
  }

  if (!empty($admin['role']) && in_array(strtolower($admin['role']), ['super','superadmin','administrator','admin'], true)) return true;

  return true;
}

/* ---------- load page title from jos_admin_menus ---------- */
function load_title_from_menu(mysqli $con, string $fallback) : string {
  $script = basename($_SERVER['SCRIPT_NAME']);
  $candidates = ['menu_name','title','label','name'];
  $link_cols   = ['menu_link','link','url','file'];
  foreach ($link_cols as $lcol) {
    $lcol_esc = preg_replace('/[^a-zA-Z0-9_]/','',$lcol);
    foreach ($candidates as $c) {
      $c_esc = preg_replace('/[^a-zA-Z0-9_]/','',$c);
      $sql = "SELECT `{$c_esc}` AS label FROM `jos_admin_menus`
              WHERE `{$lcol_esc}` LIKE ? LIMIT 1";
      if ($st = $con->prepare($sql)) {
        $like = '%'.$script.'%';
        $st->bind_param('s',$like);
        if ($st->execute()) {
          $res = $st->get_result();
          if ($row = $res->fetch_assoc()) {
            $st->close();
            return $row['label'] ?: $fallback;
          }
        }
        $st->close();
      }
    }
  }
  return $fallback;
}

$page_title = load_title_from_menu($con, $DEFAULT_PAGE_TITLE);

/* ---------- mode ---------- */
$mode = (isset($_GET['add']) || isset($_GET['edit'])) ? 'form' : 'list';

/* ---------- enforce view permission (UI-level) ---------- */
$can_view   = has_access('view');
$can_add    = has_access('add');
$can_edit   = has_access('edit');
$can_delete = has_access('delete');

if (!$can_view && $mode === 'list') {
  ob_start();
  ?>
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <div class="master-wrap">
    <div class="headbar"><h2><?=h($page_title)?></h2></div>
    <div class="card">
      <div class="err">You do not have permission to view this page.</div>
    </div>
  </div>
  <?php
  echo ob_get_clean();
  exit;
}

/* ---------- POST handler ---------- */
$err = ''; $ok = '';
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? '')) { die('CSRF failed'); }

  if (isset($_POST['save'])){
    // check add/edit permission
    $id = (int)($_POST['id'] ?? 0);
    if ($id>0 && !$can_edit) { $err = 'You do not have permission to edit.'; }
    if ($id===0 && !$can_add) { $err = 'You do not have permission to add.'; }

    $coupon_code     = clean($_POST['coupon_code'] ?? '');
    $discount_type   = strtolower(clean($_POST['discount_type'] ?? 'percentage'));
    $discount_value  = (float)($_POST['discount_value'] ?? 0);
    $expiry_date     = clean($_POST['expiry_date'] ?? ''); // expect YYYY-MM-DD
    $profile_type_id = (int)($_POST['profile_type_id'] ?? 0);
    $max_usage_limit = (int)($_POST['max_usage_limit'] ?? 0);
    $status          = (int)($_POST['status'] ?? 1);
    $user_id         = (int)($_POST['user_id'] ?? 0); // 0 = global coupon

    // basic validations
    if (!$err && $coupon_code==='') $err = 'Coupon Code is required.';
    if (!$err && !in_array($discount_type, ['percentage','flat'], true)) $err = 'Invalid Discount Type.';
    if (!$err && $discount_value < 0) $err = 'Discount Value cannot be negative.';
    if (!$err && $expiry_date!=='' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiry_date)) $err = 'Invalid Expiry Date (use YYYY-MM-DD).';
    if (!$err && $profile_type_id>0 && !isset($profiles[$profile_type_id])) $err = 'Invalid Profile Type.';
    if (!$err && $user_id>0 && !isset($users[$user_id])) $err = 'Invalid User selected.';

    // duplicate check on coupon_code
    if (!$err){
      $sql = "SELECT id FROM $TABLE WHERE LOWER($LABEL_COL)=LOWER(?) ".($id>0?"AND id<>$id":"")." LIMIT 1";
      $st  = $con->prepare($sql); $st->bind_param('s',$coupon_code);
      $st->execute(); $dup = $st->get_result()->fetch_assoc(); $st->close();
      if ($dup) $err = 'Duplicate Coupon Code.';
    }

    // insert / update
    $admin = $_SESSION['admin_user'] ?? [];
    $admin_id = (int)($admin['id'] ?? 0);

    if (!$err){
      if ($id>0){
        if (!$can_edit) { $err = 'You do not have permission to edit.'; }
        else {
          $sql = "UPDATE $TABLE
                  SET coupon_code=?, discount_type=?, discount_value=?, expiry_date=?, profile_type_id=?,
                      max_usage_limit=?, user_id=?, $STATUS_COL=?, updated_at=NOW()
                  WHERE id=?";
          $st = $con->prepare($sql);
          $st->bind_param(
            'ssdsiiiii',
            $coupon_code, $discount_type, $discount_value, $expiry_date, $profile_type_id,
            $max_usage_limit, $user_id, $status, $id
          );
          if ($st->execute()) {
            $st->close();
            flash_redirect('Updated successfully');
          }
          $err = 'Update failed'; $st->close();
        }
      } else {
        if (!$can_add) { $err = 'You do not have permission to add.'; }
        else {
          $sql = "INSERT INTO $TABLE
                  (coupon_code, discount_type, discount_value, expiry_date, profile_type_id,
                   max_usage_limit, user_id, used_count, $STATUS_COL, created_by_userid, created_at, updated_at)
                  VALUES (?,?,?,?,?,?,?,?,?,?,NOW(),NOW())";
          $st = $con->prepare($sql);
          $used_count = 0;
          $st->bind_param(
            'ssdsiiiiii',
            $coupon_code, $discount_type, $discount_value, $expiry_date, $profile_type_id,
            $max_usage_limit, $user_id, $used_count, $status, $admin_id
          );
          if ($st->execute()) {
            $st->close();
            flash_redirect('Saved successfully');
          }
          $err = 'Insert failed'; $st->close();
        }
      }
    }
  }

  if (isset($_POST['delete'])){
    if (!$can_delete) { $err = 'You do not have permission to delete.'; }
    else {
      $id = (int)($_POST['id'] ?? 0);
      $st = $con->prepare("DELETE FROM $TABLE WHERE id=?");
      $st->bind_param('i',$id);
      if ($st->execute()) { $st->close(); flash_redirect('Deleted successfully'); }
      $err = 'Delete failed'; $st->close();
    }
  }
}

/* ---------- edit row ---------- */
$edit = null;
if ($mode==='form' && isset($_GET['edit'])){
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT * FROM $TABLE WHERE id=? LIMIT 1");
  $st->bind_param('i',$eid); $st->execute();
  $edit = $st->get_result()->fetch_assoc(); $st->close();
}

/* ---------- filters ---------- */
$q                = clean($_GET['q'] ?? '');
$sort             = clean($_GET['sort'] ?? 'order_asc');
$flt_profile_type = clean($_GET['flt_profile_type'] ?? '');
$flt_user_id      = clean($_GET['flt_user_id'] ?? '');
$all              = isset($_GET['all']);
$limit            = $all ? 1000000 : 50;

/* ---------- list query ---------- */
$order_sql = "ORDER BY $ORDER_COL ASC";
if ($sort==='order_desc') $order_sql = "ORDER BY $ORDER_COL DESC";
if ($sort==='name_asc')   $order_sql = "ORDER BY $LABEL_COL ASC";
if ($sort==='name_desc')  $order_sql = "ORDER BY $LABEL_COL DESC";
if ($sort==='id_desc')    $order_sql = "ORDER BY id DESC";
if ($sort==='id_asc')     $order_sql = "ORDER BY id ASC";

$where = "WHERE 1";
if ($q!==''){
  $qLike = '%'.$con->real_escape_string($q).'%';
  $where.=" AND $LABEL_COL LIKE '$qLike'";
}
if ($flt_profile_type !== '') {
  $where .= " AND profile_type_id = " . (int)$flt_profile_type;
}
if ($flt_user_id !== '') {
  $where .= " AND user_id = " . (int)$flt_user_id;
}

$sql = "SELECT id, coupon_code, discount_type, discount_value, expiry_date,
               profile_type_id, max_usage_limit, used_count, user_id, $STATUS_COL AS status
        FROM $TABLE $where $order_sql";
if (!$all) $sql .= " LIMIT $limit";
$res = $con->query($sql);

/* ---------- view ---------- */
ob_start(); ?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">
<style>
  /* based on standard master template */
  .toolbar{display:flex;gap:8px;align-items:center;justify-content:space-between;margin-bottom:12px}
  .search{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
  .inp{width:260px;padding:10px;border-radius:10px;border:1px solid #374151;background:#0b1220;color:#e5e7eb}
  .inp.small{width:180px}
  .btn{padding:10px 12px;border-radius:10px;border:0;cursor:pointer}
  .btn.gray{background:#374151;color:#fff}
  .btn.green{background:#10b981;color:#fff}
  .btn.red{background:#ef4444;color:#fff}
  .btn.secondary{background:#1f2937;color:#e5e7eb}
  .btn.success{background:#10b981;color:#fff}
  .badge{padding:3px 8px;border-radius:999px;font-size:12px}
  .badge.success{background:#065f46;color:#d1fae5}
  .badge.danger{background:#7f1d1d;color:#fecaca}
  .card{background:#111827;border:1px solid #1f2937;border-radius:16px;padding:16px}
  .table-wrap{max-height:60vh;overflow:auto;border-radius:12px}
  table{width:100%;border-collapse:separate;border-spacing:0}
  th,td{padding:10px;border-bottom:1px solid #1f2937;text-align:left}
  thead th{position:sticky;top:0;background:#0b1220;z-index:2}
  .note{background:#065f46;color:#d1fae5;padding:8px 10px;border-radius:8px;margin:8px 0}
  .err{background:#7f1d1d;color:#fecaca;padding:8px 10px;border-radius:8px;margin:8px 0}
  .small-text{font-size:12px;color:#9ca3af;margin-top:4px}
  .mono{font-family:ui-monospace,Menlo,Consolas,monospace}
</style>

<div class="master-wrap">
  <div class="headbar"><h2><?=h($page_title)?></h2></div>

  <?php if ($mode==='list'): ?>
    <div class="card">
      <div class="toolbar">
        <!-- LEFT: filters -->
        <form method="get" class="search">
          <input class="inp" type="text" name="q" value="<?=h($q)?>" placeholder="Search coupon code...">

          <select class="inp small" name="sort" title="Sort by">
            <?php
              $opts = [
                'order_asc'  => 'Order Level ↑',
                'order_desc' => 'Order Level ↓',
                'name_asc'   => 'Code A–Z',
                'name_desc'  => 'Code Z–A',
                'id_desc'    => 'Newest first',
                'id_asc'     => 'Oldest first',
              ];
              foreach($opts as $k=>$v){
                $sel = ($sort===$k)?'selected':'';
                echo "<option value=\"$k\" $sel>$v</option>";
              }
            ?>
          </select>

          <!-- NEW: Profile Type Filter -->
          <select class="inp small" name="flt_profile_type">
            <option value="">All Profile Types</option>
            <?php foreach ($profiles as $pid => $pname): ?>
              <option value="<?=$pid?>" <?=($flt_profile_type == $pid ? 'selected':'')?>>
                <?=h($pname)?>
              </option>
            <?php endforeach; ?>
          </select>

          <!-- NEW: User Filter -->
          <select class="inp small" name="flt_user_id">
            <option value="">All Users</option>
            <?php foreach ($users as $uid=>$udata): ?>
              <option value="<?=$uid?>" <?=($flt_user_id == $uid ? 'selected':'')?>>
                <?=h($udata['label'])?>
              </option>
            <?php endforeach; ?>
          </select>

          <button class="btn gray" type="submit">Search</button>

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

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

      <?php if(isset($_GET['ok'])): ?><div class="note"><?=h($_GET['ok'])?></div><?php endif; ?>
      <?php if(isset($_GET['err'])): ?><div class="err"><?=h($_GET['err'])?></div><?php endif; ?>

      <div class="table-wrap">
        <table class="table">
          <thead>
            <tr>
              <th style="width:70px;">Sr No</th>
              <th>Coupon Code</th>
              <th>Type / Value</th>
              <th>Expiry</th>
              <th>Profile Type</th>
              <th>Assigned User</th>
              <th>Usage</th>
              <th>Status</th>
              <th style="width:200px;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php
          if ($res && $res->num_rows){
            $sr=1;
            while($r=$res->fetch_assoc()){
              $ptname = $profiles[(int)$r['profile_type_id']] ?? ('#'.$r['profile_type_id']);
              $typeBadge = ($r['discount_type']==='flat' ? '₹' : '%');
              $valStr = ($r['discount_type']==='flat')
                        ? number_format((float)$r['discount_value'],2)
                        : rtrim(rtrim(number_format((float)$r['discount_value'],2,'.',''), '0'), '.');
              $exp = $r['expiry_date'] ? date('d-M-Y', strtotime($r['expiry_date'])) : '';
              $uid = (int)($r['user_id'] ?? 0);
              $userLabel = $uid && isset($users[$uid]) ? $users[$uid]['label'] : '— (Global)';
              echo '<tr>';
              echo '<td>'.($sr++).'</td>';
              echo '<td class="mono">'.h($r['coupon_code']).'</td>';
              echo '<td>'.$typeBadge.' '.$valStr.'</td>';
              echo '<td>'.$exp.'</td>';
              echo '<td>'.h($ptname).'</td>';
              echo '<td>'.h($userLabel).'</td>';
              echo '<td>'.(int)$r['used_count'].' / '.(int)$r['max_usage_limit'].'</td>';
              echo '<td><span class="badge '.((int)$r['status']?'success':'danger').'">'.((int)$r['status']?'Active':'Inactive').'</span></td>';
              echo '<td>';
              if ($can_edit) {
                echo '<a class="btn gray" href="'.h(keep_params(['edit'=>$r['id']])).'">Edit</a> ';
              } else {
                echo '<button class="btn gray" disabled>View</button> ';
              }
              if ($can_delete) {
                echo '<form method="post" style="display:inline" onsubmit="return confirm(\'Delete?\');">';
                echo '<input type="hidden" name="csrf" value="'.h(csrf_token()).'">';
                echo '<input type="hidden" name="id" value="'.$r['id'].'">';
                echo '<button class="btn red" name="delete" type="submit">Delete</button>';
                echo '</form>';
              } else {
                echo '<button class="btn gray" disabled>Delete</button>';
              }
              echo '</td>';
              echo '</tr>';
            }
          } else {
            echo '<tr><td colspan="9">No records.</td></tr>';
          }
          ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php else: /* form */ 
    // default row
    $row = [
      'id'=>0,
      'coupon_code'=>'',
      'discount_type'=>'percentage',
      'discount_value'=>'',
      'expiry_date'=>'',
      'profile_type_id'=>0,
      'max_usage_limit'=>0,
      'status'=>1,
      'user_id'=>0,
    ];
    if ($edit){ $row = array_merge($row, $edit); }

    // Back to list: preserve query params (filters), but remove add/edit
    $LIST_URL = h($_SERVER['SCRIPT_NAME'] . keep_params(['add'=>null,'edit'=>null]));
    $currentUserId = (int)($row['user_id'] ?? 0);
  ?>
    <div class="card" style="max-width:980px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
        <h3 style="margin:0"><?= $row['id']? 'Edit Coupon':'Add Coupon' ?></h3>
        <a class="btn gray" href="<?=$LIST_URL?>">Back to List</a>
      </div>

      <?php if($ok): ?><div class="note"><?=h($ok)?></div><?php endif; ?>
      <?php if($err): ?><div class="err"><?=h($err)?></div><?php endif; ?>

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

        <div style="grid-column:1/-1">
          <label>Coupon Code *</label>
          <input class="inp" name="coupon_code" required maxlength="64" autocomplete="off"
                 value="<?=h($row['coupon_code'])?>" <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
        </div>

        <div>
          <label>Discount Type *</label>
          <?php $sel = strtolower($row['discount_type'] ?? 'percentage'); ?>
          <select class="inp" name="discount_type" required <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
            <option value="percentage" <?=($sel==='percentage'?'selected':'')?>>Percentage (%)</option>
            <option value="flat"       <?=($sel==='flat'?'selected':'')?>>Flat (₹)</option>
          </select>
        </div>

        <div>
          <label>Discount Value *</label>
          <input class="inp" type="number" step="0.01" min="0" name="discount_value" required
                 value="<?=h($row['discount_value'])?>" <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
          <div class="small-text">If Percentage, enter %; if Flat, enter rupee amount.</div>
        </div>

        <div>
          <label>Expiry Date *</label>
          <input class="inp" type="date" name="expiry_date" required
                 value="<?=h($row['expiry_date'] ? substr($row['expiry_date'],0,10) : '')?>"
                 <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
        </div>

        <div>
          <label>Max Usage Limit *</label>
          <input class="inp" type="number" min="0" name="max_usage_limit" required
                 value="<?=h((string)($row['max_usage_limit'] ?? 0))?>" <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
        </div>

        <div>
          <label>Profile Type *</label>
          <select class="inp" name="profile_type_id" required <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
            <option value="">-- Select --</option>
            <?php
              $cur = (int)($row['profile_type_id'] ?? 0);
              foreach ($profiles as $pid=>$pname) {
                $s = ($cur === $pid) ? 'selected' : '';
                echo "<option value='".(int)$pid."' $s>".h($pname)." (#$pid)</option>";
              }
            ?>
          </select>
        </div>

        <div>
          <label>Status</label>
          <select class="inp" name="status" <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
            <option value="1" <?=((int)$row['status']===1?'selected':'')?>>Active</option>
            <option value="0" <?=((int)$row['status']===0?'selected':'')?>>Inactive</option>
          </select>
        </div>

        <!-- USER SEARCH / SELECTION -->
        <div style="grid-column:1/-1">
          <label>User (Optional – user specific coupon)</label>
          <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center">
            <input id="userSearch" type="text" class="inp"
                   placeholder="Search by name or mobile..."
                   <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
            <select id="userSelect" name="user_id" class="inp small"
                    <?=(!$can_add && !$can_edit ? 'disabled' : '')?>>
              <option value="">-- Any user / global coupon --</option>
            </select>
          </div>
          <div class="small-text">
            List will show users whose Profile Type matches the selected type.  
            You can search by candidate / recruiter / promoter name or mobile number.
          </div>
        </div>

        <div style="grid-column:1/-1;margin-top:8px">
          <?php if (($row['id'] && $can_edit) || (!$row['id'] && $can_add)): ?>
            <button class="btn green" name="save" type="submit">Save</button>
          <?php else: ?>
            <button class="btn gray" disabled>Save</button>
          <?php endif; ?>
        </div>
      </form>

      <!-- User search JS: filter by profile type + name/mobile -->
      <script>
        (function(){
          const users = <?=json_encode(array_values($users_for_js), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?>;
          const profileSelect = document.querySelector('select[name="profile_type_id"]');
          const userSearch    = document.getElementById('userSearch');
          const userSelect    = document.getElementById('userSelect');
          const currentUserId = <?=json_encode($currentUserId)?>;

          function refreshUsers(){
            if (!userSelect) return;
            const pid = profileSelect ? String(profileSelect.value || '') : '';
            const q   = (userSearch ? userSearch.value : '').toLowerCase();
            userSelect.innerHTML = '';
            const emptyOpt = document.createElement('option');
            emptyOpt.value = '';
            emptyOpt.textContent = '-- Any user / global coupon --';
            userSelect.appendChild(emptyOpt);

            users.forEach(u => {
              if (pid && String(u.profile_type_id) !== pid) return;
              if (q && u.label.toLowerCase().indexOf(q) === -1) return;
              const opt = document.createElement('option');
              opt.value = u.id;
              opt.textContent = u.label;
              userSelect.appendChild(opt);
            });

            if (currentUserId && String(currentUserId) !== '0') {
              userSelect.value = String(currentUserId);
            }
          }

          document.addEventListener('DOMContentLoaded', function(){
            if (!userSelect) return;
            refreshUsers();
            if (profileSelect) profileSelect.addEventListener('change', refreshUsers);
            if (userSearch) userSearch.addEventListener('input', refreshUsers);
          });
        })();
      </script>
    </div>
  <?php endif; ?>
</div>

<?php
echo ob_get_clean();
