<?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['title']) || !isset($obj['subTitle']) || !isset($obj['desc']) || !isset($obj['image'])  ) {

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

    }


    if( isset($obj['title']) && isset($obj['subTitle']) && isset($obj['desc']) && isset($obj['image']) ){

      @$title =  mysql_prep($obj['title']);
      @$subTitle =  mysql_prep($obj['subTitle']);

      @$description =  ($obj['desc']);
      @$image =  ($obj['image']);

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


      //check if news is already exists
      $sql = $connectMe->prepare(" SELECT * FROM tbl_news WHERE (title = ?) "); 

      $sql->bindParam(1, $title);
      $sql->execute();

      if($sql->rowCount() > 0){ 

        $error = array("error"=> $title.' is already exist');
        exit( json_encode($error) ); 

        

      
      }else {


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

      $tk = uniqid();
      $live = 0;

      $likes = 0;


        $stmt = $connectMe->prepare("INSERT INTO tbl_news (title, subtitle, description, image, clubId, date, tk, status, live, userId, likes)  VALUES ( ?,?,?, ?,?,?, ?,?,?, ?,?) ");  

        $stmt->bindParam(1, $title);
        $stmt->bindParam(2, $subTitle);

        $stmt->bindParam(3, $description);
        $stmt->bindParam(4, $image);

        $stmt->bindParam(5, $clubId);
        $stmt->bindParam(6, $date);

        $stmt->bindParam(7, $tk);
        $stmt->bindParam(8, $status);

        $stmt->bindParam(9, $live);
        $stmt->bindParam(10, $userId);

        $stmt->bindParam(11, $likes);

        if($stmt->execute()){

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