<?php
declare(strict_types=1);

namespace DIGMA\Mediaserver;

include( 'init.inc.php' );

$requestUri = $_SERVER['REQUEST_URI'];
$pathinfo = trim( substr( $requestUri, strlen( $_SERVER['SCRIPT_NAME'] )), '/' );
if( preg_match( '/^(.*)\?/', $pathinfo, $matches )) {
  $pathinfo = $matches[1];
}
$params = explode( '/', $pathinfo );
array_walk( $params, function( &$value, &$key ) {
  $value = urldecode( $value );
});
$collection = array_shift( $params );
$signature = array_shift( $params );
$action = array_shift( $params );
$params = implode( '/', $params );

$master = null;
try {
  $coll = Collection::withName( $db, $collection );
  $master = Master::withSignature( $db, $coll, $signature );
  if( !$master->isIngested()) {
    $master->ingest();
  }
}
catch( \Exception $ex ) {
  http_response_code(404);
?>
<html>
<head>
  <title>404 Page not found: <?php echo $_SERVER['REQUEST_URI']; ?></title>
</head>
<body>
  <h1>404 Page not found</h1>
  <p><?php echo $_SERVER['REQUEST_URI']; ?></p>
  <p><?php echo $ex->getMessage(); ?></p>
  <p><code><?php echo nl2br( ''.$ex ); /* ->getTraceAsString(); */ ?></code></p>
</body>
</html>
<?php
die();
}

try {
  //header("Access-Control-Allow-Origin: *");

  $theAction = Action::withAction( $master, $action, $params );
//  var_dump( $theAction );
//  exit;
  $cache = $theAction->getCache();

  $storage = $cache->getStorage();
  $jwtkey = $storage->getJWTKey();
  if( strlen( $jwtkey ) > 0 ) {
    $token = array_key_exists( 'token', $_REQUEST ) ? $_REQUEST[ 'token' ] : '';
    if( !strlen( $token )) {
      header('HTTP/1.0 403 Forbidden');
      echo 'no JWT Token';
      die();
    }
    try {
        //echo strtolower( $config['jwt_subject_prefix'].$cache->getSubject())."\n";
        $decoded_token = jwt_decode($token, $jwtkey, ['sub'=>strtolower( $config['jwt_subject_prefix'].$cache->getSubject()), 'algorithm' => 'HS256' ] );
        if( !$decoded_token ) {
          header('HTTP/1.0 403 Forbidden');
          echo 'cannot decode token';
          die();
        }
        if( intval($decoded_token['exp']) <= time()) {
          header('HTTP/1.0 403 Forbidden');
          echo 'JWT Token expired';
          print_r( $decoded_token );
          die();
        }
    } catch (ExpiredSignatureException $e) {
        header('HTTP/1.0 403 Forbidden');
        echo 'JWT Token expired';
        print_r( $decoded_token );
        die();
    } catch (BeforeValidException $e) {
      header('HTTP/1.0 403 Forbidden');
      echo 'JWT Token not yet valid';
      print_r( $decoded_token );
      die();
    } catch (InvalidSubException $e) {
      header('HTTP/1.0 403 Forbidden');
      echo "Wrong subject: {$decoded_token['sub']} != ".$cache->getSubject();
      print_r( $decoded_token );
      die();
    }
    catch(Exception $e ) {
      header('HTTP/1.0 403 Forbidden');
      echo 'Unknown exception: '.$e->getMessage();
      print_r( $decoded_token );
      die();
    }
  }
}
catch( \Exception $ex ) {
  header( 'Content-type: text/plain' );
  echo $ex->getMessage();
  print_r( $decoded_token );
  die();
}
header( 'Content-type: '.$cache->getMimetype());
header( 'Cache-Control: max-age='.(7*86400));

if( $cache->isTransient()) {
  echo $cache->getPayload();
}
else {
  $file = $cache->getFullpath();
  header( 'Content-Length: '.filesize($file));
  readfile( $file );
}


//echo "Signature: {$signature}\n";
//echo "Action: {$action}\n";
//echo "Params: {$params}\n";

//phpinfo();
