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

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

$officer_id = $_SESSION['user_id'];
$type = $_POST['leave_type'];
$start = $_POST['start_date'];
$end = $_POST['end_date'];
$reason = trim($_POST['reason']);
$year = date('Y');

// Validate dates
$startDate = new DateTime($start);
$endDate = new DateTime($end);
$days = $startDate->diff($endDate)->days + 1;

if ($days <= 0) {
  exit("Invalid date range.");
}

$typeField = ['annual', 'medical', 'hospital', 'unpaid'];
if (!in_array($type, $typeField)) {
  exit("Invalid leave type.");
}

// Save leave request with status = pending
$stmt = $pdo->prepare("INSERT INTO leave_requests (officer_id, leave_type, start_date, end_date, reason, status) VALUES (?, ?, ?, ?, ?, 'pending')");
$stmt->execute([$officer_id, $type, $start, $end, $reason]);

header("Location: dashboard.php?submitted=1");
exit;
