<?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['newsId'])  ) {

    $error = array("error"=> "Comment 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['newsId'])  ){

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

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

      //exit($userId);


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


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

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

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

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

          $message = array("message"=> "Comment 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));
  }