<?php

function db_gericht_select_karte()
{
    try {

        $link = connectdb();


        $sql_gerichte = "SELECT * FROM gericht ORDER BY RAND() LIMIT 5";
        $result_sql_gerichte = mysqli_query($link, $sql_gerichte);
        $result_sql_gerichte1 = mysqli_query($link, $sql_gerichte);


        $verwendete_allergene_code = [];
        $verwendete_allergene_string = "";

        while ($row_gerichte = mysqli_fetch_assoc($result_sql_gerichte)) {

            // Abfrage der vorhandenen Allergene im aktuellen Gericht

            $sql_gericht_hat_allergene = "SELECT * FROM gericht_hat_allergen WHERE gericht_id=" . $row_gerichte['id'];
            $result_sql_gericht_hat_allergene = mysqli_query($link, $sql_gericht_hat_allergene);
            $allergene = "";
            while ($row_allergene = mysqli_fetch_assoc($result_sql_gericht_hat_allergene)) {
                $allergene .= $row_allergene['code'] . ", ";

                if (!in_array($row_allergene['code'], $verwendete_allergene_code)) {
                    $verwendete_allergene_code[] = $row_allergene['code'];
                }
            }

        }


        $sql_allergen = "SELECT code, name FROM allergen";
        $result_sql_allergen = mysqli_query($link, $sql_allergen);



        $data = [
            "allergene" => $verwendete_allergene_string,
            "result_sql_allergen" => $result_sql_allergen,
            "verwendete_allergene_code" => $verwendete_allergene_code,
            "result_sql_gerichte" => $result_sql_gerichte1,
            "allergene1" => $allergene
        ];


        mysqli_close($link);


    } catch (Exception $ex) {
        $data = array(
            'id' => '-1',
            'error' => true,
            'name' => 'Datenbankfehler ' . $ex->getCode(),
            'beschreibung' => $ex->getMessage());
    } finally {
        return $data;
    }
}