<?php header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: *");  

  header('Content-Type: application/json');

  $json = file_get_contents('php://input');
  $obj = json_decode($json, true);

  include '../db/connectMe.php';   
  include '../function/function.php';  

  // (C) GENERATE JWT TOKEN
  require "../vendor/autoload.php";
  use Firebase\JWT\JWT;

  // (A) NO data
  if (!isset($obj["quizId"]) || !isset($obj['answers'])  ) {

    $error = array("error"=> "Try again");
    exit( json_encode($error) ); 

  }


  if( AuthorizeMe(@substr(getallheaders()["authorization"], 7)) ){

    $jwt = substr(getallheaders()["authorization"], 7);

    //Decoding data
    $decodeToken = (json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $jwt)[1]))))->data);

    if(!isset($decodeToken)){

      exit(json_encode(array("error" => "unauthorised") ));

    }


    if( isset($obj['quizId']) && isset($obj['answers'])  ){

      @$quizId =  mysql_prep($obj['quizId']);
      @$answers = $obj['answers'];

      @$userId =  mysql_prep(@$decodeToken->ID);

      
      foreach ($answers as $answer) {

        $questionId = @$answer['questionId'];
        $optionId   = @$answer['optionId'];

        // already did quiz
        $sql = $connectMe->prepare("SELECT * FROM tbl_result R, tbl_question_option O WHERE (R.optionId = O.id) AND (O.questionId = ?) AND R.userId = ?  " );

        $sql->bindParam(1, $questionId);
        $sql->bindParam(2, $userId);

        $sql->execute();
  
        if($sql->rowCount() > 0){
        
          //http_response_code(409);
          $error = array("error"=> "You already did this quiz");

          exit( json_encode($error) ); 
        

        }else {
        

          //option info
          $optionInfo = find_question_option_by_id($optionId);

          if(!isset($optionInfo)){
            continue;
          }

          // question info
          $questionInfo = find_question_by_id($optionInfo->questionId);

          if(!isset($questionInfo)){
             continue;
          }


          $status = 1;
          $date = date("Y-m-d");

          $marks = 0;

          if($optionInfo->correct == 1){

            $marks = $questionInfo->marks;

          }

          // save reult
          $stmt = $connectMe->prepare("INSERT INTO tbl_result( optionId, userId, marks, date, status)  VALUES ( ?,?, ?,?, ? ) ");  

          $stmt->bindParam(1, $optionId);
          $stmt->bindParam(2, $userId);

          $stmt->bindParam(3, $marks);
          $stmt->bindParam(4, $date);

          $stmt->bindParam(5, $status);
          if($stmt->execute()){

            $message = array("message"=> "Quiz completed");
            //exit( json_encode($message) ); 

          }else{

            $error = array("error"=> 'Something went wrong, please try again');
            //exit( json_encode($error) ); 
          
          }

        }

      }


      $message = array("message"=> "Quiz completed");
      exit( json_encode($message) ); 
      
      


    }




  }else{

    $error = array("error" => "UNAUTHORIZED");

    exit(json_encode($error));
  }