<?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['userId'])  || !isset($obj['courseId'])  ){

    //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") ));

    }



  //enrol student

  if (isset($obj['userId'])  && isset($obj['courseId'])  ) {


    $userId = mysql_prep($obj['userId']);
    $courseId = mysql_prep($obj['courseId']);

    $token = mysql_prep(uniqid());
  

      $sql = $connectMe->prepare("SELECT * FROM tbl_enrol WHERE tbl_courseId = ?  AND tbl_userId =?  " );
      $sql->bindParam(1, $courseId);

      $sql->bindParam(2, $userId);
      $sql->execute();
  
      if($sql->rowCount() > 0){
        
        //http_response_code(409);
        $error = array("error"=> "You are already enrolled");

        exit( json_encode($error) ); 

        

      }else {


        $date = date("Y-m-d");
        $hour = date("H:i:sa");

        $status = 1;

        $sql = $connectMe->prepare("INSERT INTO tbl_enrol (tbl_courseId, tbl_userId, tbl_enrolDate, tbl_enrolTime, tbl_enrolToken, tbl_enrolStatus) VALUES (?,?,?, ?,?,? )" );
        
        $sql->bindParam(1, $courseId);
        $sql->bindParam(2, $userId);

        $sql->bindParam(3, $date);
        $sql->bindParam(4, $hour);

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

        if($sql->execute()){

          $message = array("message"=> 'Student enroled');
          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") ));

  }