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

$page_title = 'Experience Description Master';
$TABLE     = 'jos_crm_expdescription';
$TYPE_TBL  = 'jos_app_experience_list';
$MENU_TBL  = '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 `".mysqli_real_escape_string($con,$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 `".mysqli_real_escape_string($con,$table)."` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  }
}
ensure_schema($con,$TABLE);

/* ---------- load Menu info / page title (safe) ---------- */
$menu = null;
$menu_title = $page_title;
$script_basename = basename($_SERVER['SCRIPT_NAME']);
$req_uri = $_SERVER['REQUEST_URI'] ?? '';

if ($con) {
  $candidates = ['link','path','file','url','name','title','label'];
  $existing = [];
  $colRes = mysqli_query($con, "SHOW COLUMNS FROM `".mysqli_real_escape_string($con,$MENU_TBL)."`");
  if ($colRes) {
    while ($colRow = mysqli_fetch_assoc($colRes)) {
      $colName = $colRow['Field'];
      if (in_array($colName, $candidates, true)) $existing[] = $colName;
    }
    mysqli_free_result($colRes);
  }

  if (!empty($existing)) {
    $clauses = [];
    foreach ($existing as $c) $clauses[] = "COALESCE(`{$c}`,'') LIKE ?";
    $where_sql = implode(' OR ', $clauses);
    $sql = "SELECT * FROM `".mysqli_real_escape_string($con,$MENU_TBL)."` WHERE ({$where_sql}) ORDER BY id DESC LIMIT 1";
    $st = $con->prepare($sql);
    if ($st) {
      $params = [];
      foreach ($existing as $c) {
        if ($c === 'url') $params[] = "%{$req_uri}%";
        else $params[] = "%{$script_basename}%";
      }
      $types = str_repeat('s', count($params));
      $bind_names = [];
      $bind_names[] = $types;
      foreach ($params as $i => $p) $bind_names[] = &$params[$i];
      call_user_func_array([$st, 'bind_param'], $bind_names);
      $st->execute();
      $res = $st->get_result();
      if ($res && ($m = $res->fetch_assoc())) {
        $menu = $m;
        if (!empty($m['title'])) $menu_title = $m['title'];
        elseif (!empty($m['name'])) $menu_title = $m['name'];
        elseif (!empty($m['label'])) $menu_title = $m['label'];
      }
      $st->close();
    }
  }
}
$page_title = $menu_title;

/* ---------- access control helper ---------- */
function has_access($action) {
  $me = $_SESSION['admin_user'] ?? [];
  if (isset($me['can_'.$action])) return (bool)$me['can_'.$action];
  if (!empty($me['permissions']) && is_array($me['permissions'])) {
    global $menu;
    if ($menu && isset($me['permissions'][$menu['id']]) && isset($me['permissions'][$menu['id']][$action])) {
      return (bool)$me['permissions'][$menu['id']][$action];
    }
    if ($menu && isset($menu['link']) && isset($me['permissions'][$menu['link']]) && isset($me['permissions'][$menu['link']][$action])) {
      return (bool)$me['permissions'][$menu['link']][$action];
    }
    if (isset($me['permissions'][$action])) return (bool)$me['permissions'][$action];
  }
  global $menu;
  if ($menu && is_array($menu)) {
    $candidates = [$action,'can_'.$action,$action.'_perm',$action.'_permission','perm_'.$action,'allow_'.$action];
    foreach ($candidates as $col) {
      if (array_key_exists($col, $menu)) return (bool)$menu[$col];
    }
  }
  return true; // default allow for backward compatibility
}

/* ---------- load types ---------- */
$types = [];
$tr = mysqli_query($con, "SELECT id,name FROM `".mysqli_real_escape_string($con,$TYPE_TBL)."` WHERE status=1 ORDER BY name ASC");
while ($tr && $row = mysqli_fetch_assoc($tr)) $types[(int)$row['id']] = $row['name'];

