<?php

require_once 'vendor/autoload.php';
require_once 'post_adapter.php';

// $sql = mysqli_connect('mysql', 'root', 'example', 'dragon_fire');

$adapter = new PostHandler();

//if (!$sql)
// {
//    echo 'Connection failed<br>';
//    echo 'Error number: ' . mysqli_connect_errno() . '<br>';
//    echo 'Error message: ' . mysqli_connect_error() . '<br>';
//    die();
// }

$loader = new \Twig\Loader\FilesystemLoader(['./templates', './user_content']);

$twig = new \Twig\Environment($loader,['debug' => true]);
$twig->addExtension(new Twig\Extra\Markdown\MarkdownExtension());

use Twig\Extra\Markdown\DefaultMarkdown;
use Twig\Extra\Markdown\MarkdownRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
    public function load($class) {
        if (MarkdownRuntime::class === $class) {
            return new MarkdownRuntime(new DefaultMarkdown());
        }
    }
});

$SURI = $_SERVER['REQUEST_URI'];

if(preg_match('/^\/api\/admin/', $SURI)) {
    header('Content-Type: application/json');

    $user_api_key = '';
    if(isset($_GET['api_key'])) {
        $user_api_key = $_GET['api_key'];
    }
    if(isset($_POST['api_key'])) {
        $user_api_key = $_POST['api_key'];
    }

    if($user_api_key != file_get_contents('secrets/api_admin_key')) {
        http_response_code(401);

        echo json_encode([
            "authorized" => false
        ]);

        die();
    }

    if($SURI = '/api/admin/upload') {
        $adapter->handle_upload($_POST['post_path'], $_FILES['post_data']['tmp_name']);

        echo json_encode(["ok" => true]);
    }
} elseif(preg_match('/^\/api/', $SURI)) {
    if(preg_match('/^\/api\/posts(.*)$/', $SURI, $match)) {

        header('Content-Type: application/json');
        echo json_encode($adapter->get_post_by_path($match[1]));

    } elseif(preg_match('/^\/api\/subposts(.*)$/', $SURI, $match)) {

        header('Content-Type: application/json');
        echo json_encode(get_subposts($match[1]));
    } elseif($SURI == '/api/upload') {

        echo $twig->render('upload.html');
    }
} elseif(preg_match('/^\s*image/', $_SERVER['HTTP_ACCEPT'])) {
    header('Location: /raw' . $SURI);
    exit(0);
} elseif(true) {
    $post = $adapter->get_post_by_path($SURI);

    if(!$post['found']) {
        echo $twig->render('post_types/rrror.html',[
            "error_code" => '404 Hoard not found!',
            "error_description" => "Well, we searched 
                far and wide for `" . $SURI . "` but 
                somehow it must have gotten lost... Sorry!",
            "post" => $post
        ]);	
        
        exit(0);
    }

    if($post['post_metadata']['type'] == 'directory') {
        if(preg_match('/^(.*[^\/])((?:#.*)?)$/', $SURI, $match)) {
            header('Location: ' . $match[1] . '/' . $match[2]);
            exit(0);
        }

        echo $twig->render('post_types/directory.html', [ 
            "post" => $post,
            "subposts" => $post['subposts']
        ]);
    }
    elseif($post['post_metadata']['type'] == 'text/markdown') {
        echo $twig->render('post_types/markdown.html', [ 
            "post" => $post,
            "subposts" => $post['subposts']
        ]);
    }
    elseif($post['post_metadata']['type'] == 'image') {
        echo $twig->render('post_types/image.html', [
            "post" => $post
        ]);
    }

} else {
	echo $twig->render('rrror.html',[
        "error_code" => '404 Hoard not found!',
		"error_description" => "Well, we searched 
            far and wide for `" . $SURI . "` but 
            somehow it must have gotten lost... Sorry!"
	]);	
}

?>
