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

    $error = array("error"=> "Select result");
    exit( json_encode($error) ); 

  }

  //exit(var_dump(getallheaders()));


  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['optionId']) && isset($obj['voteId'])  ){

      @$optionId =  mysql_prep($obj['optionId']);
      @$voteId =  mysql_prep($obj['voteId']);
      
      @$userId =  mysql_prep(@$decodeToken->ID);
      $status = 1;

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


      $sql = $connectMe->prepare("SELECT * FROM tbl_vote_result VR, tbl_vote_option VO WHERE (VR.optionId = VO.id) AND (VO.voteId = ?) AND VR.userId = ?  " );

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

      $sql->execute();
  
      if($sql->rowCount() > 0){
        
        //http_response_code(409);
        $error = array("error"=> "Vote is already exist");

        exit( json_encode($error) ); 

        

      }else {


        //option by id
        $optionInfo = find_vote_option_by_id($optionId);

        if(!isset($optionInfo)){
          $error = array("error"=> "Option does not exist");
          exit( json_encode($error) ); 
        }


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

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

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

        if($stmt->execute()){

          
          // update votes
          $total = $optionInfo->votes + 1;

          update_vote_option_by_id($total, $optionId);

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