<?php
session_start();
include('includes/dbconnection.php');
include('includes/flash.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['refund_id'])) {
    $refund_id = intval($_POST['refund_id']);
    $action = isset($_POST['approve']) ? 'approve' : (isset($_POST['reject']) ? 'reject' : '');

    if ($refund_id && $action) {
        $status = ($action === 'approve') ? 'approved' : 'rejected';

        $stmt = $dbh->prepare("UPDATE refund SET status = :status WHERE id = :id AND status = 'pending' LIMIT 1");
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':id', $refund_id);

        if ($stmt->execute()) {
            flash_alert('Refund has been successfully ' . strtoupper($status), 'view_refunds.php');
        header('Location: view_refunds.php'); exit;
        } else {
            flash_alert('Error: Could not update refund status.', 'view_refunds.php');
        header('Location: view_refunds.php'); exit;
        }
    } else {
        flash_alert('Invalid action.', 'view_refunds.php');
        header('Location: view_refunds.php'); exit;
    }
} else {
    flash_alert('No refund selected.', 'view_refunds.php');
        header('Location: view_refunds.php'); exit;
}
?>