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

$page_title = 'Education Degree Master';
$TABLE = 'jos_crm_education_status';

$err = '';
$ok  = '';

/* ---------- 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);
}

/* ---------------------------
   Permission / Menu helpers
--------------------------- */
$MENU_ROW = null;
$MENU_ID  = null;
$script_file = basename(__FILE__);

try {
    if (isset($con) && $con instanceof mysqli) {
        $like = "%{$script_file}%";
        $mstm = $con->prepare("SELECT id, title FROM jos_admin_menus WHERE link LIKE ? LIMIT 1");
        if ($mstm) {
            $mstm->bind_param('s', $like);
            $mstm->execute();
            $MENU_ROW = $mstm->get_result()->fetch_assoc();
            $mstm->close();
            if ($MENU_ROW && !empty($MENU_ROW['title'])) {
                $page_title = $MENU_ROW['title'];
            }
            if ($MENU_ROW && isset($MENU_ROW['id'])) $MENU_ID = (int)$MENU_ROW['id'];
        }
    }
} catch (Exception $e) {}

/* ---- permission helper ---- */
if (!function_exists('current_user_can')) {
    function current_user_can(string $action, $menu_id = null): bool {
        global $con;
        $uid = function_exists('current_user_id') ? (int)current_user_id() : 0;
        $map = ['view'=>'can_view','add'=>'can_add','edit'=>'can_edit','delete'=>'can_delete'];
        $col = $map[$action] ?? null;
        if (!$col || !($con instanceof mysqli)) return true;

        try {
            $check = $con->prepare("
                SELECT COLUMN_NAME FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'jos_admin_menu_permissions'
                  AND COLUMN_NAME = ? LIMIT 1
            ");
            if ($check) {
                $check->bind_param('s', $col);
                $check->execute();
                $has = (bool)$check->get_result()->fetch_assoc();
                $check->close();
                if ($has) {
                    if ($menu_id) {
                        $q = $con->prepare("SELECT {$col} AS v FROM jos_admin_menu_permissions WHERE menu_id=? AND user_id=? LIMIT 1");
                        $q->bind_param('ii', $menu_id, $uid);
                        $q->execute(); $r=$q->get_result()->fetch_assoc(); $q->close();
                        if ($r) return (bool)$r['v'];
                    }
                }
            }
        } catch (Exception $e) {}
        return true;
    }
}

$can_view   = current_user_can('view', $MENU_ID);
$can_add    = current_user_can('add', $MENU_ID);
$can_edit   = current_user_can('edit', $MENU_ID);
$can_delete = current_user_can('delete', $MENU_ID);

if (!$can_view) {
    ob_start(); ?>
    <link rel="stylesheet" href="/adminconsole/assets/ui.css">
    <div class="card" style="max-width:720px">
      <h3><?=htmlspecialchars($page_title)?></h3>
      <div class="badge off" style="margin-top:10px">Access denied — you do not have permission to view this page.</div>
    </div>
    <?php echo ob_get_clean(); exit;
}

/* ---------- POST ---------- */
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);
            if ($id > 0 && !$can_edit) $err = 'You do not have permission to edit.';
            elseif ($id == 0 && !$can_add) $err = 'You do not have permission to add.';
            else {
                $name = trim($_POST['name'] ?? '');
                $status = (int)($_POST['status'] ?? 1);
                if ($name === '') $err = 'Name is required.';
                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: '.$con->error;
                        $st->close();
                    } else {
                        $uid=function_exists('current_user_id')?(int)current_user_id():0;
                        $st=$con->prepare("INSERT INTO $TABLE (created_by,name,status) VALUES (?,?,?)");
                        $st->bind_param('isi',$uid,$name,$status);
                        $ok=$st->execute()?'Added successfully':'Insert failed: '.$con->error;
                        $st->close();
                    }
                }
            }
        }
        if (isset($_POST['delete']) && isset($_POST['id'])) {
            if (!$can_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: '.$con->error;
                $st->close();
            }
        }
    }
}

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

