<?php include __DIR__ . '/../includes/header.php';
if (!can_approve_leaves()) { set_flash('danger', 'No tenés permiso para aprobar solicitudes.'); redirect('leaves/index.php'); }
$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare("SELECT l.*, e.hire_date FROM leaves_requests l JOIN employees e ON e.id = l.employee_id WHERE l.id=?");
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) { set_flash('danger', 'Solicitud no encontrada.'); redirect('leaves/index.php'); }
if ($row['leave_type'] === 'Vacaciones') {
    $vac = vacation_balance(['id'=>$row['employee_id'],'hire_date'=>$row['hire_date']]);
    $days = leave_days_between($row['start_date'], $row['end_date']);
    if ($days > $vac['pending']) {
        set_flash('danger', 'No se puede aprobar: el saldo disponible de vacaciones es insuficiente.');
        redirect('leaves/index.php');
    }
}
$stmt = db()->prepare("UPDATE leaves_requests SET status='Aprobado' WHERE id=?");
$stmt->execute([$id]);
audit_log('update', 'leaves_requests', $id, 'Solicitud aprobada');
set_flash('success', 'Solicitud aprobada.');
redirect('leaves/index.php');
