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

    $error = array("error"=> "Click to follow");
    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['clubId'])  ){

      @$clubId =  mysql_prep($obj['clubId']);
      @$userId =  mysql_prep(@$decodeToken->ID);

      //check if like is already exists
      $sql = $connectMe->prepare(" SELECT * FROM tbl_follow WHERE (clubId = ?) AND (userId = ?) "); 

      $sql->bindParam(1, $clubId);
      $sql->bindParam(2, $userId);

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

        $error = array("error"=> 'You already followed this');
        exit( json_encode($error) ); 

        

      
      }else {


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


        $stmt = $connectMe->prepare("INSERT INTO tbl_follow(clubId, userId, date, status)  VALUES ( ?,?, ?,?) ");  

        $stmt->bindParam(1, $clubId);
        $stmt->bindParam(2, $userId);

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

        if($stmt->execute()){

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