<?php
require __DIR__ . '/vendor/autoload.php';

require_once('config/config.php');

use \Firebase\JWT\JWT;
//// Suppose you have submitted your form data here with username and password
$action = $_REQUEST['action'];
if ( !is_null($_REQUEST['username']) && !is_null($_REQUEST['password']) && $action == 'login' ) {
  // if there is no error below code run
  $stmt = $db_conn->stmt_init();
  $stmt->prepare("select id,name,password from login where name = ?");
  $stmt->bind_param("s", $_REQUEST["username"]);
  $stmt->execute();
  $stmt->bind_result($app_id, $app_name, $app_password);
  $stmt->fetch();
  if(!is_null($app_password) && password_verify($_REQUEST['password'],$app_password)) {
    $tokenId    = base64_encode(openssl_random_pseudo_bytes(32));
    $issuedAt   = time();
    $notBefore  = $issuedAt + 10;  //Adding 10 seconds
    $expire     = $notBefore + 7200; // Adding 60 seconds
    $serverName = 'https://pplus.thieme-logistik.de/'; // set your domain name

    /*
     *Create the token as an array
     */
    $data = [
      'iat'  => $issuedAt,         // Issued at: time when the token was generated
      'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
      'iss'  => $serverName,       // Issuer
      'nbf'  => $notBefore,        // Not before
      'exp'  => $expire,           // Expire
      'data' => [                  // Data related to the logged user you can set your required data
        'id'   => $app_id, // id from the users table
        'name' => $app_name, //  name
      ]
    ];
  $secretKey = base64_decode(SECRET_KEY);
  /// Here we will transform this array into JWT:
  $jwt = JWT::encode(
    $data, //Data to be encoded in the JWT
    $secretKey, // The signing key
    ALGORITHM
  );
  $unencodedArray = ['jwt' => $jwt];
  echo  "{'status' : 'success','resp':".json_encode($unencodedArray)."}";
  } else {
    echo  "{'status' : 'error','msg':'Invalid user or password'}";
  }
} elseif( $action == 'order' && !is_numeric($_REQUEST['input'])) {
  try {
    $secretKey = base64_decode(SECRET_KEY);
    $DecodedDataArray = JWT::decode($_REQUEST['input'], $secretKey, array(ALGORITHM));
    include("include/order.php");
  } catch (Exception $e) {
    echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
  }
}elseif( $action == 'order' ) {
    include("include/order.php");
}

?>
