<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;


class Gerichte extends Model
{
    use HasFactory;



    function db_gericht_select_karte()
    {
        try {

            $sql_gerichte = "SELECT * FROM gericht ORDER BY RAND() LIMIT 5";
            $result_sql_gerichte = DB::select($sql_gerichte);
            $result_sql_gerichte1 = DB::select($sql_gerichte);


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


            foreach ($result_sql_gerichte as $row_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 = DB::select($sql_gericht_hat_allergene);
                $allergene = "";
                foreach ($result_sql_gericht_hat_allergene as $row_allergene) {
                    $allergene .= $row_allergene->code . ", ";

                    $drin = 0;
                    foreach ($verwendete_allergene_code as $verwendet){
                        if ($verwendet == $row_allergene->code){
                            $drin =1;
                        }
                    }

                    if ($drin == 0) {
                        $verwendete_allergene_code[] = $row_allergene->code;
                    }
                }

            }


            $sql_allergen = "SELECT code, name FROM allergen";
            $result_sql_allergen = DB::select($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
            ];


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

    }

    function db_gericht_bewertung(int $id){
        $sql_gerichte = "SELECT gericht.name, gericht.bildname FROM gericht WHERE id =". $id;
        $result_sql_gerichte = DB::select($sql_gerichte);
        return $result_sql_gerichte;
    }

    function db_gericht_name(int $id){
        $sql_gerichte = "SELECT gericht.name FROM gericht WHERE id =". $id;
        $result_sql_gerichte = DB::select($sql_gerichte);
        return $result_sql_gerichte;
    }

}
