<?php
$dbroot = __DIR__ . "/../db/";
define("JETTYDB", "sqlite:" . $dbroot . "jetty.sqlite");
define("ERRJETTYDB", "sqlite:" . __DIR__ . "/../bd/jetty.sqlite");
define("RASTDB", "sqlite:" . $dbroot . "rasmussteen.sqlite");

function create_session()
{
    $name = substr(preg_replace("/[^a-z\d]/i", "", __DIR__), -30);
    session_name($name);
    session_start();
}

function destroy_session()
{
    $_SESSION = array();
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params["path"],
            $params["domain"],
            $params["secure"],
            $params["httponly"]
        );
    }
    session_destroy();
}

function get_page($pageArr)
{
    $page = isset($_GET["page"]) ? $_GET["page"] : "me";
    if (array_key_exists($page, $pageArr)) {
        return array("id" => $page, "file" => "pages/$page.php", "title" => $pageArr[$page]);
    } else {
        return array("id" => "404", "file" => "pages/404.php", "title" => "404");
    }
}

function get_style($styleArr)
{
    if (isset($_POST["style"])) {
        $_SESSION["style"] = $_POST["style"];
    }
    if (isset($_GET["style"])) {
        $_SESSION["style"] = $_GET["style"];
    }
    $style = isset($_SESSION["style"]) ? $_SESSION["style"] : "default";

    if (array_key_exists($style, $styleArr)) {
        return array("id" => $style, "file" => $styleArr[$style]);
    } else {
        return array("id" => "default", "file" => $styleArr["default"]);
    }
}

function get_usagedata()
{
    return array(
        "files" => count(get_included_files()),
        "memory" => round(memory_get_peak_usage(true) / pow(10, 6), 1),
        "time" => round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 3)
    );
}

function create_navbar($pageArr, $pageId)
{
    $navButtons = "";
    foreach ($pageArr as $id => $name) {
        $class = $pageId == $id ? "class=\"selected\"" : "";
        $navButtons .= "<a $class href=\"?page=$id\">$name</a>";
    }
    return $navButtons;
}

function create_stylechooser($styleArr, $styleId)
{
    $styleOpts = "";
    foreach (array_keys($styleArr) as $id) {
        $selected = $styleId == $id ? "selected" : "";
        $text = ucfirst($id);
        $styleOpts .= "<option value=\"$id\" $selected>$text</option>";
    }
    return $styleOpts;
}

function check_libs()
{
    if (class_exists('PDO') && in_array("sqlite", pdo_drivers())) {
        return true;
    } else {
        return false;
    }
}

function connect_database($dsn)
{
    try {
        $db = new PDO($dsn);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $db;
    } catch (PDOException $e) {
        echo "DSN: $dsn";
        echo "<p style=\"color: red;\">$e</p>";
        return null;
    }
}

function create_statement($querySql)
{
    if (check_libs()) {
        $db = connect_database(RASTDB);
        if ($db != null) {
            return $db->prepare($querySql);
        } else {
            echo "ERROR: Failed to get the requested database.";
        }
    } else {
        echo "ERROR: The sqlite PDO drive is disabled.";
    }
}

function format_comments($queryResult)
{
    $rows = null;
    foreach ($queryResult as $row) {
        $name = htmlentities($row["name"]);
        $time = htmlentities($row["time"]);
        $text = htmlentities($row["text"]);

        $rows .= "<div class=\"comment\">";
        $rows .= "$name wrote on $time UTC<br />";
        $rows .= "<p>$text</p>";
        $rows .= "</div>";
    }
    return $rows;
}

function get_comments($parent, $maxResults)
{
    $stmt = create_statement("SELECT * FROM comments WHERE parent = ? ORDER BY datetime(time) DESC LIMIT ?");
    $params = [$parent, $maxResults];
    try {
        $stmt->execute($params);
        $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return format_comments($res);
    } catch (PDOException $e) {
        return "<p>Failed to get comments.</p>";
        throw $e;
    }
}

function get_comments_table($res)
{
    if (count($res) > 0) {
        $rows = "<table cellspacing=\"0\" cellpadding=\"0\"><tr>";
        #$rows .= "<th>Id</th>";
        $rows .= "<th>Time</th>";
        $rows .= "<th>Parent</th>";
        $rows .= "<th>Author</th>";
        $rows .= "<th>Text</th></tr>";
        foreach ($res as $row) {
            #$id = htmlentities($row["id"]);
            $name = htmlentities($row["name"]);
            $parent = htmlentities($row["parent"]);
            $time = htmlentities($row["time"]);
            $text = htmlentities($row["text"]);

            #$rows .= "<tr><td>$id</td>";
            $rows .= "<td>$time</td>";
            $rows .= "<td>$parent</td>";
            $rows .= "<td>$name</td>";
            $rows .= "<td>$text</td></tr>";
        }
        $rows .= "</table>";
        return $rows;
    } else {
        return "<p>Lyckades inte hitta vad du sökte efter.</p><p>Det kan vara så att du stavat fel eller att det du sökte efter inte finns i databasen.</p>";
    }
}

// Ugly AF
function printJettyResultsetToHTMLTable($res)
{
    $rows = null;
    foreach ($res as $row) {
        $rows .= "<tr><td>{$row['jettyPosition']}</td><td>{$row['boatType']}</td><td>{$row['boatEngine']}</td><td>{$row['boatLength']}</td><td>{$row['boatWidth']}</td><td>{$row['ownerName']}</td></tr>";
    }
    echo "<table cellspacing=\"0\" cellpadding=\"0\"><tr><th>jettyPostion</th><th>boatType</th><th>boatEngine</th><th>boatLength</th><th>boatWidth</th><th>ownerName</th></tr>$rows</table>";
}
