<?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)

/* ===========================================================
   Help Question Category Master
   =========================================================== */

/* ---------- robust get_menu_row_for_script (adapted to your schema) ---------- */
function get_menu_row_for_script(mysqli $con) {
  $script = basename($_SERVER['SCRIPT_NAME']);
  $tableCheck = $con->query("SHOW TABLES LIKE 'jos_admin_menus'");
  if (!($tableCheck && $tableCheck->fetch_assoc())) return null;

  $like = '%' . $con->real_escape_string($script) . '%';
  $row = null;

  $sql = "SELECT * FROM `jos_admin_menus` WHERE (menu_link LIKE ? OR url LIKE ?) LIMIT 1";
  if ($st = $con->prepare($sql)) {
    $st->bind_param('ss', $like, $like);
    $st->execute(); $res = $st->get_result(); $row = $res ? $res->fetch_assoc() : null; $st->close();
  }
  if (!$row) {
    $sql2 = "SELECT * FROM `jos_admin_menus` WHERE menu_name LIKE ? LIMIT 1";
    if ($st2 = $con->prepare($sql2)) {
      $st2->bind_param('s', $like);
      $st2->execute(); $res2 = $st2->get_result(); $row = $res2 ? $res2->fetch_assoc() : null; $st2->close();
    }
  }
  if (!$row) {
    $sql3 = "SELECT * FROM `jos_admin_menus` LIMIT 1";
    if ($st3 = $con->prepare($sql3)) {
      $st3->execute(); $res3 = $st3->get_result(); $row = $res3 ? $res3->fetch_assoc() : null; $st3->close();
    }
  }
  if (!$row) return null;

  $row['title'] = $row['menu_name'] ?? ($row['menu_link'] ?? 'Menu');
  $row['link']  = $row['menu_link'] ?? ($row['url'] ?? '');
  return $row;
}

/* ------------------------- ACCESS CONTROL ------------------------- */
$MENU_ROW = get_menu_row_for_script($con);

function user_can(string $action) {
  global $MENU_ROW;
  $action = strtolower($action);
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();

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

  if ($MENU_ROW && !empty($_SESSION['permissions']) && isset($_SESSION['permissions'][(int)$MENU_ROW['id']])) {
    $perms = $_SESSION['permissions'][(int)$MENU_ROW['id']];
    if (isset($perms[$action])) return (bool)$perms[$action];
  }
  return true; // default allow
}

/* ------------------------- VARIABLES ------------------------- */
$page_title = $MENU_ROW['title'] ?? 'Help Question Category';
$TABLE      = 'jos_app_helpquestion_category';
$PTABLE     = 'jos_app_profile_types';

/* ------------------------- HELPERS ------------------------- */
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); }

function col_exists(mysqli $con, string $table, string $col): bool {
  $table = preg_replace('/[^a-zA-Z0-9_]/','', $table);
  $col   = $con->real_escape_string($col);
  $res   = $con->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  return ($res && $res->fetch_assoc()) ? true : false;
}
function ensure_schema(mysqli $con, string $table){
  if (!col_exists($con,$table,'status'))  { $con->query("ALTER TABLE `{$table}` ADD `status`  TINYINT DEFAULT 1"); }
  if (!col_exists($con,$table,'orderby')) { $con->query("ALTER TABLE `{$table}` ADD `orderby` INT DEFAULT 0"); }
}

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));
  }
}
function flash_redirect(string $msg='Saved'){
  $qs = $_GET; unset($qs['add'], $qs['edit']);
  $qs['ok'] = $msg;
  header('Location: ?'.http_build_query($qs)); exit;
}

ensure_schema($con, $TABLE);

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

