<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);
require_once __DIR__ . '/../includes/auth.php';
require_login();

global $con;
if (!isset($con) || !$con instanceof mysqli) {
  die('<div style="color:#f66">DB connection ($con) missing. Check includes/auth.php initializes $con.</div>');
}

$TABLE = 'jos_admin_menus';

/* ---------- 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($con,$table,$col){
  $r=mysqli_query($con,"SHOW COLUMNS FROM `$table` LIKE '".mysqli_real_escape_string($con,$col)."'");
  return ($r && mysqli_num_rows($r)>0);
}
function ensure_schema_min($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");
  else                                     mysqli_query($con,"ALTER TABLE `$table` MODIFY `orderby` INT NOT NULL DEFAULT 0");
  if(!col_exists($con,$table,'parent_id')) mysqli_query($con,"ALTER TABLE `$table` ADD `parent_id` INT NOT NULL DEFAULT 0");
  if(!col_exists($con,$table,'menu_name')) mysqli_query($con,"ALTER TABLE `$table` ADD `menu_name` VARCHAR(150) NOT NULL");
  if(!col_exists($con,$table,'menu_link')) mysqli_query($con,"ALTER TABLE `$table` ADD `menu_link` VARCHAR(255) NULL DEFAULT NULL");
  if(!col_exists($con,$table,'icon'))      mysqli_query($con,"ALTER TABLE `$table` ADD `icon` VARCHAR(100) NULL DEFAULT NULL");
  if(!col_exists($con,$table,'remarks'))   mysqli_query($con,"ALTER TABLE `$table` ADD `remarks` VARCHAR(255) NULL DEFAULT NULL");
  if(!col_exists($con,$table,'created_at'))mysqli_query($con,"ALTER TABLE `$table` ADD `created_at` DATETIME NULL DEFAULT NULL");
  if(!col_exists($con,$table,'updated_at'))mysqli_query($con,"ALTER TABLE `$table` ADD `updated_at` DATETIME NULL DEFAULT NULL");
}
ensure_schema_min($con,$TABLE);

/* ---------- ensure unique key for jos_admin_rolemenus ---------- */
function ensure_rolemenu_unique(mysqli $con){
  $sql = "SELECT COUNT(*) c
            FROM INFORMATION_SCHEMA.STATISTICS
           WHERE TABLE_SCHEMA = DATABASE()
             AND TABLE_NAME='jos_admin_rolemenus'
             AND INDEX_NAME='uq_role_menu'";
  $c = $con->query($sql)->fetch_assoc();
  if (empty($c['c']) || (int)$c['c']===0){
    $con->query("ALTER TABLE jos_admin_rolemenus ADD UNIQUE KEY uq_role_menu (role_id, menu_id)");
  }
}
ensure_rolemenu_unique($con);

/* ---------- Resolve current script + dynamic page title from menus ---------- */
$script  = $_SERVER['SCRIPT_NAME'] ?? '';
$file    = basename($script);
$page_title = 'Menu Master';     // default
$menu_id = 0;

// 1) exact match
if ($st = $con->prepare("SELECT id, menu_name FROM $TABLE WHERE menu_link=? LIMIT 1")) {
  $st->bind_param('s',$script);
  $st->execute();
  if ($r = $st->get_result()->fetch_assoc()) {
    $menu_id = (int)$r['id'];
    $page_title = $r['menu_name'] ?: $page_title;
  }
  $st->close();
}
// 2) filename LIKE
if ($menu_id===0 && $file!=='') {
  if ($st = $con->prepare("SELECT id, menu_name FROM $TABLE WHERE menu_link LIKE CONCAT('%',?,'%') LIMIT 1")) {
    $st->bind_param('s',$file);
    $st->execute();
    if ($r = $st->get_result()->fetch_assoc()) {
      $menu_id = (int)$r['id'];
      $page_title = $r['menu_name'] ?: $page_title;
    }
    $st->close();
  }
}

