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

$page_title = 'Roles & Responsibilities';
$TABLE     = 'jos_erp_roles';
$JOBTABLE  = 'jos_crm_jobpost';

/* ---------- helpers ---------- */
function keep_params(array $changes = []) {
  $qs = $_GET; foreach ($changes as $k=>$v) { if ($v===null) unset($qs[$k]); else $qs[$k]=$v; }
  return '?' . http_build_query($qs);
}
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($con,$table){
  if(!col_exists($con,$table,'status')){
    mysqli_query($con,"ALTER TABLE `$table` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  }
}
ensure_schema($con,$TABLE);

/* ---------- load title from Menu Master (uses menu_name/menu_link) ---------- */
function load_menu_title($con){
  $table = 'jos_admin_menus';
  $script = basename(__FILE__); // e.g. roles_responsibilities.php
  $like = '%' . $script . '%';

  // Your table uses menu_name and menu_link based on the screenshot
  $sql = "SELECT menu_name FROM `$table`
          WHERE menu_link LIKE ? OR menu_link = ?
          LIMIT 1";
  if ($st = $con->prepare($sql)) {
    $st->bind_param('ss', $like, $script);
    $st->execute();
    $res = $st->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $st->close();
    if ($row && !empty($row['menu_name'])) return $row['menu_name'];
  }
  return null;
}
$mt = load_menu_title($con);
if ($mt) $page_title = $mt;

/* ---------- user access control ---------- */
$me   = $_SESSION['admin_user'] ?? [];
$myid = (int)($me['id'] ?? 0);

function parse_permissions($me) {
  if (!$me) return [];
  if (isset($me['permissions']) && $me['permissions']) {
    if (is_array($me['permissions'])) return array_map('strtolower', $me['permissions']);
    $parts = array_filter(array_map('trim', explode(',', $me['permissions'])));
    return array_map('strtolower', $parts);
  }
  $out = [];
  foreach (['view','add','edit','delete'] as $k) {
    $ck = 'can_' . $k;
    if (isset($me[$ck]) && ($me[$ck]==1 || $me[$ck]==='1' || $me[$ck]===true)) $out[]=$k;
  }
  return $out;
}
$__user_perms = parse_permissions($me);
function has_access($me,$cap){
  global $__user_perms;
  if (!$me) return false;
  if ((int)($me['id']??0)===1) return true; // admin full access
  return in_array(strtolower($cap),$__user_perms,true);
}

/* ---------- deny view ---------- */
if (!has_access($me,'view')) {
  echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
  echo '<div class="card"><h3>Access Denied</h3><div class="badge off">You do not have permission to view this page.</div></div>';
  exit;
}

/* ---------- AJAX: position suggestions ---------- */
if (isset($_GET['ajax']) && $_GET['ajax']==='positions') {
  header('Content-Type: application/json; charset=utf-8');
  $q = '%' . (mysqli_real_escape_string($con, clean($_GET['q'] ?? ''))) . '%';
  $sql="SELECT id, name FROM `$JOBTABLE` WHERE status=1 AND name LIKE ? ORDER BY name ASC LIMIT 20";
  $st=$con->prepare($sql); $st->bind_param('s',$q); $st->execute();
  $rs=$st->get_result(); $out=[];
  while($r=$rs->fetch_assoc()) $out[]=['id'=>(int)$r['id'], 'name'=>$r['name']];
  $st->close();
  echo json_encode($out);
  exit;
}
function get_position_name($con,$id){
  if ($id<=0) return '';
  $st=$con->prepare("SELECT name FROM `jos_crm_jobpost` WHERE id=? LIMIT 1");
  $st->bind_param('i',$id); $st->execute();
  $res = $st->get_result();
  $name = $res ? ($res->fetch_assoc()['name'] ?? '') : '';
  $st->close();
  return (string)$name;
}

/* ---------- POST ---------- */
$flash_ok = clean($_GET['ok'] ?? '');
$err=''; $ok='';

if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request.';
  } else {
    /* delete */
    if (isset($_POST['delete'])) {
      if (!has_access($me,'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);
        $ok=$st->execute()?'Deleted successfully.':'Delete failed.'; $st->close();
        if ($ok==='Deleted successfully.') {
          header('Location: ' . keep_params(['ok'=>'Deleted successfully.']));
          exit;
        }
      }
    }
    /* save (add/update) */
    if (isset($_POST['save'])) {
      $id       = (int)($_POST['id'] ?? 0);
      if ($id>0 && !has_access($me,'edit')) $err='You do not have permission to edit.';
      elseif ($id<=0 && !has_access($me,'add')) $err='You do not have permission to add.';
      else {
        $position = (int)($_POST['position'] ?? 0);
        $roles    = clean($_POST['roles'] ?? '');
        $status   = (int)($_POST['status'] ?? 1);
        if ($position<=0) $err='Please select a Job Position from suggestions.';
        elseif ($roles==='') $err='Roles & Responsibilities text is required.';
        else {
          // duplicate check
          $dup_sql="SELECT id FROM $TABLE WHERE position=? AND LOWER(roles)=LOWER(?)";
          if ($id>0) $dup_sql.=" AND id<>?";
          $st=$con->prepare($dup_sql." LIMIT 1");
          if ($id>0) $st->bind_param('isi',$position,$roles,$id); else $st->bind_param('is',$position,$roles);
          $st->execute(); $dup=$st->get_result()->fetch_assoc(); $st->close();
          if ($dup) $err='This entry already exists for the selected Job Position.';
          else {
            $hasCreated = col_exists($con,$TABLE,'created_by');
            $hasMod     = col_exists($con,$TABLE,'modified_by');
            if ($id>0){
              if ($hasMod){
                $sql="UPDATE $TABLE SET position=?, roles=?, status=?, modified_by=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('isiii',$position,$roles,$status,$myid,$id);
              } else {
                $sql="UPDATE $TABLE SET position=?, roles=?, status=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('isii',$position,$roles,$status,$id);
              }
              $ok=$st->execute()?'Updated successfully.':'Update failed.'; $st->close();
              if ($ok==='Updated successfully.') {
                header('Location: ' . keep_params(['edit'=>null,'add'=>null,'prefpos'=>null,'ok'=>'Updated successfully.']));
                exit;
              }
            } else {
              if ($hasCreated && $hasMod){
                $sql="INSERT INTO $TABLE (position,roles,status,created_by,modified_by) VALUES (?,?,?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('isiii',$position,$roles,$status,$myid,$myid);
              } else {
                $sql="INSERT INTO $TABLE (position,roles,status) VALUES (?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('isi',$position,$roles,$status);
              }
              $ok=$st->execute()?'Added successfully.':'Insert failed.'; $st->close();
              if ($ok==='Added successfully.') {
                header('Location: ' . keep_params(['edit'=>null,'add'=>null,'prefpos'=>null,'ok'=>'Added successfully.']));
                exit;
              }
            }
          }
        }
      }
    }
  }
}

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

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

/* ---------- filters ---------- */
$qPos = (int)($_GET['position'] ?? 0);
$qTxt = clean($_GET['q'] ?? '');
$onlyNoRoles = (int)($_GET['no_roles'] ?? 0) === 1;
$all  = isset($_GET['all']); $lim = $all ? 0 : 50;

/* ---------- list data ---------- */
$rows=[]; $total=0;
if ($onlyNoRoles) {
  // Positions with zero roles
  $sql = "SELECT p.id AS pid, p.name AS position_name
          FROM $JOBTABLE p
          LEFT JOIN $TABLE r ON r.position=p.id
          WHERE p.status=1
          GROUP BY p.id
          HAVING COUNT(r.id)=0
          ORDER BY p.name ASC";
  if (!$all) $sql .= " LIMIT $lim";
  $rs = $con->query($sql);
  while($r = $rs->fetch_assoc()){
    $r['mode']='emptypos'; $r['rcnt']=0;
    $rows[] = $r;
  }
  $total = count($rows);
} else {
  $where=" WHERE 1=1 "; $bind=[]; $type='';
  if ($qPos>0){ $where.=" AND r.position=?"; $bind[]=$qPos; $type.='i'; }
  if ($qTxt!==''){ $like="%$qTxt%"; $where.=" AND r.roles LIKE ?"; $bind[]=$like; $type.='s'; }

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

  $sql="SELECT r.id,r.position,r.roles,r.status, p.name AS position_name,
               (SELECT COUNT(*) FROM $TABLE rr WHERE rr.position=r.position) AS rcnt
        FROM $TABLE r
        LEFT JOIN $JOBTABLE p ON p.id=r.position
        $where
        ORDER BY r.id DESC";
  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()){
    $r['rcnt'] = (int)$r['rcnt'];
    $rows[] = $r;
  }
  $st->close();
}

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