/* ------------------------- FETCH PROFILE TYPES ------------------------- */
$profile_opts = [];
$rst = $con->query("SELECT id, profile_name FROM $PTABLE ORDER BY profile_name ASC");
while ($rst && $row = $rst->fetch_assoc()){ $profile_opts[(int)$row['id']] = $row['profile_name']; }

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

  if (isset($_POST['save'])){
    $id            = (int)($_POST['id'] ?? 0);
    $category_name = clean($_POST['category_name'] ?? '');
    $profile_type  = (int)($_POST['profile_type'] ?? 0);
    $status        = (int)($_POST['status'] ?? 1);
    $orderby       = (int)($_POST['orderby'] ?? 0);

    if ($category_name==='')  $err = 'Category Name is required.';
    elseif ($profile_type<=0) $err = 'Please choose a Profile Type.';
    else {
      $sql = "SELECT id FROM $TABLE WHERE LOWER(category_name)=LOWER(?) AND profile_type=? ".($id>0?"AND id<>$id":"")." LIMIT 1";
      $st  = $con->prepare($sql); $st->bind_param('si', $category_name, $profile_type);
      $st->execute(); $dup = $st->get_result()->fetch_assoc(); $st->close();
      if ($dup) $err = 'Duplicate category for the selected profile type.';
    }

    if (!$err){
      if ($orderby<=0){
        $r=$con->query("SELECT COALESCE(MAX(orderby),0)+1 mx FROM $TABLE");
        $orderby = ($r && $rw=$r->fetch_assoc()) ? (int)$rw['mx'] : 1;
      }

      if ($id>0 && user_can('edit')){
        $st = $con->prepare("UPDATE $TABLE SET category_name=?, profile_type=?, status=?, orderby=? WHERE id=?");
        $st->bind_param('siiii', $category_name,$profile_type,$status,$orderby,$id);
        if ($st->execute()) { $st->close(); flash_redirect('Updated successfully'); }
        $err = 'Update failed'; $st->close();
      } elseif ($id==0 && user_can('add')) {
        $st = $con->prepare("INSERT INTO $TABLE (category_name, profile_type, status, orderby) VALUES (?,?,?,?)");
        $st->bind_param('siii', $category_name,$profile_type,$status,$orderby);
        if ($st->execute()) { $st->close(); flash_redirect('Saved successfully'); }
        $err = 'Insert failed'; $st->close();
      } else {
        $err = 'Permission denied.';
      }
    }
  }

  if (isset($_POST['delete']) && user_can('delete')){
    $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 id, category_name, profile_type, status, orderby FROM $TABLE WHERE id=?");
  $st->bind_param('i',$eid); $st->execute();
  $edit = $st->get_result()->fetch_assoc(); $st->close();
}

/* ------------------------- FILTERS ------------------------- */
$q        = clean($_GET['q'] ?? '');
$ptype    = (int)($_GET['ptype'] ?? 0);
$stfilter = ($_GET['st'] ?? '') !== '' ? (int)$_GET['st'] : null;
$level    = clean($_GET['level'] ?? '');
$sort     = clean($_GET['sort'] ?? 'order_asc');
$all      = isset($_GET['all']);
$limit    = $all ? 1000000 : 50;

$order_sql = "ORDER BY c.orderby ASC";
if ($sort==='order_desc') $order_sql = "ORDER BY c.orderby DESC";
if ($sort==='name_asc')   $order_sql = "ORDER BY c.category_name ASC";
if ($sort==='name_desc')  $order_sql = "ORDER BY c.category_name DESC";
if ($sort==='id_desc')    $order_sql = "ORDER BY c.id DESC";
if ($sort==='id_asc')     $order_sql = "ORDER BY c.id ASC";

$where   = "WHERE 1";
$bind    = []; $types='';
if ($q!==''){ $where.=" AND c.category_name LIKE ?"; $bind[]="%$q%"; $types.='s'; }
if ($ptype>0){ $where.=" AND c.profile_type=?"; $bind[]=$ptype; $types.='i'; }
if ($stfilter!==null){ $where.=" AND c.status=?"; $bind[]=$stfilter; $types.='i'; }
if ($level!==''){ $where.=" AND c.orderby=?"; $bind[]=(int)$level; $types.='i'; }

$sql = "SELECT c.id, c.category_name, c.profile_type, c.orderby, c.status,
               pt.profile_name
        FROM $TABLE c
        LEFT JOIN $PTABLE pt ON pt.id=c.profile_type
        $where
        $order_sql
        LIMIT $limit";

