<?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['name'])  || !isset($obj['desc']) || !isset($obj['period'])  || !isset($obj['cost']) || !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") ));

    }



  //update course

  if (isset($obj['name'])  && isset($obj['desc']) && isset($obj['period']) && isset($obj['cost']) && isset($obj['courseId'])  ) {


    $name = mysql_prep($obj['name']);
    $desc = mysql_prep($obj['desc']);

    $period = mysql_prep($obj['period']);
    $cost = mysql_prep($obj['cost']);
    
    $courseId = mysql_prep($obj['courseId']);
    $token = mysql_prep(uniqid()); 
  

        $sql = $connectMe->prepare("UPDATE tbl_course SET tbl_courseName = ?, tbl_courseDesc =?, tbl_courseLength =?, tbl_courseCost =? WHERE tbl_courseId =? " );
        
        $sql->bindParam(1, $name);
        $sql->bindParam(2, $desc);

        $sql->bindParam(3, $period);
        $sql->bindParam(4, $cost);

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

        if($sql->execute()){

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

  }