<?php

class Bestell {
    private $tabelle = "artikel";

    private function baueBestellTabelle($sql) {
        require_once("db.inc.php");

        if ($stmt = $pdo -> prepare($sql)) {
            $stmt -> execute();

            echo "<table>\n\t";
            echo "<thead>
            
            <tr>
            <th>Artikelnummer</th><th>Artikelgruppe</th><th>Artikelbezeichnung</th><th>Preis</th>
            </tr> 
            </thead>";

            echo "<tbody>\n\t";

            while ($z = $stmt -> fetch()) {
            
            echo "<tr "

            .">\n\t<td>"

            . htmlspecialchars($z['anr'])

            ."</td>\n\t<td>"

            . htmlspecialchars($z['gnr'])

            ."</td>\n\t<td>"

            . htmlspecialchars($z['name'])

            ."</td>\n\t<td>"

            . htmlspecialchars($z['preis'])

            ."</td>\n\t";

            }
        }
    }
        public function lesenAlleDaten() {
        $sql = "SELECT anr, gnr, name, preis 
        FROM " .$this->tabelle ."
        ORDER BY anr";
        
        $this->baueBestellTabelle($sql);
    }

    public function lesenGruppe() {
        $sql = "SELECT artikel.anr, gruppen.gruppe AS gnr, artikel.name, artikel.preis FROM " .$this->tabelle ."
        JOIN gruppen ON artikel.gnr = gruppen.gnr
        ORDER BY artikel.anr";

        $this->baueBestellTabelle($sql);
    }

    public function loeschen($id){
        require("db.inc.php");

        $sql = "DELETE FROM " .$this->tabelle ." WHERE anr = :anr";

        if($stmt = $pdo->prepare($sql)) {
            $stmt->bindParam(':anr', $id);
            $stmt->execute();
            echo "Artikel gelöscht";
        }
        else {
            echo "Fehler beim Löschen";
        }


    }

    public function einfuegenSelect($tab, $val, $text, $def) {
        $s = "<select name =\"" .$val . "\" id= \"" . $val . "\">";

        require("db.inc.php");

        $sql = "SELECT " .$val . ", " . $text . " FROM " .$tab;

        //$sql = "SELECT anr, gnr, name FROM artikel";

        if ($stmt = $pdo->prepare($sql)) {
            $stmt->execute();

            while ($z = $stmt->fetch()) {
                $s = $s . "<option value=\"" . $z[0] . "\"";

                if($z[0] == $def) {
                    $s = $s . " selected";
                }

                $s = $s . ">" . $z[0] ." | " . $z[1] ."</option>";
            }
            $s = $s . "</select>";

            return $s;
        }
        else {
            return false; 
        }
        
    }
}

?>