<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

include('../../includes/config.php');

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['txn_id'], $data['action'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

$txn_id = intval($data['txn_id']);
$action = strtolower(trim($data['action']));

if ($txn_id <= 0 || !in_array($action, ['approved', 'voided'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid action or transaction ID']);
    exit;
}

$stmt = $conn->prepare("UPDATE bank_transactions SET status = ? WHERE id = ?");
$stmt->bind_param("si", $action, $txn_id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => "Transaction successfully {$action}."]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to update transaction status']);
}

$stmt->close();
$conn->close();
?>
