<?php
require_once __DIR__ . '/career/includes/db.php';
require_once __DIR__ . '/career/includes/functions.php';
$pdo = get_db();

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ? AND status = 'published'");
$stmt->execute([$id]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$job) {
    http_response_code(404);
}
$links = $job ? get_job_links($pdo, $id) : [];
$skills = $job ? get_job_skills($pdo, $id) : [];
$expired = $job ? is_job_expired($job['deadline']) : true;

$submitted = isset($_GET['applied']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><?= $job ? h($job['title']) . ' — Careers — Delmas Apparels' : 'Job Not Found — Delmas Apparels' ?></title>
  <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="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400&family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />
  <style>
    /* Delmas Apparels brand palette (matches index.html) */
    :root{
      --gold:#C9A84C; --gold-light:#E8C96A; --gold-dark:#8B6914;
      --bg-dark:#0A0A0A; --bg-light:#F5F0E8;
      --text-white:#FAFAF8; --text-dark:#0A0A0A; --text-muted:#8A8A8A; --text-body:#333;
      --border-gold:rgba(201,168,76,.25);
      --transition:all .3s ease;
      --fd:'Cormorant Garamond',serif; --fb:'Outfit',sans-serif;
    }
    body{font-family:var(--fb)}
    #mainNav{font-family:var(--fb)}
    .brand-main{font-family:var(--fd);font-weight:600;letter-spacing:.04em;color:var(--text-white)}
    .brand-accent{font-family:var(--fd);font-weight:300;letter-spacing:.04em;color:var(--gold-light)}
    .toggler-line{display:block;width:22px;height:2px;background:var(--gold);margin:4px 0}
    #mainNav .nav-link{color:var(--text-white);opacity:.85;font-size:.8rem;letter-spacing:.05em;text-transform:uppercase}
    #mainNav .nav-link:hover{color:var(--gold-light)!important;opacity:1}
    .nav-cta{border:1px solid var(--gold);border-radius:3px;padding:.4rem 1rem!important}
    .btn-primary-tapl{display:inline-block;background:var(--gold);color:var(--bg-dark);border:1px solid var(--gold);padding:.65rem 1.6rem;font-family:var(--fb);font-weight:600;font-size:.82rem;letter-spacing:.06em;text-transform:uppercase;border-radius:3px;transition:var(--transition);text-decoration:none}
    .btn-primary-tapl:hover{background:transparent;color:var(--gold)}
    .btn-show-more{display:inline-block;border:1px solid var(--border-gold);color:var(--text-dark);padding:.5rem 1rem;border-radius:4px;font-size:.85rem;text-decoration:none;transition:var(--transition)}
    .btn-show-more:hover{border-color:var(--gold);color:var(--gold-dark)}
    .section-label{display:inline-block;color:var(--gold-dark);font-size:.78rem;letter-spacing:.12em;text-transform:uppercase;font-weight:600}
    .job-hero{background:var(--bg-dark);padding:9rem 0 3rem}
    .job-hero h1{font-family:var(--fd);color:var(--text-white);font-size:clamp(1.9rem,4vw,2.7rem)}
    .job-hero .job-meta{color:var(--text-muted);font-size:.85rem;margin-top:.8rem}
    .job-hero .job-meta span{margin-right:1.2rem}
    .job-body{padding:3.5rem 0;background:var(--bg-light)}
    .job-desc{background:#fff;border:1px solid var(--border-gold);border-radius:6px;padding:2rem;margin-bottom:2rem;line-height:1.35;color:var(--text-body)}
    .apply-box{background:#fff;border:1px solid var(--border-gold);border-radius:6px;padding:2rem}
    .ext-links a{display:inline-block;margin:0 .5rem .6rem 0}
    .closed-note{background:#fbe9e9;color:#9e3d3d;padding:1rem 1.2rem;border-radius:6px;font-size:.9rem}
    .form-label{font-size:.82rem;color:var(--text-body);font-weight:600}
    .info-bar{background:#fff;border:1px solid var(--border-gold);border-radius:6px;padding:0;margin-bottom:1.5rem;display:grid;grid-template-columns:repeat(3,1fr)}
    .info-bar .info-item{font-size:.9rem;color:var(--text-dark);overflow-wrap:anywhere;word-break:break-word;min-width:0;padding:1.1rem 1.3rem;display:flex;flex-direction:column;gap:.35rem;border-bottom:1px solid var(--border-gold)}
    .info-bar .info-item:nth-child(-n+3){border-top:none}
    .info-bar .info-item:not(:nth-child(3n)){border-right:1px solid var(--border-gold)}
    .info-bar .info-item:nth-last-child(-n+3){border-bottom:none}
    .info-bar .info-item strong{display:flex;align-items:center;gap:.4rem;font-size:.7rem;text-transform:uppercase;letter-spacing:.07em;color:var(--text-muted);font-weight:600}
    .info-bar .info-item strong i{color:var(--gold);font-size:.72rem;width:1em;text-align:center}
    .info-bar .info-item span.iv-val{font-weight:500;line-height:1.35}
    @media (max-width:576px){
      .info-bar{grid-template-columns:repeat(2,1fr)}
      .info-bar .info-item:nth-child(-n+3){border-top:1px solid var(--border-gold)}
      .info-bar .info-item:nth-child(1),.info-bar .info-item:nth-child(2){border-top:none}
      .info-bar .info-item:not(:nth-child(3n)){border-right:none}
      .info-bar .info-item:nth-child(odd){border-right:1px solid var(--border-gold)}
      .info-bar .info-item:nth-last-child(-n+3){border-bottom:1px solid var(--border-gold)}
      .info-bar .info-item:nth-last-child(-n+2){border-bottom:none}
    }
    .skill-pill{display:inline-block;padding:.35rem .9rem;margin:0 .4rem .4rem 0;border-radius:20px;background:#f3eee0;color:var(--text-dark);font-size:.82rem;border:1px solid var(--border-gold)}
    .info-section-title{font-family:var(--fd);font-size:1.25rem;color:var(--gold-dark,#9e7d4a);font-weight:600;margin-bottom:.7rem}
    .info-box{background:#fff;border:1px solid var(--border-gold);border-radius:6px;padding:1.6rem 1.8rem;margin-bottom:1.5rem;white-space:pre-wrap;line-height:1.7;color:var(--text-body);font-size:.93rem}
    .cover-note-label{color:#9e6d1f;font-weight:700}
    .cover-note-hint{font-size:.78rem;color:#9e6d1f;background:#fff8e8;border:1px solid #e5cf9a;border-radius:5px;padding:.4rem .7rem;margin-top:.3rem;display:inline-block}
  </style>
</head>
<body>

  <nav class="navbar navbar-expand-lg fixed-top" id="mainNav" style="background:rgba(7,13,26,.97);backdrop-filter:blur(12px)">
    <div class="container">
      <a class="navbar-brand" href="index.html"><span class="brand-main">DELMAS</span> <span class="brand-accent">APPARELS</span></a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
        <span class="toggler-line"></span><span class="toggler-line"></span><span class="toggler-line"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto">
          <li class="nav-item"><a class="nav-link" href="index.html#home">Home</a></li>
          <li class="nav-item"><a class="nav-link" href="career.php" style="color:var(--gold)!important">Career</a></li>
          <li class="nav-item"><a class="nav-link" href="career/admin/login.php"><i class="fas fa-user-lock me-1" style="font-size:.8rem"></i>Admin Login</a></li>
          <li class="nav-item"><a class="nav-link nav-cta" href="index.html#contact">Get In Touch</a></li>
        </ul>
      </div>
    </div>
  </nav>

<?php if (!$job): ?>
  <section class="job-hero"><div class="container"><h1>Job Not Found</h1></div></section>
  <section class="job-body"><div class="container text-center py-5">
    <p>This position may have been removed or is no longer available.</p>
    <a href="career.php" class="btn-primary-tapl">View All Openings</a>
  </div></section>
<?php else: ?>

  <section class="job-hero">
    <div class="container">
      <a href="career.php" class="small" style="color:var(--gold-light)">&larr; All Openings</a>
      <h1 class="mt-2"><?= h($job['title']) ?></h1>
      <div class="job-meta">
        <?php if ($job['department']): ?><span><i class="fas fa-layer-group"></i> <?= h($job['department']) ?></span><?php endif; ?>
        <?php if ($job['location']): ?><span><i class="fas fa-location-dot"></i> <?= h($job['location']) ?></span><?php endif; ?>
        <?php if ($job['job_type']): ?><span><i class="fas fa-clock"></i> <?= h($job['job_type']) ?></span><?php endif; ?>
        <?php if ($job['deadline']): ?><span><i class="fas fa-calendar"></i> Apply by <?= format_date_pretty($job['deadline']) ?></span><?php endif; ?>
      </div>
    </div>
  </section>

  <section class="job-body">
    <div class="container" style="max-width:820px">

      <div class="info-bar">
        <div class="info-item"><strong><i class="fas fa-users"></i>Vacancy</strong><span class="iv-val"><?= h($job['vacancy'] ?: '—') ?></span></div>
        <div class="info-item"><strong><i class="fas fa-user-clock"></i>Age</strong><span class="iv-val"><?= h($job['age_range'] ?: '—') ?></span></div>
        <div class="info-item"><strong><i class="fas fa-location-dot"></i>Location</strong><span class="iv-val"><?= h($job['location'] ?: '—') ?></span></div>
        <div class="info-item"><strong><i class="fas fa-sack-dollar"></i>Salary</strong><span class="iv-val"><?= h($job['salary'] ?: '—') ?></span></div>
        <div class="info-item"><strong><i class="fas fa-briefcase"></i>Experience</strong><span class="iv-val"><?= h($job['experience'] ?: '—') ?></span></div>
        <div class="info-item"><strong><i class="fas fa-calendar-check"></i>Published</strong><span class="iv-val"><?= h(format_date_pretty(substr($job['created_at'], 0, 10))) ?></span></div>
      </div>

      <?php if ($job['description']): ?>
        <div class="job-desc"><?= nl2br(h($job['description'])) ?></div>
      <?php endif; ?>

      <?php if ($skills): ?>
        <div class="mb-4">
          <div class="info-section-title">Skills &amp; Expertise</div>
          <div class="info-box" style="white-space:normal">
            <?php foreach ($skills as $s): ?><span class="skill-pill"><?= h($s['name']) ?></span><?php endforeach; ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($job['read_before_apply']): ?>
        <div class="mb-4">
          <div class="info-section-title">Read Before Apply</div>
          <div class="info-box"><?= nl2br(h($job['read_before_apply'])) ?></div>
        </div>
      <?php endif; ?>

      <?php if ($job['apply_procedure']): ?>
        <div class="mb-4">
          <div class="info-section-title">Apply Procedure</div>
          <div class="info-box"><?= nl2br(h($job['apply_procedure'])) ?></div>
        </div>
      <?php endif; ?>

      <?php if ($links): ?>
        <div class="mb-4 ext-links">
          <div class="section-label mb-2">You can also apply via</div>
          <?php foreach ($links as $l): ?>
            <a href="<?= h($l['url']) ?>" target="_blank" rel="noopener" class="btn-show-more"><i class="fas fa-arrow-up-right-from-square me-1"></i> <?= h($l['label']) ?></a>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <div class="apply-box">
        <h5 class="mb-3" style="font-family:'Cormorant Garamond',serif">Apply for this position</h5>

        <?php if (!empty($_GET['error'])): ?>
          <div class="alert alert-danger"><?= h($_GET['error']) ?></div>
        <?php endif; ?>
        <?php if ($submitted): ?>
          <div class="alert alert-success">Thank you — your application has been received. Our HR team will contact you if your profile matches our requirements.</div>
        <?php elseif ($expired): ?>
          <div class="closed-note"><i class="fas fa-lock me-1"></i> The application deadline for this position has passed. Applications are now closed.</div>
        <?php else: ?>
          <form action="apply-submit.php" method="post" enctype="multipart/form-data">
            <input type="hidden" name="job_id" value="<?= (int)$job['id'] ?>">
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Full Name *</label>
                <input class="form-control" name="applicant_name" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">Email *</label>
                <input class="form-control" type="email" name="email" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">Phone</label>
                <input class="form-control" name="phone">
              </div>
              <div class="col-md-6">
                <label class="form-label">CV / Resume * <span class="text-muted fw-normal">(PDF/DOC/DOCX, max 5MB)</span></label>
                <input class="form-control" type="file" name="cv" accept=".pdf,.doc,.docx" required>
              </div>
              <div class="col-12">
                <label class="form-label">Other Document <span class="text-muted fw-normal">(optional — cover letter, certificate, etc.)</span></label>
                <input class="form-control" type="file" name="other_doc" accept=".pdf,.doc,.docx">
              </div>
              <div class="col-12">
                <label class="form-label cover-note-label">Cover Note *</label><br>
                <span class="cover-note-hint"><i class="fas fa-star me-1"></i>Please tell us why you're a good fit — this is an important part of your application.</span>
                <textarea class="form-control mt-2" id="coverNoteInput" name="cover_note" rows="4" placeholder="Briefly tell us why you're a good fit... (max 200 words)" required></textarea>
                <div class="form-text"><span id="coverNoteCount">0</span> / 200 words</div>
              </div>
              <input type="text" name="website" value="" style="display:none" tabindex="-1" autocomplete="off">
              <div class="col-12">
                <button type="submit" class="btn-primary-tapl">Submit Application</button>
              </div>
            </div>
          </form>
        <?php endif; ?>
      </div>

    </div>
  </section>

<?php endif; ?>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    (function(){
      const ta = document.getElementById('coverNoteInput');
      const countEl = document.getElementById('coverNoteCount');
      if (!ta) return;
      const MAX_WORDS = 200;
      function countWords(text) {
        const words = text.trim().split(/\s+/).filter(Boolean);
        return words;
      }
      function update() {
        let words = countWords(ta.value);
        if (words.length > MAX_WORDS) {
          ta.value = words.slice(0, MAX_WORDS).join(' ');
          words = countWords(ta.value);
        }
        countEl.textContent = words.length;
        countEl.parentElement.classList.toggle('text-danger', words.length >= MAX_WORDS);
      }
      ta.addEventListener('input', update);
      update();
    })();
  </script>
  <script>document.addEventListener('contextmenu', e => e.preventDefault());</script>
</body>
</html>