<!doctype html>
<?php
session_start();
require_once("lib/parsedown/Parsedown.php");
require_once("lib/lti/lti_util.php");
require_once("settings.php");

function debug($message, $variable, $pail_debug) {
  if ($pail_debug) {
    if ($message) {
      echo $message . " ";
    }
    if (!is_null($variable)) {
      var_dump($variable);
    }
    echo "<br />";
  }
}
?>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo $pail_title; ?></title>
    <meta name="description" content="<?php echo $pail_description; ?>">
    <meta name="author" content="PAIL">

    <link rel="icon" href="favicon.ico">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">

    <link rel="stylesheet" href="lib/github-markdown-css/github-markdown.css">
  </head>

  <body class="markdown-body">
    <?php
      debug("Starting...", null, $pail_debug);
      // Check if this is a valid LTI request
      $valid_lti_request = is_lti_request();
      debug("Valid LTI request:", $valid_lti_request, $pail_debug);
      if ($valid_lti_request) {
        $oauth_consumer_key = "";
        $oauth_consumer_secret = "";
        if (isset($_POST["oauth_consumer_key"])) {
          $oauth_consumer_key = $_POST["oauth_consumer_key"];
          $oauth_consumer_secret = $pail_oauth_consumer_secret;
          $_SESSION["oauth_consumer_key"] = $oauth_consumer_key;
          $_SESSION["oauth_consumer_secret"] = $oauth_consumer_secret;
        }
        debug("oauth_consumer_key", $oauth_consumer_key, $pail_debug);
        debug("oauth_consumer_secret", $oauth_consumer_secret, $pail_debug);
        $context = new BLTI($oauth_consumer_secret, true, false);
        // Ensure context is valid and context_id and user_id are alphanumeric only
        $valid_lti_request = $context->valid
          && ctype_alnum($context->info[$pail_context_id]) && ctype_alnum($context->info[$pail_user_id]);
      }
      if (!$valid_lti_request) {
        // If not a valid LTI request, display an error
        debug("LTI message type should be 'basic-lti-launch-request'", $_REQUEST["lti_message_type"], $pail_debug);
        debug("LTI version should be 'LTI-1p0'", $_REQUEST["lti_version"], $pail_debug);
        debug("Ensure context id is alphanumeric only", $context->info[$pail_context_id], $pail_debug);
        debug("Ensure user id is alphanumeric only", $context->info[$pail_user_id], $pail_debug);
        debug("Invalid LTI context", $context, $pail_debug);
        require("error_templates/not_lti.php");
      } else {
        debug("LTI Context: ", $context, $pail_debug);
        // Determine name of file to display
        $pail_dirname = getcwd() . DIRECTORY_SEPARATOR .
          $pail_generated_dir . DIRECTORY_SEPARATOR .
          $context->info[$pail_context_id] . DIRECTORY_SEPARATOR .
          $context->info[$pail_user_id] . DIRECTORY_SEPARATOR;
        // Default to display.md unless another file is requested
        $pail_filename = isset($_REQUEST["display"]) ? $_REQUEST["display"] : "display.md";
        $pail_filename = $pail_dirname . $pail_filename;
        debug("pail_filename:", $pail_filename, $pail_debug);
        debug("pail_reset:", $pail_reset, $pail_debug);
        debug("pail_filename exists: " . file_exists($pail_filename), null, $pail_debug);
        // Generate file if necessary
        if ($pail_reset || !file_exists($pail_filename)) {
          debug("Generating:", $pail_filename, $pail_debug);
          $output = null;
          $retval = null;
          $pail_command = "./generate.sh " .
            "-c \"" . $context->info[$pail_context_id] . "\"" . " ".
            "-u \"" . $context->info[$pail_user_id] . "\" " .
            $pail_generate_command;
          debug("Executing:", $pail_command, $pail_debug);
          exec($pail_command, $output, $retval);
          debug("Output:", $output, $pail_debug);
          debug("retval", $retval, $pail_debug);
        }

        // Attempt to read the file
        $file_contents = false;
        if (file_exists($pail_filename)) {
          $file_contents = file_get_contents($pail_filename);
        }
        if ($file_contents === false) {
          // Display error if unable to read file
          debug("Unable to read file:", $file_contents, $pail_debug);
          require("error_templates/file_unavailable.php");
        // Display file
        } else {
          echo Parsedown::instance()->text($file_contents) . "\n";
        }
      }
      debug("Finished", null, $pail_debug);
    ?>
    <footer><small>Generated by <a href="https://gitlab.une.edu.au/dpaul4/pail">PAIL</a></small></footer>
    <script>
    document.querySelectorAll('a[href^="http"]').forEach(link => {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener');
    });
    </script>
  </body>
</html>