<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  header("Location: ../auth/login.php");
  exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $officerId = intval($_POST['officer_id']);
  $position = $_POST['position'] ?? '';
  $start = $_POST['start_date'] ?? '';
  $end = $_POST['end_date'] ?? '';
  $fileName = null;

  if ($officerId && $position && $start && $end && isset($_FILES['contract_file'])) {
    $uploadDir = '../uploads/kets/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    $file = $_FILES['contract_file'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safeName = uniqid('KET_', true) . '.' . $ext;
    $target = $uploadDir . $safeName;

    if (move_uploaded_file($file['tmp_name'], $target)) {
      $fileName = $safeName;
    }

    $stmt = $pdo->prepare("
      INSERT INTO employment_terms (officer_id, position, start_date, end_date, contract_file)
      VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([$officerId, $position, $start, $end, $fileName]);

    header("Location: employment_terms.php?msg=added");
    exit;
  }
}

$officers = $pdo->query("SELECT id, username FROM users WHERE role = 'officer'")->fetchAll();
$rows = $pdo->query("
  SELECT et.*, u.username 
  FROM employment_terms et
  JOIN users u ON et.officer_id = u.id
  ORDER BY et.created_at DESC
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Employment Terms | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
  <?php include '../includes/topbar.php'; ?>
  <?php include '../includes/sidebar.php'; ?>

  <div class="content-wrapper p-4">
    <h4 class="mb-3">📄 Employment Terms</h4>

    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'added'): ?>
      <div class="alert alert-success">✅ Employment Terms added successfully!</div>
    <?php endif; ?>

    <div class="card mb-3">
      <div class="card-header bg-light"><strong>Add Employment Terms</strong></div>
      <div class="card-body">
        <form method="post" enctype="multipart/form-data" class="row g-3">
          <div class="col-md-4">
            <label for="officer" class="form-label">Officer</label>
            <select name="officer_id" id="officer" class="form-select" required>
              <option value="">Select Officer</option>
              <?php foreach ($officers as $officer): ?>
                <option value="<?= $officer['id'] ?>"><?= htmlspecialchars($officer['username']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Position</label>
            <input type="text" name="position" class="form-control" required>
          </div>
          <div class="col-md-2">
            <label class="form-label">Start Date</label>
            <input type="date" name="start_date" class="form-control" required>
          </div>
          <div class="col-md-2">
            <label class="form-label">End Date</label>
            <input type="date" name="end_date" class="form-control" required>
          </div>
          <div class="col-md-12">
            <label class="form-label">Contract File</label>
            <input type="file" name="contract_file" accept=".pdf,.doc,.docx" class="form-control" required>
          </div>
          <div class="col-12 text-end">
            <button class="btn btn-dark" type="submit"><i class="fas fa-plus-circle me-1"></i> Add KET</button>
          </div>
        </form>
      </div>
    </div>

    <div class="card">
      <div class="card-body table-responsive">
        <table class="table table-bordered table-hover">
          <thead class="table-dark">
            <tr>
              <th>Officer</th>
              <th>Position</th>
              <th>Start</th>
              <th>End</th>
              <th>Contract</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $row): ?>
              <tr>
                <td><?= htmlspecialchars($row['username']) ?></td>
                <td><?= htmlspecialchars($row['position']) ?></td>
                <td><?= htmlspecialchars($row['start_date']) ?></td>
                <td><?= htmlspecialchars($row['end_date']) ?></td>
                <td>
                  <?php if (!empty($row['contract_file'])): ?>
                    <a href="../uploads/kets/<?= $row['contract_file'] ?>" target="_blank">📄 View</a>
                  <?php else: ?>
                    <span class="text-muted">No File</span>
                  <?php endif; ?>
                </td>
                <td><?= date("d M Y", strtotime($row['created_at'])) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
</body>
</html>
