<?php
session_start();
include 'config.php';
if (!isset($_GET['id']) || !isset($_GET['action']) || !in_array($_SESSION['role'], ['admin', 'superadmin'])) {
    header("Location: advance_requests.php");
    exit();
}

$id = (int)$_GET['id'];
$action = $_GET['action'];
$admin = $_SESSION['username'];

if ($action === 'approve') {
    $sql = "UPDATE salary_advances 
            SET status = 'approved', approved_by = ?, approved_date = CURDATE()
            WHERE id = ? AND status = 'pending'";
} else {
    $sql = "UPDATE salary_advances 
            SET status = 'rejected', approved_by = ?, approved_date = CURDATE()
            WHERE id = ? AND status = 'pending'";
}

$stmt = $conn->prepare($sql);
$stmt->bind_param("si", $admin, $id);
$stmt->execute();

header("Location: advance_requests.php?msg=" . ucfirst($action));
exit();
?>