/* ---------- ACL: resolve role_id from session ---------- */
$u = current_user();
$ROLE_ID = (int)($u['role_id'] ?? 0);
if ($ROLE_ID === 0 && !empty($u['role'])) {
  if ($st = $con->prepare("SELECT id FROM jos_admin_roles WHERE name=? LIMIT 1")) {
    $st->bind_param('s', $u['role']);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $ROLE_ID = (int)($row['id'] ?? 0);
    $st->close();
  }
}

/* ---------- If still no $menu_id, try by title we have (fallback) ---------- */
if ($menu_id===0) {
  if ($st = $con->prepare("SELECT id FROM $TABLE WHERE menu_name=? LIMIT 1")) {
    $st->bind_param('s',$page_title);
    $st->execute();
    if ($r = $st->get_result()->fetch_assoc()) $menu_id=(int)$r['id'];
    $st->close();
  }
}

/* ---------- ACL: load capabilities ---------- */
$CAN_VIEW = $CAN_ADD = $CAN_EDIT = $CAN_DELETE = 0;
$deny_reason = '';
if ($menu_id === 0) {
  $deny_reason = "Menu not found for this page (add `menu_link`='$script' in $TABLE).";
} elseif ($ROLE_ID === 0) {
  $deny_reason = "Your account does not have a valid role_id.";
} else {
  $q=$con->prepare("SELECT can_view,can_add,can_edit,can_delete FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1");
  $q->bind_param('ii',$ROLE_ID,$menu_id);
  $q->execute(); $acl=$q->get_result()->fetch_assoc(); $q->close();
  if(!$acl){ $deny_reason="No role-menu mapping for role_id=$ROLE_ID & menu_id=$menu_id."; }
  else {
    $CAN_VIEW   = (int)$acl['can_view'];
    $CAN_ADD    = (int)$acl['can_add'];
    $CAN_EDIT   = (int)$acl['can_edit'];
    $CAN_DELETE = (int)$acl['can_delete'];
    if(!$CAN_VIEW) $deny_reason="Your role does not have view permission (can_view=0).";
  }
}
if(!$CAN_VIEW){
  http_response_code(403);
  echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
  echo '<div class="master-wrap"><div class="card" style="border-left:4px solid #ef4444"><div>';
  echo '<strong>Access denied:</strong> '.$deny_reason;
  echo '</div></div></div>';
  exit;
}

/* ---------- flash redirect ---------- */
function back_to_list($msg=''){
  $path = $_SERVER['SCRIPT_NAME'] ?? '/adminconsole/masters/menu.php';
  $url  = $path; if ($msg!=='') $url .= '?'.http_build_query(['ok'=>$msg]);
  header('Location: '.$url); exit;
}
$ok  = clean($_GET['ok'] ?? '');
$err = '';

