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

/**
 * CV Project Type Master
 * - Loads title from jos_admin_menus.menu_name
 * - Applies simple access control:
 *     Super Admin (id=1 or role_id=1) => full access
 *     Others => view-only (until role permissions table is available)
 */

$page_title = 'CV Project Type Master';
$TABLE = 'jos_app_can_projecttype';

/* ---------- 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");
  }
  if(!col_exists($con,$table,'order_by')){
    mysqli_query($con,"ALTER TABLE `$table` ADD `order_by` INT NOT NULL DEFAULT 0");
  } else {
    mysqli_query($con,"ALTER TABLE `$table` MODIFY `order_by` INT NOT NULL DEFAULT 0");
  }
}
ensure_schema($con,$TABLE);

/* ---------- load menu info ---------- */
$menu = null;
$self_file = basename($_SERVER['PHP_SELF']);
if ($r = mysqli_query($con, "SHOW TABLES LIKE 'jos_admin_menus'")) {
  if (mysqli_num_rows($r) > 0) {
    $st = $con->prepare("SELECT * FROM jos_admin_menus WHERE menu_link=? LIMIT 1");
    $st->bind_param('s', $self_file);
    $st->execute();
    $res = $st->get_result();
    if ($res->num_rows > 0) $menu = $res->fetch_assoc();
    $st->close();
    if (!$menu) {
      $st2 = $con->prepare("SELECT * FROM jos_admin_menus WHERE menu_link LIKE CONCAT('%',?,'%') LIMIT 1");
      $st2->bind_param('s', $self_file);
      $st2->execute();
      $res2 = $st2->get_result();
      if ($res2->num_rows > 0) $menu = $res2->fetch_assoc();
      $st2->close();
    }
  }
}
if ($menu && isset($menu['menu_name']) && $menu['menu_name'] !== '') {
  $page_title = $menu['menu_name'];
}

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

$can_view = true;
$can_add = $can_edit = $can_delete = false;
if ($myid === 1 || $role_id === 1) {
  $can_add = $can_edit = $can_delete = true;
}

function back_to_list($msg=''){
  $self = $_SERVER['PHP_SELF'];
  $ret = $_POST['return'] ?? '';
  if ($ret && (strpos($ret, '/') === 0 || strpos($ret, $_SERVER['PHP_SELF']) !== false)) {
    $self = $ret;
  }
  header('Location: ' . $self . ($msg!=='' ? ('?ok='.urlencode($msg)) : ''));
  exit;
}

$ok = clean($_GET['ok'] ?? '');
$err = '';

if (!$can_view) {
  http_response_code(403);
  echo "<div style='padding:24px;font-family:sans-serif'><h3>Access Denied</h3>You do not have permission to view this page.</div>";
  exit;
}

/* ---------- POST ---------- */
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 && !$can_edit) $err = 'You are not authorized to edit records.';
      elseif ($id<=0 && !$can_add) $err = 'You are not authorized to add records.';
      else {
        $name = clean($_POST['name'] ?? '');
        $status = (int)($_POST['status'] ?? 1);
        $order_by = (int)($_POST['order_by'] ?? 0);
        if ($name==='') $err='Project type name is required.';
        else {
          $dup_sql = "SELECT id FROM $TABLE WHERE LOWER(name)=LOWER(?)";
          if ($id>0) $dup_sql .= " AND id<>?";
          $st = $con->prepare($dup_sql." LIMIT 1");
          if ($id>0) $st->bind_param('si',$name,$id); else $st->bind_param('s',$name);
          $st->execute(); $dup=$st->get_result()->fetch_assoc(); $st->close();
          if ($dup){ $err='This project type already exists.'; }
          else {
            if ($order_by<=0){
              $r = mysqli_query($con,"SELECT COALESCE(MAX(order_by),0)+1 nxt FROM $TABLE");
              $order_by = (int)($r ? mysqli_fetch_assoc($r)['nxt'] : 1);
            }
            $hasCreated = col_exists($con,$TABLE,'created_by');
            $hasMod = col_exists($con,$TABLE,'modified_by');
            if ($id>0){
              if ($hasMod){
                $sql="UPDATE $TABLE SET name=?, status=?, order_by=?, modified_by=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('siiii',$name,$status,$order_by,$myid,$id);
              } else {
                $sql="UPDATE $TABLE SET name=?, status=?, order_by=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('siii',$name,$status,$order_by,$id);
              }
              if ($st->execute()){ $st->close(); back_to_list('Updated successfully.'); }
              $err='Update failed.'; $st->close();
            } else {
              if ($hasCreated && $hasMod){
                $sql="INSERT INTO $TABLE (name,status,order_by,created_by,modified_by) VALUES (?,?,?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('siiii',$name,$status,$order_by,$myid,$myid);
              } else {
                $sql="INSERT INTO $TABLE (name,status,order_by) VALUES (?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('sii',$name,$status,$order_by);
              }
              if ($st->execute()){ $st->close(); back_to_list('Added successfully.'); }
              $err='Insert failed.'; $st->close();
            }
          }
        }
      }
    }
  }
}

