<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require('config.php');

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

// Check if flag, servedBy, and shopListID are set
if (isset($_GET['flag']) && isset($_GET['servedBy'])) {
    $flag = $_GET['flag'];
    $servedBy = $_GET['servedBy'];

    try {
        if ($flag === "deleteSingle" && isset($_GET['shopListID'])) {
            $shopListID = $_GET['shopListID'];

            // Prepare delete query for a single item
            $deleteQuery = "DELETE FROM tempShopList WHERE shopListID = ? AND servedBy = ?";
            $stmt = $connect->prepare($deleteQuery);
            $stmt->bind_param("ss", $shopListID, $servedBy);
        } elseif ($flag === "clearList") {
            // Prepare delete query to clear all items for a specific servedBy
            $deleteQuery = "DELETE FROM tempShopList WHERE servedBy = ?";
            $stmt = $connect->prepare($deleteQuery);
            $stmt->bind_param("s", $servedBy);
        } else {
            throw new Exception("Invalid flag or missing shopListID for deleteSingle.");
        }

        // Execute query
        if ($stmt->execute()) {
            $response["message"] = ($flag === "deleteSingle") ? "Item removed from shoplist." : "Shoplist cleared.";
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to delete items.";
        }
    } catch (Exception $e) {
        $response["error"] = true;
        $response["message"] = "Error: " . $e->getMessage();
    }
} else {
    $response["error"] = true;
    $response["message"] = "Required parameters (flag, servedBy) not provided.";
}

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