<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);

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

global $con;
if (!isset($con) || !$con) {
  http_response_code(500);
  echo '<!doctype html><html><head><meta charset="utf-8"><title>Server error</title>';
  echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
  echo '</head><body><div class="master-wrap"><div class="card">';
  echo '<h2>Server error</h2><div class="alert danger">DB connection ($con) not initialized.</div>';
  echo '</div></div></body></html>';
  exit;
}

$page_title = 'Subscription Pack Features';
$TABLE = 'jos_app_userfeatures'; // id, profile_type, name, (status), (orderby)

/* ---------- helpers (Languages Master pattern) ---------- */
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($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");
  }
}
function back_to_list($msg){
  header("Location: ". keep_params(['mode'=>null,'id'=>null,'ok'=>$msg]));
  exit;
}

/* Profile Types from master */
function load_profile_types(mysqli $con): array {
  $out = [];
  $res = mysqli_query($con, "SELECT id, profile_name FROM jos_app_profile_types ORDER BY id ASC");
  if ($res) {
    while ($r = mysqli_fetch_assoc($res)) {
      $out[(int)$r['id']] = $r['profile_name'];
    }
  }
  return $out;
}

ensure_schema($con,$TABLE);
$PROFILE_TYPES = load_profile_types($con);

/* ---------- state ---------- */
$err=''; $ok='';
$mode   = $_GET['mode'] ?? 'list';
$view   = $_GET['view'] ?? 'last'; // last | all
$search = clean($_GET['search'] ?? '');
$f_prof = (int)($_GET['profile_type'] ?? 0);
$f_stat = ($_GET['status'] ?? '')!=='' ? (int)$_GET['status'] : '';
$f_order= ($_GET['orderby_eq'] ?? '') !== '' ? (int)$_GET['orderby_eq'] : '';
$sort   = $_GET['sort'] ?? 'order_asc';
if(isset($_GET['ok'])) $ok = clean($_GET['ok']);

$ORDER_MAP = [
  'order_asc'  => 'orderby ASC, id DESC',
  'order_desc' => 'orderby DESC, id DESC',
  'name_asc'   => 'name ASC',
  'name_desc'  => 'name DESC',
  'id_desc'    => 'id DESC',
  'id_asc'     => 'id ASC',
];
$order_by = $ORDER_MAP[$sort] ?? $ORDER_MAP['order_asc'];

$sort_label_map = [
  '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'
];

/* ---------- POST (save/delete) ---------- */
if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!verify_csrf($_POST['csrf'] ?? null)){
    $err='Invalid request. Please refresh.';
  } else {

    if(isset($_POST['save'])){
      $id          = (int)($_POST['id'] ?? 0);
      $name        = clean($_POST['name'] ?? '');
      $profile_type= (int)($_POST['profile_type'] ?? 0);
      $status      = (int)($_POST['status'] ?? 1);
      $orderby     = (int)($_POST['orderby'] ?? 0);

      if($name==='' || $profile_type<=0){
        $err='Name and Profile Type are required.';
      } else {

        // Auto orderby if blank/0: put at end for that profile_type
        if($orderby<=0){
          $mx = 0;
          $rs = mysqli_query($con, "SELECT MAX(orderby) AS mx FROM `$TABLE` WHERE profile_type=".intval($profile_type));
          if($rs){ $rr=mysqli_fetch_assoc($rs); $mx=(int)($rr['mx'] ?? 0); }
          $orderby = $mx + 1;
        }

        // duplicate check (name+profile_type)
        $st = mysqli_prepare($con,"SELECT id FROM `$TABLE` WHERE LOWER(name)=LOWER(?) AND profile_type=? AND id<>? LIMIT 1");
        mysqli_stmt_bind_param($st,'sii',$name,$profile_type,$id);
        mysqli_stmt_execute($st);
        $dup = mysqli_stmt_get_result($st);

        if($dup && mysqli_num_rows($dup)>0){
          $err='Feature already exists for this Profile Type.';
        } else {

          if($id>0){
            $st=mysqli_prepare($con,"UPDATE `$TABLE` SET name=?, profile_type=?, status=?, orderby=? WHERE id=?");
            mysqli_stmt_bind_param($st,'siiii',$name,$profile_type,$status,$orderby,$id);
            mysqli_stmt_execute($st);
            back_to_list('Updated successfully.');
          } else {
            $st=mysqli_prepare($con,"INSERT INTO `$TABLE` (name, profile_type, status, orderby) VALUES (?,?,?,?)");
            mysqli_stmt_bind_param($st,'siii',$name,$profile_type,$status,$orderby);
            mysqli_stmt_execute($st);
            back_to_list('Saved successfully.');
          }

        }
      }
    }

    if(isset($_POST['delete'])){
      $id=(int)($_POST['id'] ?? 0);
      if($id>0){
        $st=mysqli_prepare($con,"DELETE FROM `$TABLE` WHERE id=?");
        mysqli_stmt_bind_param($st,'i',$id);
        mysqli_stmt_execute($st);
        back_to_list('Deleted successfully.');
      } else {
        $err='Invalid record.';
      }
    }

  }
}

