<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_admin();

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id']) && csrf_verify($_POST['csrf'] ?? null)) {
    $id = (int)$_POST['delete_id'];
    if ($id > 0) {
        try {
            db()->prepare('DELETE FROM job_openings WHERE id = ?')->execute([$id]);
            admin_flash_set('success', 'Job opening deleted.');
        } catch (Throwable $e) {
            admin_flash_set('danger', 'Could not delete. If the database was not migrated yet, run sql/migrate_job_openings.sql.');
        }
    }
    header('Location: jobs.php');
    exit;
}

$perPage = 15;
$q = trim((string)($_GET['q'] ?? ''));
$pageNum = max(1, (int)($_GET['page'] ?? 1));

$where = '';
$params = [];
if ($q !== '') {
    $where = 'WHERE title LIKE ? OR slug LIKE ? OR location LIKE ? OR employment_type LIKE ? OR short_description LIKE ?';
    $like = '%' . $q . '%';
    $params = [$like, $like, $like, $like, $like];
}

$rows = [];
$total = 0;
$tableMissing = false;
try {
    $countSql = 'SELECT COUNT(*) FROM job_openings ' . $where;
    $stc = db()->prepare($countSql);
    $stc->execute($params);
    $total = (int)$stc->fetchColumn();

    $pages = max(1, (int)ceil($total / $perPage));
    if ($pageNum > $pages) {
        $pageNum = $pages;
    }
    $offset = ($pageNum - 1) * $perPage;

    $sql = 'SELECT * FROM job_openings ' . $where . ' ORDER BY sort_order ASC, id DESC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
    $st = db()->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll();
} catch (Throwable $e) {
    $tableMissing = true;
}

$page = 'jobs';
$pageTitle = 'Job openings';
$pageSubtitle = 'Manage listings shown on the public Careers page. Inactive jobs are hidden from visitors.';
$breadcrumbs = [
    ['label' => 'Dashboard', 'href' => 'index.php'],
    ['label' => 'Job openings', 'href' => null],
];
$headerActions = '<a href="job-edit.php" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add opening</a>';

require __DIR__ . '/includes/layout-header.php';
?>
<?php if (!empty($tableMissing)): ?>
  <div class="alert alert-warning shadow-sm">The <code>job_openings</code> table is not installed. Run <code>sql/migrate_job_openings.sql</code> on your database, then reload this page.</div>
<?php endif; ?>
<div class="admin-card rounded mb-3">
  <div class="card-body py-3">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-6 col-lg-4">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Title, location, type…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary"><i class="bi bi-search me-1"></i>Search</button>
        <?php if ($q !== ''): ?><a href="jobs.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
      </div>
    </form>
  </div>
</div>

<div class="admin-card rounded">
  <div class="card-header py-3 d-flex justify-content-between align-items-center">
    <span>All openings (<?= $total ?>)</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Title</th>
          <th>Location</th>
          <th>Type</th>
          <th>Active</th>
          <th>Order</th>
          <th>Created</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td class="text-muted"><?= (int)$r['id'] ?></td>
            <td class="fw-semibold"><?= h((string)$r['title']) ?></td>
            <td class="small"><?= h((string)($r['location'] ?? '')) ?: '—' ?></td>
            <td class="small"><?= h((string)($r['employment_type'] ?? '')) ?: '—' ?></td>
            <td><?= !empty($r['is_active']) ? '<span class="badge text-bg-success">Yes</span>' : '<span class="badge text-bg-secondary">No</span>' ?></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td class="small text-muted"><?= h((string)$r['created_at']) ?></td>
            <td class="text-end text-nowrap">
              <a href="job-edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary" title="Edit">Edit</a>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this opening?');">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="delete_id" value="<?= (int)$r['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if (!$rows && $total === 0): ?>
    <div class="card-body text-center text-muted py-5">
      No job openings yet. <a href="job-edit.php">Add one</a>
      <?php if (empty($q)): ?>
        <p class="small mt-2 mb-0">If saving fails, run <code>sql/migrate_job_openings.sql</code> once on your database.</p>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>

<?php require __DIR__ . '/includes/layout-footer.php'; ?>