$st = $con->prepare($sql);
if ($bind) $st->bind_param($types, ...$bind);
$st->execute();
$res = $st->get_result();
$rows=[]; while($res && $r=$res->fetch_assoc()) $rows[]=$r;
$st->close();

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

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

  <?php if ($mode==='list'): ?>
    <?php if(isset($_GET['ok'])): ?><div class="alert ok"><?=htmlspecialchars($_GET['ok'])?></div><?php endif; ?>
    <div class="card">
      <div class="toolbar" style="justify-content:space-between;">
        <form method="get" class="form" style="flex:1;">
          <input type="text" name="q" value="<?=htmlspecialchars($q)?>" placeholder="Search category..." class="inp">
        </form>
        <?php if (user_can('add')): ?>
          <a class="btn success" href="<?=keep_params(['add'=>1])?>">+ Add New</a>
        <?php endif; ?>
      </div>

      <div class="table-wrap">
        <table class="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Category</th>
              <th>Profile Type</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if(!$rows): ?>
              <tr><td colspan="5">No records found.</td></tr>
            <?php else: foreach($rows as $r): ?>
              <tr>
                <td><?=$r['id']?></td>
                <td><?=htmlspecialchars($r['category_name'])?></td>
                <td><?=htmlspecialchars($r['profile_name'] ?? '-')?></td>
                <td><span class="badge <?=($r['status']?'success':'danger')?>"><?=($r['status']?'Active':'Inactive')?></span></td>
                <td>
                  <?php if (user_can('edit')): ?>
                    <a class="btn secondary" href="<?=keep_params(['edit'=>$r['id']])?>">Edit</a>
                  <?php endif; ?>

                  <?php if (user_can('delete')): ?>
                    <form method="post" style="display:inline" onsubmit="return confirm('Are you sure to delete this record?');">
                      <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
                      <input type="hidden" name="id" value="<?=$r['id']?>">
                      <button class="btn danger" name="delete" type="submit">Delete</button>
                    </form>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php else:
    $row = ['id'=>0,'category_name'=>'','profile_type'=>0,'status'=>1,'orderby'=>0];
    if ($edit){ $row = $edit; }
    // Fixed Back-to-List
    $base_path = strtok($_SERVER['REQUEST_URI'], '?');
    $clean_qs  = keep_params(['add'=>null,'edit'=>null,'ok'=>null]);
    $LIST_URL  = htmlspecialchars($base_path . $clean_qs);
  ?>
    <div class="card" style="max-width:820px">
      <div class="toolbar" style="justify-content:space-between;">
        <h3><?= $row['id']? 'Edit Category':'Add Category' ?></h3>
        <a class="btn secondary" href="<?=$LIST_URL?>">Back to List</a>
      </div>
      <?php if($err): ?><div class="alert warn"><?=htmlspecialchars($err)?></div><?php endif; ?>
      <form method="post" class="form">
        <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
        <?php if($row['id']): ?><input type="hidden" name="id" value="<?=$row['id']?>"><?php endif; ?>
        <div class="grid" style="grid-template-columns:1fr 1fr 1fr 1fr;gap:12px">
          <div><label>Category Name*</label><input class="inp" name="category_name" required value="<?=htmlspecialchars($row['category_name'])?>"></div>
          <div><label>Profile Type*</label>
            <select class="inp" name="profile_type" required>
              <option value="">Select…</option>
              <?php foreach($profile_opts as $pid=>$pname): ?>
                <option value="<?=$pid?>" <?=$row['profile_type']==$pid?'selected':''?>><?=htmlspecialchars($pname)?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div><label>Order Level</label><input class="inp" type="number" name="orderby" value="<?=intval($row['orderby'])?>"></div>
          <div><label>Status</label>
            <select class="inp" name="status">
              <option value="1" <?=($row['status']==1?'selected':'')?>>Active</option>
              <option value="0" <?=($row['status']==0?'selected':'')?>>Inactive</option>
            </select>
          </div>
        </div>
        <div class="toolbar" style="margin-top:12px">
          <?php $can_save = $row['id'] ? user_can('edit') : user_can('add'); ?>
          <?php if ($can_save): ?>
            <button class="btn success" name="save" type="submit">Save</button>
          <?php else: ?>
            <button class="btn success" disabled>Save</button>
          <?php endif; ?>
        </div>
      </form>
    </div>
  <?php endif; ?>
</div>

<?php
echo ob_get_clean();
