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

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

global $con;

/* =========================
   Config / Tables
========================= */
$TABLE   = 'jos_app_crm_lead_statuses';
$MENUTBL = 'jos_admin_menus';

/* =========================
   Tiny utils
========================= */
function clean($v){ return trim((string)$v); }
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function keep_params($changes = array()) {
  $qs = $_GET;
  foreach ($changes as $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $q = http_build_query($qs);
  if ($q) return '?'.$q;

  $script = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : (isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : basename(__FILE__));
  return $script;
}

function table_exists($con, $name) {
  $name = mysqli_real_escape_string($con, $name);
  $rs = mysqli_query($con, "SHOW TABLES LIKE '$name'");
  return ($rs && mysqli_num_rows($rs) > 0);
}
function col_exists($con, $table, $col) {
  $t = mysqli_real_escape_string($con, $table);
  $c = mysqli_real_escape_string($con, $col);
  $r = mysqli_query($con, "SHOW COLUMNS FROM `$t` LIKE '$c'");
  return ($r && mysqli_num_rows($r) > 0);
}

/* dynamic bind helper (PHP 7 safe) */
function bind_params($stmt, $types, $params) {
  if (!$params) return;
  $bind_names = array();
  $bind_names[] = $types;

  for ($i=0; $i<count($params); $i++) {
    $bind_names[] = &$params[$i];
  }
  call_user_func_array(array($stmt, 'bind_param'), $bind_names);
}

/* =========================
   Ensure schema (safe)
========================= */
function ensure_schema($con, $table){
  if (!table_exists($con, $table)) return;

  if (!col_exists($con,$table,'status_name')) {
    mysqli_query($con,"ALTER TABLE `$table` ADD `status_name` VARCHAR(150) NOT NULL");
  }
  if (!col_exists($con,$table,'is_active')) {
    mysqli_query($con,"ALTER TABLE `$table` ADD `is_active` TINYINT(1) NOT NULL DEFAULT 1");
  }
  if (!col_exists($con,$table,'sort_order')) {
    mysqli_query($con,"ALTER TABLE `$table` ADD `sort_order` INT NOT NULL DEFAULT 0");
  } else {
    mysqli_query($con,"ALTER TABLE `$table` MODIFY `sort_order` INT NOT NULL DEFAULT 0");
  }
  if (!col_exists($con,$table,'created_at')) {
    mysqli_query($con,"ALTER TABLE `$table` ADD `created_at` DATETIME NULL DEFAULT NULL");
  }
}
ensure_schema($con, $TABLE);

/* =========================
   Current menu (for title + ACL)
========================= */
function current_script_paths() {
  $script = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '';
  $req = '';
  if (!empty($_SERVER['REQUEST_URI'])) {
    $req = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  }
  if (!$req) $req = $script;

  $variants = array();
  $variants[] = $script;
  $variants[] = $req;
  $variants[] = preg_replace('#^/beta#','', $script);
  $variants[] = preg_replace('#^/beta#','', $req);

  $out = array();
  foreach ($variants as $p) {
    $p = (string)$p;
    if ($p === '') continue;
    if (!in_array($p, $out, true)) $out[] = $p;
  }
  return $out;
}

function fetch_menu_info($con, $MENUTBL) {
  $out = array('id'=>0, 'menu_name'=>'', 'menu_link'=>'');
  if (!table_exists($con, $MENUTBL)) return $out;

  $paths = current_script_paths();

  foreach ($paths as $p) {
    $sql = "SELECT id, menu_name, menu_link FROM `$MENUTBL` WHERE menu_link=? LIMIT 1";
    if ($st = $con->prepare($sql)) {
      $st->bind_param('s', $p);
      $st->execute();
      $res = $st->get_result();
      $r = $res ? $res->fetch_assoc() : null;
      $st->close();
      if ($r) return $r;
    }
  }

  foreach ($paths as $p) {
    $like = '%'.$p;
    $sql = "SELECT id, menu_name, menu_link FROM `$MENUTBL`
            WHERE menu_link LIKE ? ORDER BY LENGTH(menu_link) DESC LIMIT 1";
    if ($st = $con->prepare($sql)) {
      $st->bind_param('s', $like);
      $st->execute();
      $res = $st->get_result();
      $r = $res ? $res->fetch_assoc() : null;
      $st->close();
      if ($r) return $r;
    }
  }

  return $out;
}

$menu = fetch_menu_info($con, $MENUTBL);
$page_title = !empty($menu['menu_name']) ? $menu['menu_name'] : 'Lead Status Master';
$MENU_ID    = (int)(isset($menu['id']) ? $menu['id'] : 0);

/* =========================
   Access control
========================= */
function user_can($action, $menu_id, $con) {
  $action = strtolower((string)$action);
  $valid  = array('view','add','edit','delete');
  if (!in_array($action, $valid, true)) return false;

  $sess = isset($_SESSION) ? $_SESSION : array();

  // Session-based
  if (!empty($sess['user_permissions']) && is_array($sess['user_permissions'])) {
    if ($menu_id && isset($sess['user_permissions'][$menu_id][$action])) {
      return (bool)$sess['user_permissions'][$menu_id][$action];
    }
    $paths = current_script_paths();
    foreach ($paths as $k) {
      if (isset($sess['user_permissions'][$k][$action])) return (bool)$sess['user_permissions'][$k][$action];
    }
  }

  // DB fallback
  $me = isset($sess['admin_user']) ? $sess['admin_user'] : array();
  $role_id = (int)(isset($me['role_id']) ? $me['role_id'] : 0);
  if ($role_id <= 0 || $menu_id <= 0) return false;

  $MAP1 = 'jos_admin_rolemenus';
  $MAP2 = 'jos_admin_role_menu';
  $mapTable = table_exists($con, $MAP1) ? $MAP1 : (table_exists($con, $MAP2) ? $MAP2 : '');
  if ($mapTable === '') return false;

  $cols = array('view'=>'can_view','add'=>'can_add','edit'=>'can_edit','delete'=>'can_delete');
  $col  = $cols[$action];

  $sql = "SELECT $col AS allowed FROM `$mapTable` WHERE role_id=? AND menu_id=? LIMIT 1";
  if ($st = $con->prepare($sql)) {
    $st->bind_param('ii', $role_id, $menu_id);
    $st->execute();
    $res = $st->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $st->close();
    return ($row && (int)$row['allowed'] === 1);
  }

  return false;
}

/* Gate "view" */
if (!user_can('view', $MENU_ID, $con)) {
  http_response_code(403);
  ?>
  <!doctype html>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <div class="card" style="max-width:680px;margin:24px auto">
    <h3 style="margin-top:0"><?=h($page_title)?></h3>
    <div class="badge off" style="margin:8px 0">You are not authorized to view this content.</div>
  </div>
  <?php
  exit;
}

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

/* =========================
   POST
========================= */
$err='';

if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request.';
  } else {

    // Save
    if (isset($_POST['save'])) {
      $id          = (int)($_POST['id'] ?? 0);
      $status_name = clean($_POST['status_name'] ?? '');
      $sort_order  = (int)($_POST['sort_order'] ?? 0);
      $is_active   = (int)($_POST['is_active'] ?? 1);

      if ($id > 0 && !user_can('edit', $MENU_ID, $con)) {
        $err = 'You are not authorized to edit.';
      } elseif ($id === 0 && !user_can('add', $MENU_ID, $con)) {
        $err = 'You are not authorized to add.';
      } elseif ($status_name==='') {
        $err = 'Status Name is required.';
      } else {
        if ($id > 0) {
          $st = $con->prepare("UPDATE `$TABLE` SET status_name=?, sort_order=?, is_active=? WHERE id=?");
          $st->bind_param('siii', $status_name, $sort_order, $is_active, $id);
          if ($st->execute()) { $st->close(); flash_redirect('Updated successfully'); }
          $err = 'Update failed';
          $st->close();
        } else {
          $st = $con->prepare("INSERT INTO `$TABLE` (status_name, sort_order, is_active, created_at) VALUES (?,?,?,NOW())");
          $st->bind_param('sii', $status_name, $sort_order, $is_active);
          if ($st->execute()) { $st->close(); flash_redirect('Saved successfully'); }
          $err = 'Insert failed';
          $st->close();
        }
      }
    }

    // Delete
    if (isset($_POST['delete'])) {
      if (!user_can('delete', $MENU_ID, $con)) {
        $err = 'You are not authorized to delete.';
      } else {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) $err = 'Invalid ID.';
        else {
          $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();
        }
      }
    }
  }
}

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

