<?php

// Save info to the database...
function saveToDB($LINK, $CATEGORY, $TAGS, $NOTES) {
    try {
        $db = new SQLite3('resources/db/knowledge.db');
        $stmt = $db->prepare('INSERT INTO Knowledge VALUES(?,?,?,?)');

        $stmt->bindValue(1, $LINK, SQLITE3_TEXT);
        $stmt->bindValue(2, $CATEGORY, SQLITE3_TEXT);
        $stmt->bindValue(3, $TAGS, SQLITE3_TEXT);
        $stmt->bindValue(4, $NOTES, SQLITE3_TEXT);

        $stmt->execute();

        echo "<h1 class='success'>Success: Inserted knowledge to the database.</h1>";
    } catch (Exception $e) {
        echo "<h2 class='error'>";
        echo $e;
        echo "</h2>";
    }
}

// Search info from the database...
function searchDB($QUERYPART) {
    try {
        $db = new SQLite3('resources/db/knowledge.db');
        $query = "SELECT * FROM Knowledge WHERE " . $QUERYPART;
        $result = $db->query($query);

        while ($row = $result->fetchArray()) {
            echo "<div class='resultData'>" .
                     "<p>Link: <a href='" . $row["links"] . "' target='_blank'>" .
                          $row["links"] . "</a></p>" .
                     "<p>Category: " . $row["category"] . "</p>" .
                     "<p>Tags: " . $row["tags"] . "</p>" .
                     "<p>Notes:<br/>" . $row["notes"] . "</p>" .
                 "</div>";
        }

        if ($result->fetchArray() == 0) {
            echo "<h2 class='warnning'>Knowledge Not Found...</h2>";
        } else {
            echo "<h2 class='success'>Knowledge Found...</h2>";
        }
    } catch (Exception $e) {
        echo "<h2 class='error'>";
        echo $e;
        echo "</h2>";
    }
}


// Validate access attempt...
if (isset($_POST["saveInfo"])) {
    if (isset($_POST["link"], $_POST["category"])) {
        if ($_POST["link"] != "" && $_POST["category"] != "") {
            saveToDB($_POST["link"],
                     $_POST["category"],
                     $_POST["tags"],
                     $_POST["notes"]);
        } else {
            echo "<h2 class='error'>Error: Must fill at least Link and Category fields!<h2>";
        }
    } else {
        echo "<h2 class='error'>Error: Must fill at least Link and Category fields!<h2>";
    }
} elseif (isset($_POST["searchInfo"])) {
    if (isset($_POST["query"]) && $_POST["query"] != "") {
        searchDB($_POST["query"]);
    } else {
        echo "<h2 class='error'>Error: No query given!<h2>";
    }
} else {
    echo "<h2 class='error'>Error: Access attempt failed! Incorrect access type!<h2>";
}

?>
