<?php

// Retrieve data
function searchDB($TITLE, $GENRE, $TYPE) {
    $queryPart = "";
    $fillPart = false;
    $STRICTSEARCH = "";

    if ($TITLE != "") {
        if ($STRICTSEARCH == "true") {
            $queryPart = $queryPart . "name='" . $TITLE . "'"; $fillPart = true;
        } else {
            $queryPart = $queryPart . "name LIKE '%" . $TITLE . "%' "; $fillPart = true;
        }
    }
    if ($GENRE != "") {
        if ($STRICTSEARCH == "true") {
            if ($fillPart == true) {
                $queryPart = $queryPart . " AND genre='" . $GENRE . "'";
            } else {
                $queryPart = $queryPart . " genre='" . $GENRE . "'";
            }
        } else {
            if ($fillPart == true) {
                $queryPart = $queryPart . " AND genre LIKE '%" . $GENRE . "%'";
            } else {
                $queryPart = $queryPart . " genre LIKE '%" . $GENRE . "%'";
            }
        }
        $fillPart = true;
    }
    if ($TYPE != "") {
        if ($fillPart == true) {
            $queryPart = $queryPart . " AND type='" . $TYPE . "'";
        } else {
            $queryPart = $queryPart . " type='" . $TYPE . "'";
        }
    }

    if ($LIMIT == "") { $LIMIT = 50; }
    if ($OFFSET == "") { $OFFSET = -1; }

    $query = "SELECT * FROM Anime WHERE " . $queryPart . " LIMIT " . $LIMIT . " OFFSET " . $OFFSET . ";";

    if ($TITLE == "" && $GENRE == "" && $TYPE == "") {
        $query = "SELECT * FROM Anime LIMIT " . $LIMIT . " OFFSET " . $OFFSET . ";";
    }
echo $query;
    try {
        $serverPDO = new SQLite3('resources/data/anime.db');
        $result = $serverPDO->query($query);
        if ($result->fetchArray() == 0) {
            echo "<div class='message warnning'>Nothing Found...</div>";
        }
        while ($row = $result->fetchArray()) {
            echo "<div class='resultContainer'>" .
                     "<p class='title'>" . $row["name"] . "</p>" .
                 "</div>";
        }
    } catch (Exception $e) { echo "<h2 class='message error'>Error!</h2><br/>" . $e; }
}



// Determin action
if (isset($_POST['dbQuery'])) {
    searchDB($_POST['title'],
             $_POST['genres'],
             $_POST['type']);
} else {
    echo "<h2 class='message error''>Error! Illegal Access Method!</h2>";
}

?>
