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

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

// Check if servedBy is set in the GET request
if (isset($_GET['servedBy'])) {
    $servedBy = $_GET['servedBy'];

    // Prepare the query to fetch items based on servedBy
    $query = "SELECT * FROM tempShopList WHERE servedBy = ?";
    $stmt = $connect->prepare($query);
    $stmt->bind_param("s", $servedBy);

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

        // Check if any records were found
        if ($result->num_rows > 0) {
            $totalAmount = 0;

            // Fetch all matching records
            while ($row = $result->fetch_assoc()) {
                $response["data"][] = $row;
                
                // Accumulate the total amount
                $totalAmount += (int) $row["amount"];
            }

            // Add the total amount to the response
            $response["totalAmount"] = $totalAmount;
        } else {
            $response["message"] = "No items found for the provided servedBy value.";
        }
    } catch (Exception $e) {
        $response["error"] = true;
        $response["message"] = "Error executing query: " . $e->getMessage();
    }
} else {
    $response["error"] = true;
    $response["message"] = "servedBy value not provided.";
}

// Output the response as JSON
echo json_encode($response);
?>