/* ---------- role-perms SAVE (clear + rebuild) ---------- */
function save_role_perms(mysqli $con, int $menu_id, array $perms): void {
    if ($menu_id <= 0) return;

    $con->begin_transaction();
    try {
        // 1) Remove ALL existing mappings for this menu
        $delAll = $con->prepare("DELETE FROM jos_admin_rolemenus WHERE menu_id=?");
        $delAll->bind_param('i', $menu_id);
        $delAll->execute();
        $delAll->close();

        // If nothing posted, we’re done (no permissions for this menu at all)
        if (empty($perms)) {
            $con->commit();
            return;
        }

        // 2) Insert only roles that actually have some permission
        $ins = $con->prepare("
            INSERT INTO jos_admin_rolemenus
                (role_id, menu_id, can_view, can_add, can_edit, can_delete, status, orderby, created_at, updated_at)
            VALUES
                (?,       ?,       ?,       ?,       ?,        ?,         1,      0,        NOW(),    NOW())
        ");

        foreach ($perms as $rid => $flags) {
            $rid = (int)$rid;

            // '0' or '1'; !empty('0') = false, !empty('1') = true
            $v = !empty($flags['view'])   ? 1 : 0;
            $a = !empty($flags['add'])    ? 1 : 0;
            $e = !empty($flags['edit'])   ? 1 : 0;
            $d = !empty($flags['delete']) ? 1 : 0;

            // If all are 0, skip (no row for this role)
            if (($v | $a | $e | $d) === 0) {
                continue;
            }

            $ins->bind_param('iiiiii', $rid, $menu_id, $v, $a, $e, $d);
            $ins->execute();
        }

        $ins->close();
        $con->commit();
    } catch (Throwable $ex) {
        $con->rollback();
        throw $ex;
    }
}

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

/* ---------- POST ---------- */
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if(!verify_csrf($_POST['csrf'] ?? null)) $err='Invalid request. Please refresh.';
  else{
    if(isset($_POST['delete'])){
      if(!$CAN_DELETE){ http_response_code(403); die('Forbidden: no delete permission.'); }
      $id=(int)($_POST['id']??0);
      $st=$con->prepare("DELETE FROM $TABLE WHERE id=?"); $st->bind_param('i',$id);
      if($st->execute()){ $st->close(); back_to_list('Deleted successfully.'); }
      $err='Delete failed.'; $st->close();
    }
    if(isset($_POST['save'])){
      $id=(int)($_POST['id']??0);
      if($id>0 && !$CAN_EDIT){ http_response_code(403); die('Forbidden: no edit permission.'); }
      if($id===0 && !$CAN_ADD){ http_response_code(403); die('Forbidden: no add permission.'); }

      $menu_name = clean($_POST['menu_name'] ?? '');
      $menu_link = clean($_POST['menu_link'] ?? '');
      $icon      = clean($_POST['icon'] ?? '');
      $remarks   = clean($_POST['remarks'] ?? '');
      $parent_id = (int)($_POST['parent_id'] ?? 0);
      $orderby   = (int)($_POST['orderby'] ?? 0);
      $status    = (int)($_POST['status'] ?? 1);

      if($menu_name===''){ $err='Menu name is required.'; }
      else{
        if($id>0){ $st=$con->prepare("SELECT id FROM $TABLE WHERE LOWER(menu_name)=LOWER(?) AND id<>?"); $st->bind_param('si',$menu_name,$id); }
        else     { $st=$con->prepare("SELECT id FROM $TABLE WHERE LOWER(menu_name)=LOWER(?)");             $st->bind_param('s',$menu_name); }
        $st->execute(); $st->store_result();
        if($st->num_rows>0) $err='Menu already exists.'; $st->close();

        if(!$err){
          if ($orderby<=0){
            $q=mysqli_query($con,"SELECT COALESCE(MAX(orderby),0)+1 FROM $TABLE");
            $orderby = ($q && ($r=mysqli_fetch_row($q))) ? (int)$r[0] : 1;
          }

          if($id>0){
            $st=$con->prepare("UPDATE $TABLE SET menu_name=?,menu_link=?,icon=?,remarks=?,parent_id=?,orderby=?,status=?,updated_at=NOW() WHERE id=?");
            $st->bind_param('ssssiiii',$menu_name,$menu_link,$icon,$remarks,$parent_id,$orderby,$status,$id);
            if($st->execute()){
              $st->close();
              $postedPerms = $_POST['perms'] ?? [];
              save_role_perms($con, $id, is_array($postedPerms)?$postedPerms:[]);
              back_to_list('Updated successfully.');
            }
            $err='Update failed.'; $st->close();
          } else {
            $st=$con->prepare("INSERT INTO $TABLE (menu_name,menu_link,icon,remarks,parent_id,orderby,status,created_at,updated_at)
                               VALUES (?,?,?,?,?,?,?,NOW(),NOW())");
            $st->bind_param('ssssiii',$menu_name,$menu_link,$icon,$remarks,$parent_id,$orderby,$status);
            if($st->execute()){
              $newMenuId = $st->insert_id; $st->close();
              $postedPerms = $_POST['perms'] ?? [];
              save_role_perms($con, (int)$newMenuId, is_array($postedPerms)?$postedPerms:[]);
              back_to_list('Added successfully.');
            }
            $err='Insert failed.'; $st->close();
          }
        }
      }
    }
  }
}

/* ---------- edit row (guard) ---------- */
$edit=null;
if ($mode==='form' && isset($_GET['edit'])){
  if (!$CAN_EDIT){ http_response_code(403); die('Forbidden: no edit permission.'); }
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT id,menu_name,menu_link,icon,remarks,parent_id,orderby,status FROM $TABLE WHERE id=?");
  $st->bind_param('i',$eid); $st->execute();
  $edit=$st->get_result()->fetch_assoc(); $st->close();
}
if ($mode==='form' && isset($_GET['add']) && !$CAN_ADD){
  http_response_code(403); die('Forbidden: no add permission.');
}

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

$where=" WHERE 1=1 "; $bind=[]; $type='';
if ($q!==''){
  $like="%$q%"; $where.=" AND (m.menu_name LIKE ? OR m.menu_link LIKE ? OR m.remarks LIKE ?)";
  $bind[]=$like; $bind[]=$like; $bind[]=$like; $type.='sss';
}
if ($status!==''){ $stt=(int)$status; $where.=" AND m.status=?"; $bind[]=$stt; $type.='i'; }
if ($parent!==''){ $pid=(int)$parent; $where.=" AND m.parent_id=?"; $bind[]=$pid; $type.='i'; }

/* ---- sort options (Parent→children grouping on order_asc/desc) ---- */
switch ($sort){
  case 'order_desc':
    $order="ORDER BY
              CASE WHEN m.parent_id=0 THEN m.id ELSE m.parent_id END DESC,
              m.parent_id DESC, m.orderby DESC, m.menu_name ASC";
    break;
  case 'name_asc':   $order="ORDER BY m.menu_name ASC"; break;
  case 'name_desc':  $order="ORDER BY m.menu_name DESC"; break;
  case 'id_desc':    $order="ORDER BY m.id DESC"; break;
  case 'id_asc':     $order="ORDER BY m.id ASC"; break;
  default:
    $order="ORDER BY
              CASE WHEN m.parent_id=0 THEN m.id ELSE m.parent_id END,
              m.parent_id, m.orderby, m.menu_name";
}

/* ---------- counts / list with parent name ---------- */
$rows=[]; $total=0;
if ($mode==='list'){
  $st=$con->prepare("SELECT COUNT(*) c FROM $TABLE m $where");
  if($bind) $st->bind_param($type, ...$bind);
  $st->execute(); $total=(int)$st->get_result()->fetch_assoc()['c']; $st->close();

  $sql="SELECT
          m.id, m.menu_name, m.menu_link, m.icon, m.remarks,
          m.parent_id, m.orderby, m.status,
          p.menu_name AS parent_name
        FROM $TABLE m
        LEFT JOIN $TABLE p ON p.id = m.parent_id
        $where
        $order";
  if(!$all) $sql.=" LIMIT $lim";

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

/* ---------- Parent Menu options (top-level only) ---------- */
$parents=[];
$pr=mysqli_query($con,"SELECT id,menu_name FROM $TABLE WHERE parent_id=0 ORDER BY orderby ASC, menu_name ASC");
while($p=mysqli_fetch_assoc($pr)) $parents[]=$p;

/* ---------- Roles + existing perms for this menu (for form matrix) ---------- */
$roles = [];
$rq = $con->query("SELECT id, name FROM jos_admin_roles ORDER BY name ASC");
while($rr = $rq->fetch_assoc()) $roles[] = $rr;

$existingPerms = [];
if ($mode==='form' && $edit && !empty($edit['id'])) {
  $mid = (int)$edit['id'];
  $prs = $con->prepare("SELECT role_id, can_view, can_add, can_edit, can_delete FROM jos_admin_rolemenus WHERE menu_id=?");
  $prs->bind_param('i', $mid);
  $prs->execute();
  $res = $prs->get_result();
  while ($p = $res->fetch_assoc()) {
    $existingPerms[(int)$p['role_id']] = [
      'view'   => (int)$p['can_view'],
      'add'    => (int)$p['can_add'],
      'edit'   => (int)$p['can_edit'],
      'delete' => (int)$p['can_delete'],
    ];
  }
  $prs->close();
}

/* ---------- (optional) role access preview ---------- */
$viewAccessMenuId = isset($_GET['view_access']) ? (int)$_GET['view_access'] : 0;
$roleAccessRows = []; $menuTitle = '';
if ($mode==='list' && $viewAccessMenuId > 0) {
  $stmt = $con->prepare("
    SELECT r.id AS role_id, r.name AS role_name,
           COALESCE(rm.can_view,0)  AS can_view,
           COALESCE(rm.can_add,0)   AS can_add,
           COALESCE(rm.can_edit,0)  AS can_edit,
           COALESCE(rm.can_delete,0)AS can_delete
      FROM jos_admin_roles r
      LEFT JOIN jos_admin_rolemenus rm
             ON rm.role_id = r.id AND rm.menu_id = ?
     ORDER BY r.name ASC
  ");
  $stmt->bind_param('i', $viewAccessMenuId);
  $stmt->execute();
  $res = $stmt->get_result();
  while($row = $res->fetch_assoc()) $roleAccessRows[] = $row;
  $stmt->close();

  $mn = $con->prepare("SELECT menu_name FROM $TABLE WHERE id=?");
  $mn->bind_param('i',$viewAccessMenuId);
  $mn->execute();
  $menuTitle = $mn->get_result()->fetch_assoc()['menu_name'] ?? ('#'.$viewAccessMenuId);
  $mn->close();
}

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

<div class="master-wrap">
  <div class="headbar">
    <div class="headbar-left"><h2 style="margin:0"><?php echo htmlspecialchars($page_title); ?></h2></div>
  </div>

  <?php if($ok):  ?><div class="card" style="border-left:4px solid #10b981"><div><?php echo htmlspecialchars($ok); ?></div></div><?php endif; ?>
  <?php if($err): ?><div class="card" style="border-left:4px solid #ef4444"><div><?php echo htmlspecialchars($err); ?></div></div><?php endif; ?>

  <?php if ($mode==='list'): ?>
    <div class="card">
      <div class="toolbar">
        <form method="get" class="search">
          <input type="text" name="q" class="inp" placeholder="Search menu..." value="<?php echo htmlspecialchars($q); ?>" style="width:320px">

          <select name="parent" class="inp small" title="Parent">
            <option value="">All Parents</option>
            <option value="0" <?php echo ($parent==='0')?'selected':''; ?>>(Top-level)</option>
            <?php foreach($parents as $p): ?>
              <option value="<?php echo (int)$p['id']; ?>" <?php echo ($parent==(string)$p['id'])?'selected':''; ?>>
                <?php echo htmlspecialchars($p['menu_name']); ?>
              </option>
            <?php endforeach; ?>
          </select>

          <select name="status" class="inp small" title="Status">
            <option value="">All Status</option>
            <option value="1" <?php echo ($status==='1')?'selected':''; ?>>Active</option>
            <option value="0" <?php echo ($status==='0')?'selected':''; ?>>Inactive</option>
          </select>

          <select name="sort" class="inp small" title="Sort by">
            <?php
              $opts = [
                'order_asc'  => 'Order Level ↑ (Parent → Menu)',
                'order_desc' => 'Order Level ↓ (Parent → Menu)',
                'name_asc'   => 'Name A–Z',
                'name_desc'  => 'Name 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>

          <button class="btn gray" type="submit">Search</button>
          <a class="btn gray" href="<?php echo keep_params(['all'=>1]); ?>">View All (<?php echo $total; ?>)</a>
        </form>

        <div style="display:flex;gap:8px">
          <?php if ($CAN_ADD): ?>
            <a class="btn green" href="<?php echo keep_params(['add'=>1,'edit'=>null]); ?>">Add New</a>
          <?php endif; ?>
        </div>
      </div>

      <?php if ($viewAccessMenuId > 0): ?>
        <div id="roleAccess" class="card" style="margin-top:8px; border-left:4px solid #3b82f6">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px">
            <h3 style="margin:0">Role Access – <?php echo htmlspecialchars($menuTitle); ?></h3>
            <a class="btn gray" href="<?php echo keep_params(['view_access'=>null]); ?>">Close</a>
          </div>

          <div class="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>SR No</th>
                  <th>Role</th>
                  <th>View</th>
                  <th>Add</th>
                  <th>Edit</th>
                  <th>Delete</th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$roleAccessRows): ?>
                  <tr><td colspan="6" style="color:#9ca3af">No roles found.</td></tr>
                <?php endif; $sr=0; foreach($roleAccessRows as $ra): $sr++; ?>
                  <tr>
                    <td><?php echo $sr; ?></td>
                    <td><?php echo htmlspecialchars($ra['role_name']); ?></td>
                    <td><span class="badge <?php echo $ra['can_view']?'on':'off'; ?>"><?php echo $ra['can_view']?'Yes':'No'; ?></span></td>
                    <td><span class="badge <?php echo $ra['can_add']?'on':'off'; ?>"><?php echo $ra['can_add']?'Yes':'No'; ?></span></td>
                    <td><span class="badge <?php echo $ra['can_edit']?'on':'off'; ?>"><?php echo $ra['can_edit']?'Yes':'No'; ?></span></td>
                    <td><span class="badge <?php echo $ra['can_delete']?'on':'off'; ?>"><?php echo $ra['can_delete']?'Yes':'No'; ?></span></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
        <script>
          window.addEventListener('load', ()=> {
            const el = document.getElementById('roleAccess');
            if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
          });
        </script>
      <?php endif; ?>

      <div style="margin:6px 0 12px;color:#9ca3af">
        Showing <strong><?php echo !$all ? count($rows) : $total; ?></strong> of <strong><?php echo $total; ?></strong>
      </div>

      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>SR No</th>
              <th>Name (Parent › Menu)</th>
              <th>Link</th>
              <th>Icon</th>
              <th>Remarks</th>
              <th>Order</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="8" style="color:#9ca3af">No records</td></tr>
          <?php endif; $sr=0; foreach($rows as $r): $sr++; ?>
            <tr>
              <td><?php echo $sr; ?></td>
              <td>
                <?php
                  $isChild = ((int)$r['parent_id'] !== 0);
                  $parentLabel = $isChild ? '<span style="opacity:.7">'.htmlspecialchars($r['parent_name'] ?: ('#'.$r['parent_id'])).'</span> &rsaquo; ' : '';
                  echo $parentLabel . htmlspecialchars($r['menu_name']);
                ?>
              </td>
              <td><?php echo htmlspecialchars($r['menu_link']); ?></td>
              <td><?php echo htmlspecialchars($r['icon']); ?></td>
              <td><?php echo htmlspecialchars($r['remarks'] ?? ''); ?></td>
              <td><?php echo (int)$r['orderby']; ?></td>
              <td><span class="badge <?php echo $r['status']?'on':'off'; ?>"><?php echo $r['status']?'Active':'Inactive'; ?></span></td>
              <td>
                <a class="btn gray" href="<?php echo keep_params(['view_access'=>$r['id']]); ?>">Access</a>
                <?php if ($CAN_EDIT): ?>
                  <a class="btn gray" href="<?php echo keep_params(['edit'=>$r['id'],'add'=>null]); ?>">Edit</a>
                <?php endif; ?>
                <?php if ($CAN_DELETE): ?>
                  <form method="post" style="display:inline" onsubmit="return confirm('Delete this menu?');">
                    <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn red" name="delete" type="submit">Delete</button>
                  </form>
                <?php endif; ?>
                <?php if (!$CAN_EDIT && !$CAN_DELETE): ?>
                  <span style="color:#9ca3af">—</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php else: /* -------- FORM -------- */ ?>
    <div class="card" id="formTop" style="max-width:980px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
        <h3 style="margin:0"><?php echo $edit ? 'Edit Menu' : 'Add Menu'; ?></h3>
        <a class="btn gray" href="<?php echo keep_params(['edit'=>null,'add'=>null]); ?>">Back to List</a>
      </div>

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

        <div style="grid-column:1/-1">
          <label>Menu Name*</label>
          <input name="menu_name" class="inp" required value="<?php echo htmlspecialchars($edit['menu_name'] ?? ''); ?>" <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
        </div>

        <div>
          <label>Menu Link (URL)</label>
          <input name="menu_link" class="inp" value="<?php echo htmlspecialchars($edit['menu_link'] ?? ''); ?>" placeholder="/adminconsole/..." <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
        </div>

        <div>
          <label>Icon (file/class)</label>
          <input name="icon" class="inp" value="<?php echo htmlspecialchars($edit['icon'] ?? ''); ?>" placeholder="e.g. dashboard.svg" <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
        </div>

        <div>
          <label>Parent Menu</label>
          <select name="parent_id" class="inp" <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
            <option value="0">None (Top level)</option>
            <?php foreach($parents as $p):
              $sel = (isset($edit['parent_id']) && (int)$edit['parent_id']===(int)$p['id']) ? 'selected' : ''; ?>
              <option value="<?php echo (int)$p['id']; ?>" <?php echo $sel; ?>>
                <?php echo htmlspecialchars($p['menu_name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>Order Level</label>
          <input type="number" name="orderby" class="inp" value="<?php echo htmlspecialchars($edit['orderby'] ?? 0); ?>" <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
        </div>

        <div style="grid-column:1/-1">
          <label>Remarks (optional)</label>
          <input name="remarks" class="inp" value="<?php echo htmlspecialchars($edit['remarks'] ?? ''); ?>" <?php echo (!$CAN_ADD && !$CAN_EDIT)?'disabled':''; ?>>
        </div>

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

        <?php if ($CAN_ADD || $CAN_EDIT): ?>
          <!-- Role-wise permission matrix -->
          <div style="grid-column:1/-1; margin-top:8px">
            <h4 style="margin:8px 0">Role Permissions for this Menu</h4>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th style="text-align:left">Role</th>
                    <th>View</th>
                    <th>Add</th>
                    <th>Edit</th>
                    <th>Delete</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($roles as $r):
                    $rid = (int)$r['id'];
                    $p   = $existingPerms[$rid] ?? ['view'=>0,'add'=>0,'edit'=>0,'delete'=>0];
                  ?>
                    <tr>
                      <td><?php echo htmlspecialchars($r['name']); ?></td>

                      <td style="text-align:center">
                        <input type="hidden" name="perms[<?php echo $rid; ?>][view]" value="0">
                        <input type="checkbox"
                               name="perms[<?php echo $rid; ?>][view]"
                               value="1"
                               <?php echo $p['view'] ? 'checked' : ''; ?>>
                      </td>

                      <td style="text-align:center">
                        <input type="hidden" name="perms[<?php echo $rid; ?>][add]" value="0">
                        <input type="checkbox"
                               name="perms[<?php echo $rid; ?>][add]"
                               value="1"
                               <?php echo $p['add'] ? 'checked' : ''; ?>>
                      </td>

                      <td style="text-align:center">
                        <input type="hidden" name="perms[<?php echo $rid; ?>][edit]" value="0">
                        <input type="checkbox"
                               name="perms[<?php echo $rid; ?>][edit]"
                               value="1"
                               <?php echo $p['edit'] ? 'checked' : ''; ?>>
                      </td>

                      <td style="text-align:center">
                        <input type="hidden" name="perms[<?php echo $rid; ?>][delete]" value="0">
                        <input type="checkbox"
                               name="perms[<?php echo $rid; ?>][delete]"
                               value="1"
                               <?php echo $p['delete'] ? 'checked' : ''; ?>>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
            <div style="color:#9ca3af; margin-top:6px">
              Tip: leave all unchecked for a role to remove its mapping for this menu.
            </div>
          </div>

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

    <script>
      (function(){
        function toTop(){ window.scrollTo({top:0, behavior:'instant'}); }
        if('scrollRestoration' in history) history.scrollRestoration='manual';
        window.addEventListener('load',function(){ toTop(); setTimeout(toTop,50); setTimeout(toTop,150); });
      })();
    </script>
  <?php endif; ?>
</div>
<?php
echo ob_get_clean();