if ($mode==='form') {
  if (isset($_GET['add']) && !user_can('add', $MENU_ID, $con)) { $mode='denied_form'; $err='You are not authorized to add.'; }
  if (isset($_GET['edit']) && !user_can('edit', $MENU_ID, $con)) { $mode='denied_form'; $err='You are not authorized to edit.'; }
}

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

/* =========================
   Filters
========================= */
$q = trim($_GET['q'] ?? '');
$all = isset($_GET['all']);
$lim = $all ? 0 : 50;

$where = " WHERE 1=1 ";
$bind = array();
$type = '';

if ($q !== '') {
  $where .= " AND status_name LIKE ? ";
  $bind[] = "%$q%";
  $type  .= 's';
}

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

$sql = "SELECT id,status_name,is_active,sort_order,created_at
        FROM `$TABLE`
        $where
        ORDER BY sort_order ASC, id DESC";
if (!$all) $sql .= " LIMIT $lim";

$st = $con->prepare($sql);
bind_params($st, $type, $bind);
$st->execute();
$rs = $st->get_result();
$rows = array();
while ($rs && ($r = $rs->fetch_assoc())) $rows[] = $r;
$st->close();

/* =========================
   View
========================= */
ob_start(); ?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">

<h2 style="margin:8px 0 12px"><?=h($page_title)?></h2>