/* ---------- counts for headbar ---------- */
$whereCount = " WHERE 1=1 ";
if($search!==''){
  $s = mysqli_real_escape_string($con, strtolower($search));
  $whereCount .= " AND (LOWER(name) LIKE '%$s%')";
}
if($f_prof>0){ $whereCount .= " AND profile_type=".intval($f_prof); }
if($f_stat!==''){ $whereCount .= " AND status=".intval($f_stat); }
if($f_order!==''){ $whereCount .= " AND orderby=".$f_order; }

$total = 0;
$cntRes = mysqli_query($con,"SELECT COUNT(*) AS cnt FROM `$TABLE` $whereCount");
if($cntRes){ $rowCnt=mysqli_fetch_assoc($cntRes); $total=(int)($rowCnt['cnt'] ?? 0); }
$showing = ($view==='all') ? $total : min(50,$total);

/* ---------- render ---------- */
ob_start();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?=htmlspecialchars($page_title)?></title>
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
</head>
<body>

<div class="master-wrap">

  <div class="headbar" style="display:flex;align-items:center;justify-content:space-between;gap:12px">
    <div>
      <h2 style="margin:0;"><?=htmlspecialchars($page_title)?></h2>
      <div style="color:#9aa3b2;font-size:0.95rem;margin-top:6px">
        Showing <?=$showing?> of <?=$total?> (sorted: <?=htmlspecialchars($sort_label_map[$sort] ?? $sort)?>)
      </div>
    </div>

    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
      <a class="btn success" href="<?=keep_params(['mode'=>'form','id'=>null])?>" style="padding:10px 14px">Add New</a>
      <a class="btn secondary" href="<?=keep_params(['view'=>$view==='all'?'last':'all'])?>" style="padding:10px 14px"><?=$view==='all'?'Show Last 50':'View All'?></a>
    </div>
  </div>

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

<?php if($mode==='form'):
  $id=(int)($_GET['id'] ?? 0);
  $row=['id'=>0,'name'=>'','profile_type'=>0,'status'=>1,'orderby'=>0];
  if($id>0){
    $st = mysqli_prepare($con,"SELECT * FROM `$TABLE` WHERE id=? LIMIT 1");
    mysqli_stmt_bind_param($st,'i',$id);
    mysqli_stmt_execute($st);
    $r = mysqli_stmt_get_result($st);
    if($r && mysqli_num_rows($r)>0){ $row=mysqli_fetch_assoc($r); }
  }
  $csrf=csrf_token();
?>
  <div class="card" style="max-width:1000px;margin-top:18px;padding:0;border-radius:12px;overflow:visible">
    <div style="padding:22px 28px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">
      <div>
        <h3 style="margin:0 0 4px 0"><?= $row['id'] ? 'Edit Feature' : 'Add Feature' ?></h3>
        <div style="color:#9aa3b2;font-size:0.95rem"><?= $row['id'] ? 'Modify feature details below' : 'Create a new feature for a profile type' ?></div>
      </div>
      <div>
        <a class="btn secondary" href="<?=keep_params(['mode'=>null,'id'=>null])?>" style="padding:10px 14px">Back to List</a>
      </div>
    </div>

    <form method="post" action="<?=keep_params()?>" style="padding:20px 28px">
      <input type="hidden" name="csrf" value="<?=$csrf?>">
      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

      <div style="display:flex;gap:18px;align-items:flex-end;flex-wrap:wrap">
        <label style="flex:1;min-width:260px">
          <div style="color:#cbd5dd;margin-bottom:6px;font-weight:600">Title *</div>
          <input class="inp" type="text" name="name" value="<?=htmlspecialchars($row['name'])?>" required style="width:100%">
        </label>

        <label style="min-width:260px">
          <div style="color:#cbd5dd;margin-bottom:6px;font-weight:600">Profile Type *</div>
          <select class="inp" name="profile_type" required style="width:100%">
            <option value="">-- Select --</option>
            <?php foreach($PROFILE_TYPES as $k=>$v): ?>
              <option value="<?=$k?>" <?=((int)$row['profile_type']===$k?'selected':'')?>><?=htmlspecialchars($v)?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <label style="width:180px">
          <div style="color:#cbd5dd;margin-bottom:6px;font-weight:600">Status</div>
          <select class="inp" name="status" style="width:100%">
            <option value="1" <?=((int)$row['status']===1?'selected':'')?>>Active</option>
            <option value="0" <?=((int)$row['status']===0?'selected':'')?>>Inactive</option>
          </select>
        </label>

        <label style="width:160px">
          <div style="color:#cbd5dd;margin-bottom:6px;font-weight:600">Order Level</div>
          <input class="inp" type="number" name="orderby" value="<?= (int)$row['orderby'] ?>" style="width:100%">
        </label>
      </div>

      <div class="toolbar" style="margin-top:20px;display:flex;align-items:center;gap:12px">
        <button class="btn success" type="submit" name="save">Save</button>
      </div>
    </form>
  </div>

