<?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['enrolId'])  || !isset($obj['date']) || !isset($obj['marks'])  ){

    //http_response_code(400);

    $error = array("error"=> "Fill all fields");
    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") ));

    }



  //certify student

  if (isset($obj['enrolId'])  && isset($obj['date']) && isset($obj['marks'])  ) {


    $enrolId = mysql_prep($obj['enrolId']);
    $date = mysql_prep($obj['date']);

    $marks = mysql_prep($obj['marks']);
    $token = mysql_prep(uniqid());
  

      $sql = $connectMe->prepare("SELECT * FROM tbl_certified WHERE tbl_enrolId = ?  " );
      $sql->bindParam(1, $enrolId);

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

        exit( json_encode($error) ); 

        

      }else {


        $status = 1;

        $sql = $connectMe->prepare("INSERT INTO tbl_certified (tbl_enrolId, tbl_certifiedDate, marks, tbl_userId, tbl_certifiedStatus) VALUES (?,?,?, ?,?)" );
        
        $sql->bindParam(1, $enrolId);
        $sql->bindParam(2, $date);

        $sql->bindParam(3, $marks);
        $sql->bindParam(4, $decodeToken->ID);

        $sql->bindParam(5, $status);

        if($sql->execute()){

          $message = array("message"=> 'Student certified');
          exit( json_encode($message) ); 

          

        }else{
            
            //http_response_code(500);

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

          
        }

      }

 
  }



  }else{

    //http_response_code(401);

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

  }