<?php if ($mode==='denied_form'): ?>
  <div class="card" style="max-width:760px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <h3 style="margin:0">Access denied</h3>
      <a class="btn gray" href="<?=h(keep_params(array('edit'=>null,'add'=>null)))?>">Back to List</a>
    </div>
    <?php if($err): ?><div class="badge off" style="margin:8px 0"><?=h($err)?></div><?php endif; ?>
    <p style="color:#9ca3af;margin:8px 0">You don't have permission to perform this action.</p>
  </div>

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

  <div class="card">
    <div class="toolbar">
      <form method="get" class="search">
        <input type="text" name="q" class="inp" placeholder="Search by status..." value="<?=h($q)?>">
        <button class="btn gray" type="submit">Search</button>

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

      <?php if (user_can('add', $MENU_ID, $con)): ?>
        <a class="btn green" href="<?=h(keep_params(array('add'=>1)))?>">Add New</a>
      <?php endif; ?>
    </div>

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

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th>
          <th>Status Name</th>
          <th>Sort</th>
          <th>Active</th>
          <th>Created</th>
          <th>Actions</th>
        </tr></thead>
        <tbody>
        <?php if(!$rows): ?>
          <tr><td colspan="6" style="color:#9ca3af">No records</td></tr>
        <?php endif; ?>

        <?php $sr=0; foreach($rows as $r): $sr++; ?>
          <tr>
            <td><?=$sr?></td>
            <td><?=h($r['status_name'])?></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td><span class="badge <?=$r['is_active']?'on':'off'?>"><?=$r['is_active']?'Yes':'No'?></span></td>
            <td><?= !empty($r['created_at']) ? date('d-m-Y H:i', strtotime($r['created_at'])) : '—' ?></td>
            <td>
              <?php if (user_can('edit', $MENU_ID, $con)): ?>
                <a class="btn gray" href="<?=h(keep_params(array('edit'=>(int)$r['id'])))?>">Edit</a>
              <?php endif; ?>

              <?php if (user_can('delete', $MENU_ID, $con)): ?>
                <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');">
                  <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                  <input type="hidden" name="id" value="<?= (int)$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 (allowed) */ ?>
  <div class="card" style="max-width:760px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <h3 style="margin:0"><?= $edit ? 'Edit Lead Status' : 'Add Lead Status' ?></h3>
      <a class="btn gray" href="<?=h(keep_params(array('edit'=>null,'add'=>null)))?>">Back to List</a>
    </div>

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

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

      <div style="grid-column:1/-1">
        <label>Status Name*</label>
        <input name="status_name" class="inp" required value="<?=h($edit['status_name'] ?? '')?>">
      </div>

      <div>
        <label>Sort Order</label>
        <input type="number" name="sort_order" class="inp" value="<?=h($edit['sort_order'] ?? 0)?>">
      </div>

      <div>
        <label>Active</label>
        <?php $ia = isset($edit['is_active']) ? (int)$edit['is_active'] : 1; ?>
        <select name="is_active" class="inp">
          <option value="1" <?=$ia===1?'selected':''?>>Yes</option>
          <option value="0" <?=$ia===0?'selected':''?>>No</option>
        </select>
      </div>

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

<?php
echo ob_get_clean();
