<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
$u = require_login();
$pdo = get_db();

$id = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['id']) ? (int)$_POST['id'] : 0);
$job = ['title'=>'','department'=>'','location'=>'','job_type'=>'Full-time','vacancy'=>'','age_range'=>'','experience'=>'',
        'salary'=>'','description'=>'','read_before_apply'=>'','apply_procedure'=>'','deadline'=>'','status'=>'published'];
$links = [];
$jobSkills = [];

if ($id) {
    $stmt = $pdo->prepare('SELECT * FROM jobs WHERE id = ?');
    $stmt->execute([$id]);
    $found = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$found) { die('Job not found.'); }
    $job = $found;
    $links = get_job_links($pdo, $id);
    $jobSkills = array_column(get_job_skills($pdo, $id), 'name');
}

$allSkills = get_all_skills($pdo);

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $title = trim($_POST['title'] ?? '');
    $department = trim($_POST['department'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $job_type = trim($_POST['job_type'] ?? '');
    $vacancy = trim($_POST['vacancy'] ?? '');
    $age_range = trim($_POST['age_range'] ?? '');
    $experience = trim($_POST['experience'] ?? '');
    $salary = trim($_POST['salary'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $read_before_apply = trim($_POST['read_before_apply'] ?? '');
    $apply_procedure = trim($_POST['apply_procedure'] ?? '');
    $deadline = trim($_POST['deadline'] ?? '');
    $status = ($_POST['status'] ?? 'published') === 'draft' ? 'draft' : 'published';
    $linkLabels = $_POST['link_label'] ?? [];
    $linkUrls = $_POST['link_url'] ?? [];
    $skillsCsv = trim($_POST['skills_csv'] ?? '');

    if ($title === '') {
        $error = 'Job title is required.';
    } elseif ($deadline !== '' && !DateTime::createFromFormat('Y-m-d', $deadline)) {
        $error = 'Deadline date is invalid.';
    } else {
        if ($id) {
            $stmt = $pdo->prepare('UPDATE jobs SET title=?, department=?, location=?, job_type=?, vacancy=?, age_range=?, experience=?, salary=?, description=?, read_before_apply=?, apply_procedure=?, deadline=?, status=?, updated_at=datetime(\'now\') WHERE id=?');
            $stmt->execute([$title, $department, $location, $job_type, $vacancy, $age_range, $experience, $salary, $description, $read_before_apply, $apply_procedure, $deadline ?: null, $status, $id]);
            $jobId = $id;
        } else {
            $stmt = $pdo->prepare('INSERT INTO jobs (title, department, location, job_type, vacancy, age_range, experience, salary, description, read_before_apply, apply_procedure, deadline, status, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
            $stmt->execute([$title, $department, $location, $job_type, $vacancy, $age_range, $experience, $salary, $description, $read_before_apply, $apply_procedure, $deadline ?: null, $status, $u['id']]);
            $jobId = $pdo->lastInsertId();
        }

        // replace links
        $pdo->prepare('DELETE FROM job_links WHERE job_id = ?')->execute([$jobId]);
        $ins = $pdo->prepare('INSERT INTO job_links (job_id, label, url) VALUES (?,?,?)');
        foreach ($linkLabels as $i => $label) {
            $label = trim($label);
            $url = trim($linkUrls[$i] ?? '');
            if ($label !== '' && $url !== '' && filter_var($url, FILTER_VALIDATE_URL)) {
                $ins->execute([$jobId, $label, $url]);
            }
        }

        // replace skills (creates any new ones typed by the user for future reuse)
        save_job_skills($pdo, $jobId, $skillsCsv);

        header('Location: index.php?msg=' . urlencode($id ? 'Job post updated.' : 'Job post created.'));
        exit;
    }
}

$csrf = csrf_token();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $id ? 'Edit' : 'New' ?> Job Post — Delmas Careers Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link href="assets/admin.css" rel="stylesheet">
</head>
<body>
<?php include __DIR__ . '/includes/topbar.php'; ?>
<div class="admin-wrap">
  <h5 class="mb-3"><?= $id ? 'Edit Job Post' : 'New Job Post' ?></h5>
  <?php if ($error): ?><div class="alert alert-danger"><?= h($error) ?></div><?php endif; ?>
  <div class="card-plain p-4">
    <form method="post">
      <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
      <input type="hidden" name="id" value="<?= (int)$id ?>">

      <div class="row g-3 mb-3">
        <div class="col-md-6">
          <label class="form-label">Job Title *</label>
          <input class="form-control" name="title" required value="<?= h($job['title']) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Department</label>
          <input class="form-control" name="department" value="<?= h($job['department']) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Location</label>
          <input class="form-control" name="location" value="<?= h($job['location']) ?>" placeholder="CEPZ, Chattogram">
        </div>
      </div>

      <div class="row g-3 mb-3">
        <div class="col-md-3">
          <label class="form-label">Job Type</label>
          <select class="form-select" name="job_type">
            <?php foreach (['Full-time','Part-time','Contract','Internship'] as $t): ?>
              <option <?= $job['job_type'] === $t ? 'selected' : '' ?>><?= $t ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Application Deadline</label>
          <input type="date" class="form-control" name="deadline" value="<?= h($job['deadline']) ?>">
          <div class="form-text">Leave blank for no deadline. The Apply button turns off automatically once this date passes.</div>
        </div>
        <div class="col-md-3">
          <label class="form-label">Status</label>
          <select class="form-select" name="status">
            <option value="published" <?= $job['status']==='published'?'selected':'' ?>>Published (visible on site)</option>
            <option value="draft" <?= $job['status']==='draft'?'selected':'' ?>>Draft (hidden)</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Vacancy</label>
          <input class="form-control" name="vacancy" value="<?= h($job['vacancy']) ?>" placeholder="e.g. 2 or --">
        </div>
      </div>

      <div class="row g-3 mb-3">
        <div class="col-md-4">
          <label class="form-label">Age</label>
          <input class="form-control" name="age_range" value="<?= h($job['age_range']) ?>" placeholder="e.g. 20 to 30 years">
        </div>
        <div class="col-md-4">
          <label class="form-label">Experience</label>
          <input class="form-control" name="experience" value="<?= h($job['experience']) ?>" placeholder="e.g. At least 1 year">
        </div>
        <div class="col-md-4">
          <label class="form-label">Salary</label>
          <input class="form-control" name="salary" value="<?= h($job['salary']) ?>" placeholder="e.g. Negotiable">
        </div>
      </div>

      <div class="mb-3">
        <label class="form-label">Job Description</label>
        <textarea class="form-control" name="description" rows="8" placeholder="Responsibilities, requirements, etc."><?= h($job['description']) ?></textarea>
      </div>

      <div class="mb-3">
        <label class="form-label">Skills &amp; Expertise</label>

        <div class="skills-zone selected-zone mb-2">
          <div class="zone-title">Selected for this job <span class="text-muted fw-normal">(click × to remove)</span></div>
          <div id="selectedSkills" class="mb-1"><span class="text-muted small" id="noneSelectedMsg">None selected yet.</span></div>
        </div>

        <div class="skills-zone mb-2">
          <div class="zone-title">Available skills <span class="text-muted fw-normal">(click to add)</span></div>
          <div id="availableSkills">
            <?php foreach ($allSkills as $s): ?>
              <span class="skill-chip add-chip" data-name="<?= h($s['name']) ?>"><i class="fas fa-plus"></i> <?= h($s['name']) ?></span>
            <?php endforeach; ?>
          </div>
        </div>

        <div class="input-group input-group-sm" style="max-width:420px">
          <input type="text" id="newSkillInput" class="form-control" placeholder="Type a new skill, e.g. Adobe Illustrator">
          <button type="button" id="addNewSkillBtn" class="btn btn-outline-gold">Add</button>
        </div>
        <div class="form-text">New skills you type here are saved automatically and will appear as an option next time.</div>
        <input type="hidden" name="skills_csv" id="skillsCsv" value="<?= h(implode(',', $jobSkills)) ?>">
      </div>

      <style>
        .skills-zone{background:#fbfaf7;border:1px solid #eee2c9;border-radius:6px;padding:.8rem 1rem}
        .zone-title{font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:#8a7550;font-weight:700;margin-bottom:.5rem}
        .skill-chip{display:inline-block;padding:.35rem .8rem;margin:0 .35rem .35rem 0;border-radius:20px;border:1px solid #d8d0bd;background:#fff;color:#555;font-size:.83rem;cursor:pointer;user-select:none}
        .skill-chip:hover{border-color:#c9a96e}
        .skill-chip.add-chip{background:#fff}
        .skill-chip.remove-chip{background:#c9a96e;border-color:#c9a96e;color:#1a1e2e;font-weight:600}
        .skill-chip.remove-chip i{margin-left:.3rem}
      </style>

      <div class="row g-3 mb-3">
        <div class="col-md-6">
          <label class="form-label">Read Before Apply <span class="text-muted small">(optional note shown above the apply form)</span></label>
          <textarea class="form-control" name="read_before_apply" rows="4" placeholder="e.g. We only take the hardcopy CV for review"><?= h($job['read_before_apply']) ?></textarea>
        </div>
        <div class="col-md-6">
          <label class="form-label">Apply Procedure <span class="text-muted small">(optional — instructions shown on the job page)</span></label>
          <textarea class="form-control" name="apply_procedure" rows="4" placeholder="e.g. Send your CV to the given address..."><?= h($job['apply_procedure']) ?></textarea>
        </div>
      </div>

      <div class="mb-2">
        <label class="form-label">External Apply Links <span class="text-muted small">(optional — e.g. BDJobs, LinkedIn, or any other job site)</span></label>
        <div id="linkRepeater">
          <?php if ($links): foreach ($links as $l): ?>
            <div class="repeater-row">
              <input class="form-control" name="link_label[]" placeholder="Label, e.g. Apply on BDJobs" value="<?= h($l['label']) ?>">
              <input class="form-control" name="link_url[]" placeholder="https://..." value="<?= h($l['url']) ?>">
              <button type="button" class="btn btn-outline-danger remove-link">&times;</button>
            </div>
          <?php endforeach; else: ?>
            <div class="repeater-row">
              <input class="form-control" name="link_label[]" placeholder="Label, e.g. Apply on BDJobs">
              <input class="form-control" name="link_url[]" placeholder="https://...">
              <button type="button" class="btn btn-outline-danger remove-link">&times;</button>
            </div>
          <?php endif; ?>
        </div>
        <button type="button" id="addLink" class="btn btn-sm btn-outline-gold mt-1"><i class="fas fa-plus"></i> Add another link</button>
      </div>

      <button class="btn btn-gold mt-3" type="submit"><?= $id ? 'Save Changes' : 'Publish Job Post' ?></button>
      <a href="index.php" class="btn btn-outline-secondary mt-3">Cancel</a>
    </form>
  </div>
</div>

<script>
document.getElementById('addLink').addEventListener('click', function(){
  const row = document.createElement('div');
  row.className = 'repeater-row';
  row.innerHTML = `<input class="form-control" name="link_label[]" placeholder="Label, e.g. Apply on LinkedIn">
                    <input class="form-control" name="link_url[]" placeholder="https://...">
                    <button type="button" class="btn btn-outline-danger remove-link">&times;</button>`;
  document.getElementById('linkRepeater').appendChild(row);
});
document.getElementById('linkRepeater').addEventListener('click', function(e){
  if (e.target.classList.contains('remove-link')) {
    e.target.closest('.repeater-row').remove();
  }
});

// ---- Skills & Expertise two-zone picker ----
(function(){
  const selectedBox = document.getElementById('selectedSkills');
  const availableBox = document.getElementById('availableSkills');
  const hidden = document.getElementById('skillsCsv');
  const newInput = document.getElementById('newSkillInput');
  const addBtn = document.getElementById('addNewSkillBtn');
  const noneMsg = document.getElementById('noneSelectedMsg');

  let selected = (hidden.value || '').split(',').map(s => s.trim()).filter(Boolean);

  function render() {
    // selected zone
    selectedBox.innerHTML = '';
    if (selected.length === 0) {
      selectedBox.appendChild(noneMsg);
    } else {
      selected.forEach(function(name){
        const chip = document.createElement('span');
        chip.className = 'skill-chip remove-chip';
        chip.dataset.name = name;
        chip.innerHTML = name + ' <i class="fas fa-xmark"></i>';
        selectedBox.appendChild(chip);
      });
    }
    // available zone: hide any chip that's already selected
    availableBox.querySelectorAll('.skill-chip').forEach(function(chip){
      chip.style.display = selected.includes(chip.dataset.name) ? 'none' : 'inline-block';
    });
    hidden.value = selected.join(',');
  }

  function addSkill(name) {
    name = name.trim();
    if (!name) return;
    if (!selected.some(s => s.toLowerCase() === name.toLowerCase())) {
      // reuse the exact casing of an existing available chip if it matches
      const existingChip = Array.from(availableBox.querySelectorAll('.skill-chip'))
        .find(c => c.dataset.name.toLowerCase() === name.toLowerCase());
      selected.push(existingChip ? existingChip.dataset.name : name);
      if (!existingChip) {
        // brand-new skill: also add it to the available list so it can be re-added later if removed
        const chip = document.createElement('span');
        chip.className = 'skill-chip add-chip';
        chip.dataset.name = name;
        chip.innerHTML = '<i class="fas fa-plus"></i> ' + name;
        availableBox.appendChild(chip);
      }
    }
    render();
  }

  function removeSkill(name) {
    selected = selected.filter(s => s !== name);
    render();
  }

  availableBox.addEventListener('click', function(e){
    const chip = e.target.closest('.skill-chip');
    if (chip) addSkill(chip.dataset.name);
  });

  selectedBox.addEventListener('click', function(e){
    const chip = e.target.closest('.skill-chip');
    if (chip) removeSkill(chip.dataset.name);
  });

  function addFromInput() {
    newInput.value.split(',').forEach(addSkill);
    newInput.value = '';
  }
  addBtn.addEventListener('click', addFromInput);
  newInput.addEventListener('keydown', function(e){
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      addFromInput();
    }
  });

  render();
})();
</script>
</body>
</html>
