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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  die("Unauthorized");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'];

  if ($action === 'add') {
    $stmt = $pdo->prepare("INSERT INTO leave_balance (officer_id, annual_leave, medical_leave, hospital_leave, unpaid_leave, year) 
                           VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
      $_POST['officer_id'],
      $_POST['annual_leave'],
      $_POST['medical_leave'],
      $_POST['hospital_leave'],
      $_POST['unpaid_leave'],
      $_POST['year']
    ]);
  }

  if ($action === 'update') {
    $stmt = $pdo->prepare("UPDATE leave_balance 
                           SET annual_leave=?, medical_leave=?, hospital_leave=?, unpaid_leave=?
                           WHERE id=?");
    $stmt->execute([
      $_POST['annual_leave'],
      $_POST['medical_leave'],
      $_POST['hospital_leave'],
      $_POST['unpaid_leave'],
      $_POST['id']
    ]);
  }

  if ($action === 'delete') {
    $stmt = $pdo->prepare("DELETE FROM leave_balance WHERE id = ?");
    $stmt->execute([$_POST['id']]);
  }

  header("Location: manage_leave.php");
  exit;
}
