<!DOCTYPE html>
<html>
    <head>
        <meta lang="de"/>
        <meta charset="utf-8"/>
        <meta name="viewport" content="device=device-width, initial-scaling=1"/>
        <link rel="Stylesheet" type="text/css" href="style.css"/>
        <link rel="Stylesheet" type="text/css" href="suchergebnisse.css"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <title>Candle Bibliothek | Suchergebnisse</title>
        <link rel="icon" href="pictures/candle.png">
        <script src="notwendiges_laden.js" defer></script>
    </head>
    <body>
        <header id="header"></header>

    <!------------------------------------------------------------------------->

    <div class="hauptcontainer">
        <h1 id="searchResult_heading">Suchergebnisse</h1>
        <div id="searchResult_container">
            <?php
            $sql = '';
            $sourceForm = $_GET['searchType'];
            // Überprüfen, welches Formular die Datei aufgerufen hat
            if ($sourceForm == "simple") {
                // Einfache Suche
                // Eingegebene Daten in einer Variable speichern
                $searchQuery = $_GET['searchFor'];
                // Mögliche Whitspaces hinten und vorne entfernen
                $searchQuery = trim($searchQuery, " \t\n\r\0\x0B");

                // SQL-Befehl zusammenstellen 
                $sql = "SELECT b.BuchID, b.Titel, b.Erscheinungsjahr, b.Bild, 
                b.Verlag, 
                GROUP_CONCAT(DISTINCT CONCAT(a.VorName, ' ', a.NachName) 
                SEPARATOR ', ') AS 'Autor',
                GROUP_CONCAT(DISTINCT k.Name SEPARATOR ', ') AS 'Kategorie',
                b.ISBN, b.Klappentext AS 'Inhalt', sp.Bezeichnung AS 'Sprache',
                GROUP_CONCAT(DISTINCT st.Text SEPARATOR ', ') AS 'Stichwort',
                IF(b.Anzahl!=0, 'Verfügbar', CONCAT('Verfügbar ab: ', 
                (SELECT DATE_FORMAT(DATE_ADD(ab.Enddatum, INTERVAL 1 DAY)
                ,'%d.%m.%Y') FROM `ausgeliehenes_buch` AS ab  
                WHERE ab.BuchID = b.BuchID 
                ORDER BY ab.Reserviert ASC, ab.Enddatum  ASC LIMIT 1))) 
                AS 'Verfügbarkeit' FROM `buch` AS b
                INNER JOIN `buch_verfasst_von_autor` AS bvva 
                ON b.BuchID = bvva.BuchID
                INNER JOIN `autor` AS a ON bvva.AutorNr = a.AutorNr
                INNER JOIN `buch_hat_kategorie` AS bhk ON bhk.BuchID = b.BuchID
                INNER JOIN `kategorie` AS k ON k.KategorieID = bhk.KategorieID
                INNER JOIN `sprache` AS sp ON sp.SprachenID = b.SprachenID
                INNER JOIN `buch_hat_stichwort` AS bhs ON bhs.BuchID = b.BuchID
                INNER JOIN `stichwort` AS st ON st.StichwortID = bhs.StichwortID
                GROUP BY b.BuchID
                HAVING b.Titel LIKE '%$searchQuery%'
                OR b.Erscheinungsjahr LIKE '%$searchQuery%'
                OR b.Verlag LIKE '%$searchQuery%'
                OR Autor LIKE '%$searchQuery%'
                OR Kategorie LIKE '%$searchQuery%'
                OR Inhalt LIKE '%$searchQuery%'
                OR Sprache LIKE '%$searchQuery%'
                OR Stichwort LIKE '%$searchQuery%';";
            }
            else if ($sourceForm == "extended") {
                // Erweiterte Suche
                // Eingegebene Daten in Variablen speichern
                $dropdown1 = $_GET['dropdown1'];
                $search1 = $_GET['search1'];
                // Mögliche Whitspaces hinten und vorne entfernen
                $search1 = trim($search1, " \t\n\r\0\x0B");

                $andOr1 = $_GET['and_or1'];
                if ($andOr1 == 'und') {
                    $andOr1 = 'AND';
                }
                else {
                    $andOr1 = 'OR';
                }
                $dropdown2 = $_GET['dropdown2'];
                $search2 = $_GET['search2'];
                // Mögliche Whitspaces hinten und vorne entfernen
                $search2 = trim($search2, " \t\n\r\0\x0B");

                $andOr2 = $_GET['and_or2'];
                if ($andOr2 == 'und') {
                    $andOr2 = 'AND';
                }
                else {
                    $andOr2 = 'OR';
                }
                $dropdown3 = $_GET['dropdown3'];
                $search3 = $_GET['search3'];
                // Mögliche Whitspaces hinten und vorne entfernen
                $search3 = trim($search3, " \t\n\r\0\x0B");

                $startYear = $_GET['Buchdatum1'];
                $startYear = substr($startYear, 0, 4);
                $endYear = $_GET['Buchdatum2'];
                $endYear = substr($endYear, 0, 4);
                $yearQuery = '';
                // Nur Startjahr 
                if ($startYear && !$endYear) {
                    $yearQuery = "WHERE b.Erscheinungsjahr > $startYear";
                }
                // Nur Endjahr
                else if (!$startYear && $endYear) {
                    $yearQuery = "WHERE b.Erscheinungsjahr < $endYear";
                }
                // Start- und Endjahr
                else if ($startYear && $endYear) {
                    $yearQuery = "WHERE b.Erscheinungsjahr 
                        BETWEEN $startYear AND $endYear";
                }

                $language = $_GET['language'];
                if ($language == 'Alle Sprachen') {
                    $language = '%%';
                }

                $available = isset($_GET['status']);
                if ($available) {
                    $available = 'Verfügbar';
                }
                else {
                    $available = '%%';
                }

                // SQL-Befehl zusammenstellen 
                $sql = "SELECT b.BuchID, b.Titel, b.Erscheinungsjahr, b.Bild, 
                b.Verlag, 
                GROUP_CONCAT(DISTINCT CONCAT(a.VorName, ' ', a.NachName) 
                SEPARATOR ', ') AS 'Autor',
                GROUP_CONCAT(DISTINCT k.Name SEPARATOR ', ') AS 'Kategorie',
                b.ISBN, b.Klappentext AS 'Inhalt', sp.Bezeichnung AS 'Sprache',
                GROUP_CONCAT(DISTINCT st.Text SEPARATOR ', ') AS 'Stichwort',
                IF(b.Anzahl!=0, 'Verfügbar', CONCAT('Verfügbar ab: ', 
                (SELECT DATE_FORMAT(DATE_ADD(ab.Enddatum, INTERVAL 1 DAY)
                ,'%d.%m.%Y') FROM `ausgeliehenes_buch` AS ab  
                WHERE ab.BuchID = b.BuchID 
                ORDER BY ab.Reserviert ASC, ab.Enddatum  ASC LIMIT 1))) 
                AS 'Verfügbarkeit' FROM `buch` AS b
                INNER JOIN `buch_verfasst_von_autor` AS bvva 
                ON b.BuchID = bvva.BuchID
                INNER JOIN `autor` AS a ON bvva.AutorNr = a.AutorNr
                INNER JOIN `buch_hat_kategorie` AS bhk ON bhk.BuchID = b.BuchID
                INNER JOIN `kategorie` AS k ON k.KategorieID = bhk.KategorieID
                INNER JOIN `sprache` AS sp ON sp.SprachenID = b.SprachenID
                INNER JOIN `buch_hat_stichwort` AS bhs ON bhs.BuchID = b.BuchID
                INNER JOIN `stichwort` AS st ON st.StichwortID = bhs.StichwortID
                $yearQuery 
                GROUP BY b.BuchID
                HAVING $dropdown1 LIKE '%$search1%'
                $andOr1 $dropdown2 LIKE '%$search2%'
                $andOr2 $dropdown3 LIKE '%$search3%'
                AND Sprache LIKE '$language'
                AND Verfügbarkeit LIKE '$available';";
            }
            else {
                // Form wurde nicht erkannt
            }

            $servername = "localhost";
            $username = "web_b-3";
            $password = "een7Ao6s";
            $dbname = "bibliothek_candle";

            $connection = 
                mysqli_connect($servername, $username, $password, $dbname);

            if (!$connection) {
                die("Verbindung fehlgeschlagen: " . mysqli_connect_error());
            }

            $result = mysqli_query($connection, $sql);
            $counter = 0;
            if (mysqli_num_rows($result) > 0) {
                while($row = mysqli_fetch_assoc($result)) {
                    $bookID = $row['BuchID'];
                    $bookCover = $row['Bild'];
                    $bookTitle = $row['Titel'];
                    $bookPublishingYear = $row['Erscheinungsjahr'];
                    $bookPublisher = $row['Verlag'];
                    $bookAuthor = $row['Autor'];
                    $bookCategory = $row['Kategorie'];
                    $bookAvailability = $row['Verfügbarkeit'];

                    if ($counter != 0) {
                        echo "<div class='divider'></div>";
                    }
                    // TODO: OnClick auslagern. 
                    echo "<div id='book_container$bookID' class='book_container' 
                            onclick='open_bookDetails(this.id)'>
                            <div class='bookCover_container'>
                                <img class='bookCover' 
                                    src='book_covers/$bookCover'
                                    alt='Kein Bild vorhanden'>
                            </div>
                            <div class='bookDetails_container'>
                                <h2 class='bookTitle'>$bookTitle</h2>
                                <div class='bookDetails'>
                                    <p class='author'>Verfasser: $bookAuthor</p>
                                    <p class='publishing_year'>
                                    Erscheinungsjahr: $bookPublishingYear</p>
                                    <p class='publisher'>
                                    Verlag: $bookPublisher</p>
                                    <p class='category'>
                                    Kategorie: $bookCategory</p>
                                </div>
                                <div class='available_container'>
                                    <p id='available_$bookID' class='available'>
                                    $bookAvailability</p>
                                    <!--TODO: Auslagern-->
                                    <script type='text/javascript' 
                                    language='JavaScript'>
                                        (function() {
                                            var currentElement = document.
                                            getElementById('available_$bookID');
                                            var parentDiv = 
                                                currentElement.parentElement;
                                            if (currentElement.innerHTML.trim() 
                                                == 'Verfügbar') {
                                                parentDiv.style.backgroundColor 
                                                = '#70AD47';
                                            }
                                            else {
                                                parentDiv.style.backgroundColor 
                                                = '#F34343';
                                            }
                                        })();
                                    </script>
                                </div>
                            </div>
                            <div class='shoppingCart_container'>
                                <div class='shoppingCart'></div>
                            </div>
                        </div>";
                    $counter++;
                }
            } else {
                echo "Keine Ergebnisse.";
            }

            if (!$result) {
                die("Ungültige SQL-Abfrage: " . mysqli_connect_error());
            }

            mysqli_close($connection);
            
            ?>
        </div>
    </div>

    <!------------------------------------------------------------------------->

    <!-- Auslagern (falls möglich) -->
    <script>
        function open_bookDetails(ID) {
            var data = new URLSearchParams();
            data.append("bookID", ID);

            var url = "http://141.19.142.11/buch_details.php?" + 
                        data.toString();
            location.href = url;
        }
    </script>

    <!------------------------------------------------------------------------->

    <!--Link JS file-->
    <script src="burgerIcon.js"></script>
    <!--If it was small and got big, 
        it calls the function only one time and doesn't do it all the time-->
    <script>
        var widthissue = false;
        window.addEventListener("resize", function(event) {
            if(window.innerWidth > 800 && widthissue) {
                widthissue = false
                unset()
            } 
            else if(window.innerWidth < 800) widthissue = true;
        })
    </script>
   
    <nav id="activeid" class="active"></nav>
   
    <footer id="footer" class="fuss" ></footer>
    
    </body>
</html>