/* ---------- mode ---------- */
$mode = (isset($_GET['edit']) || isset($_GET['add'])) ? 'form' : 'list';
$edit=null;
if ($mode==='form' && isset($_GET['edit'])){
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT id,name,status,order_by FROM $TABLE WHERE id=?");
  $st->bind_param('i',$eid); $st->execute();
  $edit=$st->get_result()->fetch_assoc();
  $st->close();
}

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

$where=" WHERE 1=1 "; $bind=[]; $type='';
if ($q!==''){ $like="%$q%"; $where.=" AND name LIKE ?"; $bind[]=$like; $type.='s'; }
if ($levelS !== '' && is_numeric($levelS)){ $lvl=(int)$levelS; $where.=" AND order_by=?"; $bind[]=$lvl; $type.='i'; }

switch ($sort){
  case 'order_desc': $order="ORDER BY order_by DESC, id DESC"; break;
  case 'name_asc'  : $order="ORDER BY name ASC"; break;
  case 'name_desc' : $order="ORDER BY name DESC"; break;
  case 'id_asc'    : $order="ORDER BY id ASC"; break;
  case 'id_desc'   : $order="ORDER BY id DESC"; break;
  default          : $order="ORDER BY order_by ASC, id DESC";
}

/* ---------- 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,order_by FROM $TABLE $where $order";
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 project type..." value="<?=htmlspecialchars($q)?>">
        <input type="number" name="level" class="inp small" placeholder="Order level" value="<?=htmlspecialchars($levelS)?>">
        <select name="sort" class="inp small" title="Sort by">
          <?php
            $opts = [
              'order_asc'  => 'Order Level ↑',
              'order_desc' => 'Order Level ↓',
              '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>
        <?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($can_add): ?><a class="btn green" href="<?=htmlspecialchars(keep_params(['add'=>1]))?>">Add New</a><?php endif; ?>
    </div>

    <?php if($ok): ?><div class="note"><?=htmlspecialchars($ok)?></div><?php endif; ?>
    <?php if($err): ?><div class="err"><?=htmlspecialchars($err)?></div><?php endif; ?>

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

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th><th>Name</th><th class="num">Order Level</th><th>Status</th><th>Actions</th>
        </tr></thead>
        <tbody>
        <?php if(!$rows): ?><tr><td colspan="5" 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 class="num"><?= (int)$r['order_by'] ?></td>
            <td><span class="badge <?=$r['status']?'on':'off'?>"><?=$r['status']?'Active':'Inactive'?></span></td>
            <td>
              <?php if($can_edit): ?>
                <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>(int)$r['id']]))?>">Edit</a>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

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

    <?php if($ok): ?><div class="note"><?=htmlspecialchars($ok)?></div><?php endif; ?>
    <?php if($err): ?><div class="err"><?=htmlspecialchars($err)?></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; ?>
      <input type="hidden" name="return" value="<?=htmlspecialchars($_SERVER['REQUEST_URI'])?>">

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

      <div>
        <label>Order Level</label>
        <input name="order_by" type="number" class="inp" value="<?=htmlspecialchars((string)($edit['order_by'] ?? ''))?>" placeholder="Auto if blank/0">
      </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;text-align:left">
        <button class="btn green" name="save" type="submit">Save</button>
      </div>
    </form>
  </div>
<?php endif; ?>

<?php
echo ob_get_clean();