<?php else:
  $where=" WHERE 1=1 ";
  if($search!==''){
    $s=mysqli_real_escape_string($con,strtolower($search));
    $where.=" AND (LOWER(name) LIKE '%$s%')";
  }
  if($f_prof>0){ $where.=" AND profile_type=".intval($f_prof); }
  if($f_stat!==''){ $where.=" AND status=".intval($f_stat); }
  if($f_order!==''){ $where.=" AND orderby=".$f_order; }

  $limit = ($view==='all') ? "" : " LIMIT 50";
  $sql="SELECT * FROM `$TABLE` $where ORDER BY $order_by $limit";
  $res=mysqli_query($con,$sql);
  $rows=[]; if($res){ while($r=mysqli_fetch_assoc($res)) $rows[]=$r; }
  $csrf=csrf_token();
?>
  <div class="card" style="padding:0;margin-top:14px">

    <form method="get" action="" class="toolbar toolbar-inline" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:16px;position:sticky;top:68px;z-index:5;">
      <input type="hidden" name="mode" value="list">

      <input class="inp" type="text" name="search" placeholder="Search by feature name..." value="<?=htmlspecialchars($search)?>" style="min-width:220px">

      <select class="inp" name="profile_type" style="min-width:190px">
        <option value="0">All Profile Types</option>
        <?php foreach($PROFILE_TYPES as $k=>$v): ?>
          <option value="<?=$k?>" <?=$f_prof===$k?'selected':''?>><?=htmlspecialchars($v)?></option>
        <?php endforeach; ?>
      </select>

      <select class="inp" name="status" style="min-width:140px">
        <option value="">All Status</option>
        <option value="1" <?=$f_stat===""?'' : ($f_stat==1?'selected':'')?>>Active</option>
        <option value="0" <?=$f_stat===""?'' : ($f_stat==0?'selected':'')?>>Inactive</option>
      </select>

      <input class="inp" style="max-width:160px" type="number" name="orderby_eq" placeholder="Order Level" value="<?=htmlspecialchars((string)$f_order)?>">

      <select class="inp" name="sort" style="min-width:170px">
        <option value="order_asc"  <?=$sort==='order_asc'?'selected':''?>>Order Level ↑</option>
        <option value="order_desc" <?=$sort==='order_desc'?'selected':''?>>Order Level ↓</option>
        <option value="name_asc"   <?=$sort==='name_asc'?'selected':''?>>Name A–Z</option>
        <option value="name_desc"  <?=$sort==='name_desc'?'selected':''?>>Name Z–A</option>
        <option value="id_desc"    <?=$sort==='id_desc'?'selected':''?>>Newest first</option>
        <option value="id_asc"     <?=$sort==='id_asc'?'selected':''?>>Oldest first</option>
      </select>

      <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap">
        <button class="btn primary" type="submit">Search</button>
        <a class="btn secondary" href="<?=keep_params(['search'=>null,'profile_type'=>null,'status'=>null,'orderby_eq'=>null,'sort'=>null,'view'=>null])?>">Reset</a>
      </div>
    </form>

    <div class="table" style="max-height:520px;overflow:auto;border-top:1px solid rgba(255,255,255,0.06)">
      <div class="t-head sticky" style="display:grid;grid-template-columns:70px 1fr 200px 140px 140px 220px;gap:12px;align-items:center;padding:14px 18px;border-bottom:1px solid rgba(255,255,255,0.06)">
        <div>SR No</div>
        <div>Name</div>
        <div>Profile Type</div>
        <div style="text-align:center">Order Level</div>
        <div>Status</div>
        <div style="text-align:right">Actions</div>
      </div>

      <?php if(empty($rows)): ?>
        <div class="t-row" style="padding:22px 18px;color:#9aa3b2">No records found.</div>
      <?php else: $sr=1; foreach($rows as $r): ?>
        <div class="t-row" style="display:grid;grid-template-columns:70px 1fr 200px 140px 140px 220px;gap:12px;align-items:center;padding:14px 18px;border-bottom:1px solid rgba(255,255,255,0.04)">
          <div style="color:#cbd5dd"><?=$sr++?></div>
          <div><?=htmlspecialchars($r['name'])?></div>
          <div><?=htmlspecialchars($PROFILE_TYPES[(int)$r['profile_type']] ?? ('#'.$r['profile_type']))?></div>
          <div style="text-align:center"><?= (int)$r['orderby'] ?></div>
          <div>
            <?= ((int)$r['status']===1) ? '<span class="badge success">Active</span>' : '<span class="badge">Inactive</span>' ?>
          </div>
          <div style="text-align:right;white-space:nowrap">
            <a class="btn secondary" href="<?=keep_params(['mode'=>'form','id'=>$r['id']])?>" style="margin-right:8px">Edit</a>
            <form method="post" action="<?=keep_params()?>" style="display:inline" onsubmit="return confirm('Delete this feature?')">
              <input type="hidden" name="csrf" value="<?=$csrf?>">
              <input type="hidden" name="id" value="<?=$r['id']?>">
              <button class="btn danger" type="submit" name="delete">Delete</button>
            </form>
          </div>
        </div>
      <?php endforeach; endif; ?>
    </div>
  </div>

<?php endif; ?>

</div>
</body>
</html>
<?php
echo ob_get_clean();
