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

$page_title = 'Experience Type Master';
$TABLE = 'jos_app_experience_list';

/* -------------------------
   Load title & permissions
   from jos_admin_menus (robust)
   ------------------------- */
function load_menu_title_and_perms($con) {
  $out = [
    'title' => null,
    'perms' => [
      'view' => true,
      'add'  => true,
      'edit' => true,
      'delete'=> true,
    ],
  ];

  // Check table exists and fetch columns
  $cols = [];
  $rc = mysqli_query($con, "SHOW COLUMNS FROM `jos_admin_menus`");
  if (!$rc) return $out; // table missing or no access: return defaults (non-blocking)
  while ($c = mysqli_fetch_assoc($rc)) $cols[] = $c['Field'];

  // helper: find first existing column from a list
  $first_col = function(array $cand) use ($cols) {
    foreach ($cand as $c) if (in_array($c, $cols, true)) return $c;
    return null;
  };

  // candidate columns for link/path and title
  $link_col = $first_col(['link','url','path','menu_link','filename','file','route','href']);
  $title_col = $first_col(['title','name','menu_title','label','text']);

  if (!$link_col) {
    // can't find any column to match current script -> return defaults
    return $out;
  }

  // build pattern to match script name / request uri
  $script = basename($_SERVER['SCRIPT_NAME']);
  $try_patterns = [
    $script,
    $_SERVER['SCRIPT_NAME'],
    $_SERVER['REQUEST_URI'],
  ];

  $found = null;
  foreach ($try_patterns as $pat) {
    if (!$pat) continue;
    $p = "%$pat%";
    $sql = "SELECT * FROM `jos_admin_menus` WHERE `$link_col` LIKE ? LIMIT 1";
    if ($st = $con->prepare($sql)) {
      $st->bind_param('s', $p);
      if ($st->execute()) {
        $res = $st->get_result();
        if ($res && $row = $res->fetch_assoc()) {
          $found = $row;
          $st->close();
          break;
        }
      }
      $st->close();
    }
  }

  if (!$found) return $out;

  // set title if present
  if ($title_col && !empty($found[$title_col])) $out['title'] = $found[$title_col];

  // permission column candidates (only from columns that exist)
  $colMap = [
    'view'   => ['allow_view','can_view','is_view','view','allow_viewing','perm_view'],
    'add'    => ['allow_add','can_add','is_add','add','allow_create','perm_add'],
    'edit'   => ['allow_edit','can_edit','is_edit','edit','allow_modify','perm_edit'],
    'delete' => ['allow_delete','can_delete','is_delete','delete','allow_remove','perm_delete'],
  ];

  foreach ($colMap as $k => $candidates) {
    foreach ($candidates as $col) {
      if (in_array($col, $cols, true)) {
        $val = $found[$col];
        $ok = false;
        if (is_numeric($val)) $ok = ((int)$val) === 1;
        else {
          $val_norm = strtolower(trim((string)$val));
          if (in_array($val_norm, ['1','y','yes','true','on'])) $ok = true;
          else $ok = false;
        }
        $out['perms'][$k] = $ok;
        break;
      }
    }
    // if not found, leave default true (non-blocking)
  }

  // If a json/text 'permissions' column exists, parse it and override
  if (in_array('permissions', $cols, true) && !empty($found['permissions'])) {
    $pjson = @json_decode($found['permissions'], true);
    if (is_array($pjson)) {
      foreach (['view','add','edit','delete'] as $k) {
        if (isset($pjson[$k])) $out['perms'][$k] = (bool)$pjson[$k];
      }
    }
  }

  return $out;
}

$menu = load_menu_title_and_perms($con);
if ($menu['title']) $page_title = $menu['title'];
$PERMS = $menu['perms'];

/* ---------- 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 ensure_schema($con,$table){
  $r = mysqli_query($con,"SHOW COLUMNS FROM `$table` LIKE 'status'");
  if(!$r || mysqli_num_rows($r)==0){
    mysqli_query($con,"ALTER TABLE `$table` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  }
}
ensure_schema($con,$TABLE);

/* ---------- simple access helper (current user) ---------- */
function deny($msg='Access denied.') {
  header('HTTP/1.1 403 Forbidden');
  echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
  echo '<div class="card"><h3>Access denied</h3><div class="badge off" style="margin:8px 0">'.htmlspecialchars($msg).'</div>';
  echo '<div style="margin-top:8px"><a class="btn gray" href="/adminconsole/index.php">Back</a></div></div>';
  exit;
}

/* enforce view permission early */
if (empty($PERMS['view'])) {
  deny('You do not have permission to view this page.');
}