/* ---------- POST ---------- */
$err = ''; $ok = '';
$me = $_SESSION['admin_user'] ?? [];
$myid = (int)($me['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err = 'Invalid request.';
  } else {
    if (isset($_POST['save']) && !has_access('add') && !has_access('edit')) {
      $err = 'You do not have permission to save.';
    } elseif (isset($_POST['delete']) && !has_access('delete')) {
      $err = 'You do not have permission to delete.';
    } else {
      if (isset($_POST['save'])) {
        $id     = (int)($_POST['id'] ?? 0);
        $title  = clean($_POST['title'] ?? '');
        $desc   = clean($_POST['description'] ?? '');
        $etype  = (int)($_POST['etype'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);

        if ($title === '')           $err = 'Title is required.';
        elseif ($etype <= 0)         $err = 'Please select an Experience Type.';
        else {
          $dup_sql = "SELECT id FROM `".mysqli_real_escape_string($con,$TABLE)."` WHERE LOWER(title)=LOWER(?) AND etype=?";
          if ($id > 0) $dup_sql .= " AND id<>?";
          $dup_sql .= " LIMIT 1";
          $st = $con->prepare($dup_sql);
          if ($st) {
            if ($id > 0) $st->bind_param('sii', $title, $etype, $id);
            else $st->bind_param('si', $title, $etype);
            $st->execute();
            $dup = $st->get_result()->fetch_assoc();
            $st->close();
          } else $dup = null;

          if ($dup) {
            $err = 'This title already exists for the selected Experience Type.';
          } else {
            $hasCreated = col_exists($con, $TABLE, 'created_by');
            $hasMod     = col_exists($con, $TABLE, 'modified_by');

            if ($id > 0) {
              if (!has_access('edit')) { $err = 'You do not have permission to edit.'; }
              else {
                if ($hasMod) {
                  $sql = "UPDATE `".mysqli_real_escape_string($con,$TABLE)."` SET title=?, description=?, etype=?, status=?, modified_by=? WHERE id=?";
                  $st = $con->prepare($sql); $st->bind_param('ssiiii', $title, $desc, $etype, $status, $myid, $id);
                } else {
                  $sql = "UPDATE `".mysqli_real_escape_string($con,$TABLE)."` SET title=?, description=?, etype=?, status=? WHERE id=?";
                  $st = $con->prepare($sql); $st->bind_param('ssiii', $title, $desc, $etype, $status, $id);
                }
                if ($st) { $ok = $st->execute() ? 'Updated successfully.' : 'Update failed.'; $st->close(); }
                else $err = 'Database error while preparing update.';
              }
            } else {
              if (!has_access('add')) { $err = 'You do not have permission to add.'; }
              else {
                if ($hasCreated && $hasMod) {
                  $sql = "INSERT INTO `".mysqli_real_escape_string($con,$TABLE)."` (title,description,etype,status,created_by,modified_by) VALUES (?,?,?,?,?,?)";
                  $st = $con->prepare($sql); $st->bind_param('ssiiii', $title, $desc, $etype, $status, $myid, $myid);
                } else {
                  $sql = "INSERT INTO `".mysqli_real_escape_string($con,$TABLE)."` (title,description,etype,status) VALUES (?,?,?,?)";
                  $st = $con->prepare($sql); $st->bind_param('ssii', $title, $desc, $etype, $status);
                }
                if ($st) { $ok = $st->execute() ? 'Added successfully.' : 'Insert failed.'; $st->close(); $_POST = []; }
                else $err = 'Database error while preparing insert.';
              }
            }
          }
        }
      }

      if (isset($_POST['delete']) && !$err) {
        $id = (int)($_POST['id'] ?? 0);
        if (!has_access('delete')) {
          $err = 'You do not have permission to delete.';
        } else {
          $st = $con->prepare("DELETE FROM `".mysqli_real_escape_string($con,$TABLE)."` WHERE id=?");
          if ($st) { $st->bind_param('i', $id); $ok = $st->execute() ? 'Deleted successfully.' : 'Delete failed.'; $st->close(); }
          else $err = 'Database error while preparing delete.';
        }
      }
    }
  }
}

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

/* ---------- edit row ---------- */
$edit = null;
if ($mode === 'form' && isset($_GET['edit'])) {
  $eid = (int)$_GET['edit'];
  $st = $con->prepare("SELECT id,title,description,etype,status FROM `".mysqli_real_escape_string($con,$TABLE)."` WHERE id=?");
  if ($st) { $st->bind_param('i', $eid); $st->execute(); $edit = $st->get_result()->fetch_assoc(); $st->close(); }
}

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

$where = " WHERE 1=1 "; $bind = []; $type = '';
if ($q !== '') { $like = "%$q%"; $where .= " AND (d.title LIKE ? OR d.description LIKE ?)"; $bind[] = $like; $bind[] = $like; $type .= 'ss'; }
if ($fType > 0) { $where .= " AND d.etype=?"; $bind[] = $fType; $type .= 'i'; }

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

$sql = "SELECT d.id,d.title,d.description,d.etype,d.status, t.name AS type_name
        FROM `".mysqli_real_escape_string($con,$TABLE)."` d
        LEFT JOIN `".mysqli_real_escape_string($con,$TYPE_TBL)."` t ON t.id=d.etype
        $where
        ORDER BY d.id DESC";
if (!$all) $sql .= " LIMIT $lim";
$st = $con->prepare($sql);
$rows = [];
if ($st) {
  if ($bind) $st->bind_param($type, ...$bind);
  $st->execute();
  $rs = $st->get_result();
  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 title or description..." value="<?=htmlspecialchars($q)?>">
        <select name="etype" class="inp">
          <option value="0">All Experience Types</option>
          <?php foreach ($types as $tid => $tname): ?>
            <option value="<?=$tid?>" <?=$fType===$tid?'selected':''?>><?=htmlspecialchars($tname)?></option>
          <?php endforeach; ?>
        </select>
        <button class="btn gray" type="submit">Search</button>
        <?php if (!$all && $total > $lim): ?>
          <a class="btn gray" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . keep_params(['all'=>1]))?>">View All (<?=$total?>)</a>
        <?php endif; ?>
        <?php if ($all): ?>
          <a class="btn gray" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . keep_params(['all'=>null]))?>">Last 50</a>
        <?php endif; ?>
      </form>

      <?php if (has_access('add')): ?>
        <a class="btn green" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . keep_params(['add'=>1,'edit'=>null]))?>">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).'”' : '' ?>
      <?= $fType > 0 ? 'in ' . htmlspecialchars($types[$fType] ?? ('Type #'.$fType)) : '' ?>
      <?= !$all ? '(latest first)' : '' ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th><th>Title</th><th>Experience Type</th><th>Description</th><th>Status</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><?=htmlspecialchars($r['title'])?></td>
            <td><?=htmlspecialchars($r['type_name'] ?? '—')?></td>
            <td class="desc" title="<?=htmlspecialchars($r['description'])?>"><?=htmlspecialchars($r['description'])?></td>
            <td><span class="badge <?=$r['status']?'on':'off'?>"><?=$r['status'] ? 'Active' : 'Inactive'?></span></td>
            <td>
              <?php if (has_access('edit')): ?>
                <a class="btn gray" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . keep_params(['edit' => (int)$r['id'], 'add' => null]))?>">Edit</a>
              <?php endif; ?>

              <?php if (has_access('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:900px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <h3 style="margin:0"><?= $edit ? 'Edit Description' : 'Add Description' ?></h3>
      <a class="btn gray" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . 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; ?>

    <?php
      $can_save = $edit ? has_access('edit') : has_access('add');
      if (!$can_save): ?>
        <div style="margin:8px 0;color:#7c2d2d;background:#fff3f2;padding:8px;border-radius:6px">
          You do not have permission to <?= $edit ? 'edit' : 'add' ?> records on this page.
        </div>
    <?php endif; ?>

    <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 style="grid-column:1/-1">
        <label>Title*</label>
        <input name="title" class="inp" required value="<?=htmlspecialchars($edit['title'] ?? '')?>" <?= $can_save ? '' : 'disabled'?>>
      </div>

      <div>
        <label>Experience Type*</label>
        <select name="etype" class="inp" required <?= $can_save ? '' : 'disabled'?>>
          <option value="">-- Select --</option>
          <?php $cur = (int)($edit['etype'] ?? 0); foreach ($types as $tid => $tname): ?>
            <option value="<?=$tid?>" <?=$cur === $tid ? 'selected' : ''?>><?=htmlspecialchars($tname)?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>Status</label>
        <?php $st = isset($edit['status']) ? (int)$edit['status'] : 1; ?>
        <select name="status" class="inp" <?= $can_save ? '' : 'disabled'?>>
          <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>Description</label>
        <textarea name="description" rows="6" class="inp" style="width:100%" <?= $can_save ? '' : 'disabled'?>><?=htmlspecialchars($edit['description'] ?? '')?></textarea>
      </div>

      <div style="grid-column:1/-1;display:flex;gap:8px;align-items:center">
        <?php if ($can_save): ?>
          <button class="btn green" name="save" type="submit">Save</button>
        <?php else: ?>
          <a class="btn gray" href="<?=htmlspecialchars($_SERVER['PHP_SELF'] . keep_params(['edit'=>null,'add'=>null]))?>">Back</a>
        <?php endif; ?>
        <!-- Delete removed from edit form as requested -->
      </div>
    </form>
  </div>
<?php endif; ?> 

<?php
echo ob_get_clean();
