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

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

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

  if ($id && in_array($action, ['approve', 'reject'])) {

    // Fetch leave details
    $stmt = $pdo->prepare("SELECT * FROM leave_requests WHERE id = ?");
    $stmt->execute([$id]);
    $leave = $stmt->fetch();

    if ($leave && $action === 'approve') {
      $officerId = $leave['officer_id'];
      $type = ucfirst(strtolower(trim($leave['leave_type'])));
      $year = (new DateTime($leave['start_date']))->format('Y');

      // Calculate number of days
      $start = new DateTime($leave['start_date']);
      $end = new DateTime($leave['end_date']);
      $days = $start->diff($end)->days + 1;

      // Update leave_balance used column
      $usedColumn = match($type) {
        'Annual' => 'used_annual',
        'Sick', 'Medical' => 'used_medical',
        'Hospital' => 'used_hospital',
        'Unpaid' => 'used_unpaid',
        default => null
      };

      if ($usedColumn) {
        // Ensure leave_balance row exists
        $check = $pdo->prepare("SELECT id FROM leave_balance WHERE officer_id = ? AND year = ?");
        $check->execute([$officerId, $year]);
        if (!$check->fetch()) {
          // Create if not exists
          $pdo->prepare("INSERT INTO leave_balance (officer_id, year) VALUES (?, ?)")->execute([$officerId, $year]);
        }

        // Increment used leave
        $update = $pdo->prepare("UPDATE leave_balance SET $usedColumn = $usedColumn + ? WHERE officer_id = ? AND year = ?");
        $update->execute([$days, $officerId, $year]);
      }
    }

    // Update leave request status
    $stmt = $pdo->prepare("UPDATE leave_requests SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$action, $id]);

    $_SESSION['toast'] = "Leave successfully " . ($action === 'approve' ? "approved" : "rejected") . "!";
  }
}

header("Location: view_leave_requests.php");
exit;