/* ---------- POST ---------- */
$err=''; $ok='';
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request.';
  } else {
    if (isset($_POST['save'])) {
      $id     = (int)($_POST['id'] ?? 0);
      if ($id>0 && empty($PERMS['edit'])) {
        $err = 'You do not have permission to edit.';
      } elseif ($id===0 && empty($PERMS['add'])) {
        $err = 'You do not have permission to add.';
      } else {
        $name   = clean($_POST['name'] ?? '');
        $status = (int)($_POST['status'] ?? 1);

        if ($name==='') {
          $err='Name is required.';
        } else {
          $nameEsc = mysqli_real_escape_string($con, $name);
          $dup = mysqli_query($con, "SELECT id FROM `$TABLE` WHERE LOWER(name)=LOWER('$nameEsc')" . ($id? " AND id<>$id" : ""));
          if ($dup && mysqli_num_rows($dup)>0) {
            $err='This experience type already exists.';
          } else {
            if ($id>0){
              $st=$con->prepare("UPDATE $TABLE SET name=?, status=? WHERE id=?");
              $st->bind_param('sii',$name,$status,$id);
              $ok=$st->execute()?'Updated successfully':'Update failed';
              $st->close();
            } else {
              $st=$con->prepare("INSERT INTO $TABLE (name, status) VALUES (?,?)");
              $st->bind_param('si',$name,$status);
              $ok=$st->execute()?'Added successfully':'Insert failed';
              $st->close();
            }
          }
        }
      }
    }
    if (isset($_POST['delete'])) {
      if (empty($PERMS['delete'])) {
        $err = 'You do not have permission to delete.';
      } else {
        $id=(int)$_POST['id'];
        $st=$con->prepare("DELETE FROM $TABLE WHERE id=?");
        $st->bind_param('i',$id);
        $ok=$st->execute()?'Deleted successfully':'Delete failed';
        $st->close();
      }
    }
  }
}

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

/* ---------- edit row ---------- */
$edit=null;
if ($mode==='form' && isset($_GET['edit'])){
  $eid=(int)$_GET['edit'];
  if (empty($PERMS['edit'])) {
    deny('You do not have permission to edit this item.');
  }
  $st=$con->prepare("SELECT id,name,status FROM $TABLE WHERE id=?");
  $st->bind_param('i',$eid); $st->execute();
  $edit=$st->get_result()->fetch_assoc();
  $st->close();
}

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

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

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

$sql="SELECT id,name,status
      FROM $TABLE
      $where
      ORDER BY id DESC";
if (!$all) $sql.=" LIMIT $lim";
$st=$con->prepare($sql);
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$rs=$st->get_result(); $rows=[];
while($r=$rs->fetch_assoc()) $rows[]=$r;
$st->close();

/* ---------- view ---------- */
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">
        <input type="text" name="q" class="inp" placeholder="Search by experience type..." value="<?=htmlspecialchars($q)?>">
        <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; ?>
      </form>
      <?php if (!empty($PERMS['add'])): ?>
        <a class="btn green" href="<?=htmlspecialchars(keep_params(['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 “'.htmlspecialchars($q).'”' : '' ?>
      <?= !$all ? '(latest first)' : '' ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th><th>Name</th><th>Status</th><th>Actions</th>
        </tr></thead>
        <tbody>
        <?php if(!$rows): ?><tr><td colspan="4" style="color:#9ca3af">No records</td></tr><?php endif; ?>
        <?php $sr=0; foreach($rows as $r): $sr++; ?>
          <tr>
            <td><?=$sr?></td>
            <td><?=htmlspecialchars($r['name'])?></td>
            <td><span class="badge <?=$r['status']?'on':'off'?>"><?=$r['status']?'Active':'Inactive'?></span></td>
            <td>
              <?php if (!empty($PERMS['edit'])): ?>
                <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>(int)$r['id']]))?>">Edit</a>
              <?php endif; ?>

              <?php if (!empty($PERMS['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 endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

<?php else: /* 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"><?= $edit ? 'Edit Experience Type' : 'Add Experience Type' ?></h3>
      <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>null,'add'=>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; ?>

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

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

      <div>
        <label>Status</label>
        <?php $st = isset($edit['status']) ? (int)$edit['status'] : 1; ?>
        <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">
        <?php
          $isEdit = (bool)$edit;
          if (($isEdit && empty($PERMS['edit'])) || (!$isEdit && empty($PERMS['add']))) {
            echo '<div class="badge off">You do not have permission to '.($isEdit ? 'edit' : 'add').'.</div>';
          } else {
            echo '<button class="btn green" name="save" type="submit">Save</button>';
          }
        ?>
      </div>
    </form>
  </div>
<?php endif;

echo ob_get_clean();
