<?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["comment"]) || !isset($obj['predictionId'])  ) {

    $error = array("error"=> "Prediction is required");
    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['comment']) && isset($obj['predictionId'])  ){

      @$comment =  mysql_prep($obj['comment']);
      @$predictionId =  mysql_prep($obj['predictionId']);

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


      // already predicted 
      $sql = $connectMe->prepare("SELECT * FROM tbl_prediction_result WHERE (predictionId = ?) AND (userId = ?)  " );

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

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

          exit( json_encode($error) ); 
        

      }else {


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

        $correct = 0;


        $stmt = $connectMe->prepare("INSERT INTO tbl_prediction_result ( predictionId, description, userId, date, correct,  status)  VALUES ( ?,?, ?,?, ?,? ) ");  

        $stmt->bindParam(1, $predictionId);
        $stmt->bindParam(2, $comment);

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

        $stmt->bindParam(5, $correct);
        $stmt->bindParam(6, $status);

        if($stmt->execute()){

          $message = array("message"=> "Prediction saved");
          exit( json_encode($message) ); 

        }else{

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

          
        }
      
      
      }
    
    }




  }else{

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

    exit(json_encode($error));
  }