<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Careers Management';
$success = $error = '';
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM careers WHERE id=?", [$id]);
  header('Location: /admin/careers.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE careers SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/careers.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title    = trim($_POST['title'] ?? '');
  $dept     = trim($_POST['department'] ?? '');
  $location = trim($_POST['location'] ?? 'Karachi, Pakistan');
  $type     = $_POST['type'] ?? 'full-time';
  $exp      = trim($_POST['experience'] ?? '');
  $desc     = trim($_POST['description'] ?? '');
  $req      = trim($_POST['requirements'] ?? '');
  $ben      = trim($_POST['benefits'] ?? '');
  $salary   = trim($_POST['salary_range'] ?? '');
  $sort     = (int)($_POST['sort_order'] ?? 0);
  if (!$title) { $error = 'Job title is required.'; }
  else {
    if ($id) {
      Database::execute("UPDATE careers SET title=?,department=?,location=?,type=?,experience=?,description=?,requirements=?,benefits=?,salary_range=?,sort_order=? WHERE id=?",
        [$title,$dept,$location,$type,$exp,$desc,$req,$ben,$salary,$sort,$id]);
      $success = 'Job updated.';
    } else {
      Database::insert("INSERT INTO careers (title,department,location,type,experience,description,requirements,benefits,salary_range,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,1)",
        [$title,$dept,$location,$type,$exp,$desc,$req,$ben,$salary,$sort]);
      $success = 'Job added.'; $id = db()->lastInsertId(); $action = 'edit';
    }
  }
}
$job = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM careers WHERE id=?",[$id]) : null;
$jobs = $action==='list' ? Database::fetchAll("SELECT * FROM careers ORDER BY sort_order,created_at DESC") : [];
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">💼 Careers / Job Listings</h1>
    <div class="flex gap-3">
      <a href="/careers.php" target="_blank" class="btn-outline text-sm px-3 py-2">View Public Page ↗</a>
      <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Post New Job</a>
    </div>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">Deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="data-table">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">Title</th><th class="px-4 py-3 text-left">Department</th><th class="px-4 py-3 text-left">Type</th><th class="px-4 py-3 text-left">Location</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$jobs): ?><tr><td colspan="6" class="px-4 py-8 text-center text-gray-500">No jobs posted yet. <a href="?action=new" class="text-orange-400">Post first job →</a></td></tr><?php endif; ?>
        <?php foreach ($jobs as $j): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 font-medium"><?= e($j['title']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($j['department'] ?: '—') ?></td>
          <td class="px-4 py-3 text-gray-400"><?= ucfirst(str_replace('-', ' ', $j['type'])) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($j['location']) ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $j['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $j['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $j['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $j['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $j['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/careers.php" class="text-gray-400 hover:text-white text-sm">← All Jobs</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Job' : 'New Job Listing' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>
  <form method="POST" class="card-dark p-6 max-w-2xl">
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Job Title *</label>
        <input type="text" name="title" value="<?= e($job['title'] ?? '') ?>" class="input-field" required placeholder="e.g. Technical Sales Engineer">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Department</label>
        <input type="text" name="department" value="<?= e($job['department'] ?? '') ?>" class="input-field" list="dept-list">
        <datalist id="dept-list"><option>Sales</option><option>Engineering</option><option>Operations</option><option>Workshop</option><option>Accounts</option><option>Procurement</option></datalist>
      </div>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Employment Type</label>
        <select name="type" class="input-field">
          <?php foreach (['full-time'=>'Full Time','part-time'=>'Part Time','contract'=>'Contract','internship'=>'Internship'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= ($job['type'] ?? 'full-time')===$v ? 'selected' : '' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Location</label>
        <input type="text" name="location" value="<?= e($job['location'] ?? 'Karachi, Pakistan') ?>" class="input-field">
      </div>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Experience Required</label>
        <input type="text" name="experience" value="<?= e($job['experience'] ?? '') ?>" class="input-field" placeholder="e.g. 3–5 years">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Salary Range</label>
        <input type="text" name="salary_range" value="<?= e($job['salary_range'] ?? '') ?>" class="input-field" placeholder="e.g. PKR 80,000–120,000">
      </div>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Job Description</label>
      <textarea name="description" rows="4" class="input-field" placeholder="Role overview and responsibilities..."><?= e($job['description'] ?? '') ?></textarea>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Requirements (one per line)</label>
      <textarea name="requirements" rows="5" class="input-field" placeholder="• Bachelor's in Mechanical Engineering&#10;• 3+ years in oil & gas procurement&#10;• Familiarity with API standards"><?= e($job['requirements'] ?? '') ?></textarea>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">What We Offer (one per line)</label>
      <textarea name="benefits" rows="4" class="input-field" placeholder="• Competitive salary&#10;• Medical insurance&#10;• Professional development"><?= e($job['benefits'] ?? '') ?></textarea>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Sort Order</label>
      <input type="number" name="sort_order" value="<?= e($job['sort_order'] ?? 0) ?>" class="input-field w-24" min="0">
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save Job</button>
      <a href="/admin/careers.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
