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

$page_title = 'Job Position Master';
$TABLE = 'jos_crm_jobpost';

$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; }
    }
    $qstr = http_build_query($qs);
    return ($qstr === '') ? '' : '?' . $qstr;
}

/**
 * Return a URL to the list view (current script path + preserved GET params,
 * but with 'add' and 'edit' removed).
 */
function list_url(): string {
    $base = strtok($_SERVER['REQUEST_URI'], '?'); // e.g. /adminconsole/masters/jobposition.php
    // If SCRIPT_NAME includes path, prefer that (robust across servers)
    $script = $_SERVER['SCRIPT_NAME'] ?? $base;
    // build final URL
    $qs = keep_params(['add' => null, 'edit' => null]);
    // If keep_params returned empty string, just return script path
    return $script . $qs;
}

/**
 * Flexible permission helper. (Same logic as before)
 */
function can(string $action): bool {
    if (function_exists('has_permission')) {
        return (bool) has_permission($action);
    }

    if (!empty($_SESSION['user']) && is_array($_SESSION['user'])) {
        if (isset($_SESSION['user']['perms']) && is_array($_SESSION['user']['perms'])) {
            return !empty($_SESSION['user']['perms'][$action]);
        }
    }

    if (isset($_SESSION['perms']) && is_array($_SESSION['perms'])) {
        return !empty($_SESSION['perms'][$action]);
    }

    if (isset($_SESSION['admin_permissions']) && is_array($_SESSION['admin_permissions'])) {
        return !empty($_SESSION['admin_permissions'][$action]);
    }

    // default allow if no system detected (avoid locking out)
    return true;
}

/* ---------- load title from Menu Master (if available) ---------- */
try {
    if (isset($con) && $con instanceof mysqli) {
        $script = basename($_SERVER['SCRIPT_NAME']);
        $m_st = $con->prepare("SELECT title FROM jos_admin_menus WHERE link LIKE CONCAT('%', ?, '%') LIMIT 1");
        if ($m_st) {
            $m_st->bind_param('s', $script);
            $m_st->execute();
            $m_res = $m_st->get_result();
            if ($m_row = $m_res->fetch_assoc()) {
                $page_title = $m_row['title'] ?: $page_title;
            }
            $m_st->close();
        }
    }
} catch (Exception $e) {
    // ignore
}

/* ---------- 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);
            if ($id > 0) {
                if (!can('edit')) { $err = 'You do not have permission to edit records.'; }
            } else {
                if (!can('add')) { $err = 'You do not have permission to add records.'; }
            }

            if ($err === '') {
                $id     = (int)($_POST['id'] ?? 0);
                $name   = trim($_POST['name'] ?? '');
                $status = (int)($_POST['status'] ?? 1);

                if ($name === '') {
                    $err = 'Name is required.';
                } else {
                    if ($id > 0) {
                        $sql = "UPDATE $TABLE SET name = ?, status = ? WHERE id = ?";
                        $st  = $con->prepare($sql);
                        if (!$st) {
                            $err = 'Prepare failed: ' . $con->error;
                        } else {
                            $st->bind_param('sii', $name, $status, $id);
                            $exec = $st->execute();
                            $st->close();
                            if ($exec) { $ok = 'Updated successfully'; }
                            else { $err = 'Update failed: ' . $con->error; }
                        }
                    } else {
                        $sql = "INSERT INTO $TABLE (name, status) VALUES (?, ?)";
                        $st  = $con->prepare($sql);
                        if (!$st) {
                            $err = 'Prepare failed: ' . $con->error;
                        } else {
                            $st->bind_param('si', $name, $status);
                            $exec = $st->execute();
                            $st->close();
                            if ($exec) { $ok = 'Added successfully'; }
                            else { $err = 'Insert failed: ' . $con->error; }
                        }
                    }
                }
            }
        }

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

        // On success, redirect to list_url() to avoid re-post and to make Back to List work reliably
        if ($ok !== '' && $err === '') {
            header('Location: ' . list_url());
            exit;
        }
    }
}

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

/* ---------- load edit row if any ---------- */
$edit = null;
if ($mode === 'form' && isset($_GET['edit'])) {
    $eid = (int)$_GET['edit'];
    $st  = $con->prepare("SELECT id, name, status FROM $TABLE WHERE id = ?");
    if ($st) {
        $st->bind_param('i', $eid);
        $st->execute();
        $edit = $st->get_result()->fetch_assoc();
        $st->close();
    } else {
        $err = 'Failed to load record: ' . $con->error;
    }
}

/* ---------- list (default: last 50) ---------- */
$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'; }

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

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

/* ---------- 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)?>">
          <button class="btn gray" type="submit">Search</button>
          <?php if($q!==''): ?><a class="btn gray" href="<?= htmlspecialchars(keep_params(['q'=>null])) ?>">Clear</a><?php endif; ?>
        </form>
      </div>
      <div style="display:flex;gap:8px">
        <?php if(!$all): ?>
          <?php if($total > $lim): ?>
            <a class="btn" href="<?= htmlspecialchars(keep_params(['all'=>1])) ?>">View All (<?= $total ?>)</a>
          <?php endif; ?>
        <?php else: ?>
          <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])) ?>">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']])) ?>">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: /* form mode (add/edit) */ ?>
  <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 Position' : 'Add Position' ?></h3>
      <a class="btn gray" href="<?= htmlspecialchars(list_url()) ?>">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
      $allow_form = $edit ? can('edit') : can('add');
      if (!$allow_form):
    ?>
      <div class="badge off">You do not have permission to <?= $edit ? 'edit' : 'add' ?> positions.</div>
      <div style="margin-top:12px">
        <a class="btn" href="<?= htmlspecialchars(list_url()) ?>">Back to List</a>
      </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">Position Name</label>
        <input id="name" name="name" required placeholder="e.g. Sales Executive"
               style="width:100%;padding:10px;border-radius:10px;border:1px solid #374151;background:#0b1220;color:#e5e7eb"
               value="<?=htmlspecialchars($edit['name'] ?? '')?>">

        <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">
          <!-- Save is now green -->
          <button type="submit" name="save" class="btn green">Save</button>
          <!-- Cancel removed as requested -->
        </div>
      </form>
    <?php endif; ?>
  </div>
<?php endif; ?>

<?php
echo ob_get_clean();