<?php if ($mode==='list'): ?>
  <div class="card">
    <div class="toolbar">
      <form method="get" class="search" id="searchForm" autocomplete="off">
        <input type="hidden" name="no_roles" id="no_roles" value="<?= $onlyNoRoles?1:0 ?>">
        <div class="ac-wrap">
          <input type="hidden" name="position" id="s_position_id" value="<?= (int)$qPos ?>">
          <input type="text" class="inp" id="s_position_name" placeholder="Job Position (type to search)" value="<?= htmlspecialchars(get_position_name($con, $qPos)) ?>">
          <div class="ac-list" id="s_ac" style="display:none"></div>
        </div>
        <input type="text" name="q" class="inp" placeholder="Search roles text..." value="<?=htmlspecialchars($qTxt)?>">
        <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; ?>
        <label class="check">
          <input type="checkbox" id="toggle_no_roles" <?= $onlyNoRoles?'checked':'' ?> onclick="document.getElementById('no_roles').value=this.checked?1:0; this.form.submit();">
          Show “No roles added”
        </label>
      </form>
      <?php if (has_access($me,'add')): ?><a class="btn green" href="<?=htmlspecialchars(keep_params(['add'=>1]))?>">Add New</a><?php endif; ?>
    </div>

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

    <div class="hint" style="margin:8px 0">
      <?php if(!$onlyNoRoles): ?>
        Showing <strong><?= !$all ? count($rows) : $total ?></strong> of <strong><?= $total ?></strong> <?= $qPos>0 ? 'for ' . htmlspecialchars(get_position_name($con,$qPos)) : '' ?> <?= $qTxt!=='' ? 'containing “'.htmlspecialchars($qTxt).'”' : '' ?> <?= !$all ? '(latest first)' : '' ?>
      <?php else: ?>
        Showing <strong><?= !$all ? count($rows) : $total ?></strong> job positions with <strong>0 roles</strong>.
      <?php endif; ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th>
          <th>Job Position</th>
          <?php if(!$onlyNoRoles): ?><th>Roles & Responsibilities</th><?php endif; ?>
          <th>Roles Count</th>
          <?php if(!$onlyNoRoles): ?><th>Status</th><?php endif; ?>
          <th>Actions</th>
        </tr></thead>
        <tbody>
        <?php if(!$rows): ?><tr><td colspan="6" class="hint">No records</td></tr><?php endif; ?>
        <?php $sr=0; foreach($rows as $r): $sr++; ?>
          <?php if ($onlyNoRoles && ($r['mode'] ?? '')==='emptypos'): ?>
            <tr>
              <td><?=$sr?></td>
              <td><?=htmlspecialchars($r['position_name'])?></td>
              <td>0</td>
              <td>
                <?php if (has_access($me,'add')): ?>
                  <a class="btn green" href="<?=htmlspecialchars(keep_params(['add'=>1,'prefpos'=>(int)$r['pid']]))?>">Add Role</a>
                <?php else: ?>
                  <span class="hint">No permission to add</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php else: ?>
            <tr>
              <td><?=$sr?></td>
              <td><?=htmlspecialchars($r['position_name'] ?? '—')?></td>
              <td class="roles" title="<?=htmlspecialchars($r['roles'])?>"><?=htmlspecialchars($r['roles'])?></td>
              <td><?= (int)$r['rcnt'] ?></td>
              <td><span class="badge <?= ($r['status']? 'on':'off') ?>"><?= $r['status']?'Active':'Inactive' ?></span></td>
              <td>
                <?php if (has_access($me,'edit')): ?>
                  <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>(int)$r['id']]))?>">Edit</a>
                <?php else: ?>
                  <span class="btn disabled">Edit</span>
                <?php endif; ?>

                <?php if (has_access($me,'delete')): ?>
                  <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');">
                    <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 else: ?>
                  <span class="btn disabled">Delete</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endif; ?>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

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

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

    <?php
      $canSave = ($edit ? has_access($me,'edit') : has_access($me,'add'));
      $prefill_id = $edit ? (int)$edit['position'] : (int)$prefpos;
      $prefill_name = get_position_name($con, $prefill_id);
      $st = isset($edit['status']) ? (int)$edit['status'] : 1;
    ?>
    <form method="post" 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; ?>

      <div class="ac-wrap">
        <label>Job Position*</label>
        <input type="hidden" name="position" id="f_position_id" value="<?= $prefill_id ?>">
        <input type="text" class="inp" id="f_position_name" placeholder="Type to search Job Position" value="<?= htmlspecialchars($prefill_name) ?>">
        <div class="ac-list" id="f_ac" style="display:none"></div>
      </div>

      <div>
        <label>Status</label>
        <select name="status" class="inp">
          <option value="1" <?=$st===1?'selected':''?>>Active</option>
          <option value="0" <?=$st===0?'selected':''?>>Inactive</option>
        </select>
      </div>

      <div style="grid-column:1/-1">
        <label>Roles & Responsibilities*</label>
        <textarea name="roles" rows="8" class="inp" style="width:100%" <?= $canSave ? '' : 'disabled' ?>><?=htmlspecialchars($edit['roles'] ?? '')?></textarea>
      </div>

      <div style="grid-column:1/-1">
        <?php if ($canSave): ?>
          <button class="btn green" name="save" type="submit">Save</button>
        <?php else: ?>
          <span class="hint">You do not have permission to <?= $edit ? 'edit' : 'add' ?> records.</span>
        <?php endif; ?>
      </div>
    </form>
  </div>
