<?php
require('config.php');

// Set response header
header('Content-Type: application/json');

// Prepare response array
$response = ["error" => false, "message" => "", "data" => []];

// Check if required GET parameters are set
if (!isset($_GET['servedBy']) || !isset($_GET['trans_type']) || !isset($_GET['userRole'])) {
    echo json_encode(["error" => true, "message" => "Missing required parameters"]);
    exit();
}

$servedBy = $_GET['servedBy'];
$trans_type = $_GET['trans_type'];
$userRole = $_GET['userRole'];

try {
    // Base query
    $query = "SELECT trans_id, trans_amount, takenBy, trans_date, trans_type, servedBy, paymentMethod, referenceID, trans_token FROM transactions";
    $params = [];
    $types = "";

    if ($userRole === "Admin") {
        // Admin gets all transactions, no filters applied
    } elseif ($userRole === "Attendant") {
        if ($trans_type === "All") {
            $query .= " WHERE servedBy = ?";
            $params[] = $servedBy;
            $types .= "s";
        } elseif (in_array($trans_type, ["Credit", "Staff Credit", "Give Away"])) {
            $query .= " WHERE trans_type = ? AND servedBy = ?";
            $params[] = $trans_type;
            $params[] = $servedBy;
            $types .= "ss";
        } else {
            echo json_encode(["error" => true, "message" => "Invalid transaction type"]);
            exit();
        }
    } elseif ($userRole === "Supervisor") {
        if ($trans_type === "All") {
            // Supervisor gets all transactions
        } elseif (in_array($trans_type, ["Credit", "Staff Credit", "Give Away"])) {
            $query .= " WHERE trans_type = ?";
            $params[] = $trans_type;
            $types .= "s";
        } else {
            echo json_encode(["error" => true, "message" => "Invalid transaction type"]);
            exit();
        }
    } else {
        echo json_encode(["error" => true, "message" => "Unauthorized access"]);
        exit();
    }

    // Execute the query
    $stmt = $connect->prepare($query);

    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    // Fetch and format the response data
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $response["data"][] = $row;
        }
        $response["message"] = "Transactions retrieved successfully.";
    } else {
        $response["message"] = "No transactions found.";
    }
} catch (Exception $e) {
    $response["error"] = true;
    $response["message"] = "Error fetching transactions: " . $e->getMessage();
}

// Output JSON response
echo json_encode($response, JSON_PRETTY_PRINT);
?>
