<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireRole([1, 5]);
$db     = getDB();
$id     = (int)post('id', 0);
$action = post('action', '');
if (!$id || !$action) apiError('ID and action required.', 422);

$stmt = $db->prepare("SELECT * FROM employee_leave WHERE id = ?");
$stmt->execute([$id]);
$leave = $stmt->fetch();
if (!$leave) apiError('Leave record not found.', 404);

if ($action === 'approve') {
    $db->prepare("UPDATE employee_leave SET status='approved', approved_by=?, approved_at=NOW() WHERE id=?")
       ->execute([$user['id'], $id]);
    // Update used balance
    $db->prepare("
        INSERT INTO employee_leave_balance (employee_id, year, leave_type, allocated, used)
        VALUES (?, YEAR(?), ?, 0, ?)
        ON DUPLICATE KEY UPDATE used = used + ?
    ")->execute([$leave['employee_id'], $leave['start_date'], $leave['leave_type'], $leave['days'], $leave['days']]);
    apiSuccess([], 'Leave approved.');
} elseif ($action === 'reject') {
    $reason = post('reason', '');
    $db->prepare("UPDATE employee_leave SET status='rejected', approved_by=?, approved_at=NOW(), rejected_reason=? WHERE id=?")
       ->execute([$user['id'], $reason, $id]);
    apiSuccess([], 'Leave rejected.');
} elseif ($action === 'cancel') {
    if ($leave['status'] === 'approved') {
        // Reverse balance
        $db->prepare("
            UPDATE employee_leave_balance SET used = GREATEST(0, used - ?)
            WHERE employee_id=? AND year=YEAR(?) AND leave_type=?
        ")->execute([$leave['days'], $leave['employee_id'], $leave['start_date'], $leave['leave_type']]);
    }
    $db->prepare("UPDATE employee_leave SET status='cancelled' WHERE id=?")->execute([$id]);
    apiSuccess([], 'Leave cancelled.');
} else {
    apiError('Unknown action.', 400);
}