/* ---------- load edit ---------- */
$edit=null;
if ($mode==='form' && isset($_GET['edit'])) {
    $eid=(int)$_GET['edit'];
    $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();
}

/* ---------- list ---------- */
$q=trim((string)($_GET['q']??'')); $all=isset($_GET['all']); $lim=$all?0:50;
$where='';$bind=[];$type='';
if($q!==''){ $where=" WHERE name LIKE ?"; $bind[]="%{$q}%"; $type.='s'; }

$suggestions=[]; $sg=$con->prepare("SELECT DISTINCT name FROM $TABLE ORDER BY name ASC");
$sg->execute(); $r=$sg->get_result(); while($row=$r->fetch_assoc()) $suggestions[]=$row['name']; $sg->close();

$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']??0); $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">
      <div class="search">
        <form method="get" style="display:flex;gap:8px">
          <input type="text" name="q" placeholder="Search by name..." value="<?=htmlspecialchars($q)?>" list="degList" autocomplete="off">
          <datalist id="degList">
            <?php foreach($suggestions as $nm): ?><option value="<?=htmlspecialchars($nm)?>"></option><?php endforeach; ?>
          </datalist>
          <button class="btn gray" type="submit">Search</button>
          <?php if($q!==''): ?><a class="btn gray" href="<?= htmlspecialchars(keep_params(['q'=>null,'all'=>null])) ?>">Clear</a><?php endif; ?>
        </form>
      </div>
      <div style="display:flex;gap:8px">
        <?php if(!$all && $total>$lim): ?><a class="btn" 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])) ?>">Back to Last 50</a><?php endif; ?>
        <?php if($can_add): ?><a class="btn green" href="<?= htmlspecialchars(keep_params(['add'=>1,'edit'=>null])) ?>">Add New</a><?php endif; ?>
      </div>
    </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 class="sticky">
        <thead><tr><th>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($can_edit): ?><a class="btn" href="<?= htmlspecialchars(keep_params(['edit'=>(int)$r['id'],'add'=>null])) ?>">Edit</a><?php endif; ?>
              <?php if($can_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="<?= (int)$r['id'] ?>">
                  <button class="btn red" type="submit" name="delete">Delete</button>
                </form>
              <?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 Degree' : 'Add Degree' ?></h3>
      <a class="btn gray" href="<?= htmlspecialchars(keep_params(['edit'=>null,'add'=>null])) ?>">Back to List</a>
    </div>

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

    <?php if (!isset($_GET['edit']) && !$can_add): ?>
      <div class="badge off">You do not have permission to add new records.</div>
    <?php else: ?>
      <form method="post">
        <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

        <label for="name">Degree Name</label>
        <input id="name" name="name" required placeholder="e.g. HSC, Bachelors, Masters"
               style="width:100%;padding:10px;border-radius:10px;border:1px solid #374151;background:#0b1220;color:#e5e7eb"
               value="<?=htmlspecialchars($edit['name'] ?? '')?>"
               list="degList" autocomplete="off">

        <label for="status" style="margin-top:10px">Status</label>
        <select id="status" name="status"
                style="width:100%;padding:10px;border-radius:10px;border:1px solid #374151;background:#0b1220;color:#e5e7eb">
          <option value="1" <?=isset($edit['status']) && (int)$edit['status']===1 ? 'selected':''?>>Active</option>
          <option value="0" <?=isset($edit['status']) && (int)$edit['status']===0 ? 'selected':''?>>Inactive</option>
        </select>

        <div style="margin-top:12px">
          <?php $save_allowed = $edit ? $can_edit : $can_add; ?>
          <?php if($save_allowed): ?>
            <button type="submit" name="save" class="btn green">Save</button>
          <?php else: ?>
            <button type="button" class="btn gray" disabled>You are not allowed to save</button>
          <?php endif; ?>
        </div>
      </form>
    <?php endif; ?>
  </div>
<?php endif; ?>

<?php echo ob_get_clean(); ?>