<?php endif; ?>

<script>
/* -------- minimal autocomplete (no libs) -------- */
function wireAutocomplete(inputId, hiddenId, menuId){
  const inp = document.getElementById(inputId);
  const hid = document.getElementById(hiddenId);
  const menu = document.getElementById(menuId);
  if(!inp) return;
  let last = '', timer = null;

  function close(){ menu.style.display='none'; menu.innerHTML=''; }
  function choose(id, name){ hid.value = id; inp.value = name; close(); }
  function render(list){
    if(!list.length){ close(); return; }
    menu.innerHTML = '';
    list.forEach(x=>{
      const d=document.createElement('div');
      d.className='ac-item';
      d.textContent=x.name;
      d.onclick=()=>choose(x.id, x.name);
      menu.appendChild(d);
    });
    menu.style.display='block';
  }
  async function search(q){
    try {
      const r = await fetch('?ajax=positions&q=' + encodeURIComponent(q));
      if(!r.ok) return close();
      const data = await r.json();
      render(data);
    } catch(e) { close(); }
  }
  inp.addEventListener('input', ()=>{
    hid.value = '';
    const q = inp.value.trim();
    if (q===last) return;
    last = q;
    if (timer) clearTimeout(timer);
    if (q.length<2){ close(); return; }
    timer = setTimeout(()=>search(q), 180);
  });
  inp.addEventListener('blur', ()=> setTimeout(close, 150));
  inp.addEventListener('focus', ()=>{
    if (inp.value.trim().length>=2) search(inp.value.trim());
  });
}
wireAutocomplete('s_position_name','s_position_id','s_ac');   // search bar 
wireAutocomplete('f_position_name','f_position_id','f_ac');   // form
</script>

<?php
echo ob_get_clean();
