<?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();
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$row = null;
if ($id > 0) {
    try {
        $st = db()->prepare('SELECT * FROM job_openings WHERE id = ?');
        $st->execute([$id]);
        $row = $st->fetch();
    } catch (Throwable $e) {
        $row = null;
    }
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $title = trim((string)($_POST['title'] ?? ''));
    $slug = trim((string)($_POST['slug'] ?? ''));
    if ($slug === '') {
        $slug = slugify($title);
    }
    $location = trim((string)($_POST['location'] ?? ''));
    $empType = trim((string)($_POST['employment_type'] ?? ''));
    $short = trim((string)($_POST['short_description'] ?? ''));
    $desc = trim((string)($_POST['description'] ?? ''));
    $sort = (int)($_POST['sort_order'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($title === '') {
        $error = 'Title is required.';
    } else {
        try {
            if ($id > 0) {
                db()->prepare(
                    'UPDATE job_openings SET title=?, slug=?, location=?, employment_type=?, short_description=?, description=?, sort_order=?, is_active=? WHERE id=?'
                )->execute([$title, $slug, $location, $empType, $short, $desc, $sort, $isActive, $id]);
                admin_flash_set('success', 'Job opening updated.');
            } else {
                db()->prepare(
                    'INSERT INTO job_openings (title, slug, location, employment_type, short_description, description, sort_order, is_active) VALUES (?,?,?,?,?,?,?,?)'
                )->execute([$title, $slug, $location, $empType, $short, $desc, $sort, $isActive]);
                $newId = (int)db()->lastInsertId();
                admin_flash_set('success', 'Job opening created.');
                header('Location: job-edit.php?id=' . $newId);
                exit;
            }
            header('Location: job-edit.php?id=' . $id);
            exit;
        } catch (Throwable $e) {
            if (str_contains($e->getMessage(), 'Duplicate')) {
                $error = 'This slug is already used. Choose a different slug.';
            } elseif (str_contains($e->getMessage(), "doesn't exist") || str_contains($e->getMessage(), 'Unknown table')) {
                $error = 'Database table missing. Run sql/migrate_job_openings.sql on your database.';
            } else {
                $error = 'Could not save. Please try again.';
            }
        }
    }
}

if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Job opening not found.');
    header('Location: jobs.php');
    exit;
}

$page = 'jobs';
$pageTitle = $id ? 'Edit job opening' : 'New job opening';
$pageSubtitle = 'Only active openings appear on the public Careers page.';
$breadcrumbs = [
    ['label' => 'Dashboard', 'href' => 'index.php'],
    ['label' => 'Job openings', 'href' => 'jobs.php'],
    ['label' => $id ? 'Edit' : 'New', 'href' => null],
];
$headerActions = '<a href="jobs.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>Back to list</a>';
if ($id > 0 && $row) {
    $headerActions .= '<a href="../careers.php" class="btn btn-outline-primary btn-sm" target="_blank" rel="noopener">View careers page</a>';
}

require __DIR__ . '/includes/layout-header.php';

$r = $row ?: [
    'title' => '', 'slug' => '', 'location' => '', 'employment_type' => '',
    'short_description' => '', 'description' => '', 'sort_order' => 0, 'is_active' => 1,
];
$isActiveChecked = $_SERVER['REQUEST_METHOD'] === 'POST'
    ? isset($_POST['is_active'])
    : !empty($r['is_active']);
if ($error) {
    echo '<div class="alert alert-danger shadow-sm">' . h($error) . '</div>';
}
?>
<form method="post" class="row g-4">
  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
  <div class="col-lg-8">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Role details</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Title <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control" required value="<?= h((string)($_POST['title'] ?? $r['title'])) ?>">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">URL slug</label>
          <input type="text" name="slug" class="form-control font-monospace" placeholder="e.g. solar-engineer-bilaspur" value="<?= h((string)($_POST['slug'] ?? $r['slug'])) ?>">
          <div class="form-text">Leave blank to auto-generate from the title.</div>
        </div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-semibold">Location</label>
            <input type="text" name="location" class="form-control" placeholder="City, state" value="<?= h((string)($_POST['location'] ?? $r['location'])) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Employment type</label>
            <input type="text" name="employment_type" class="form-control" placeholder="Full-time, Part-time…" value="<?= h((string)($_POST['employment_type'] ?? $r['employment_type'])) ?>">
          </div>
        </div>
        <div class="mb-3 mt-3">
          <label class="form-label fw-semibold">Short summary</label>
          <textarea name="short_description" class="form-control" rows="3" placeholder="One or two lines shown in the listing"><?= h((string)($_POST['short_description'] ?? $r['short_description'])) ?></textarea>
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Full description</label>
          <textarea name="description" class="form-control" rows="10" placeholder="Responsibilities, requirements, how to apply"><?= h((string)($_POST['description'] ?? $r['description'])) ?></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Publishing</div>
      <div class="card-body">
        <div class="form-check form-switch mb-3">
          <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" <?= $isActiveChecked ? 'checked' : '' ?>>
          <label class="form-check-label" for="is_active">Active (visible on website)</label>
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Sort order</label>
          <input type="number" name="sort_order" class="form-control" value="<?= (int)($_POST['sort_order'] ?? $r['sort_order']) ?>">
          <div class="form-text">Lower numbers appear first.</div>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary w-100"><i class="bi bi-check-lg me-1"></i>Save</button>
  </div>
</form>

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