<?php 
	ini_set("display_errors", 1);
	header("Acces-Control-Allow-Origin: *");
	header("Content-type: application/json; charset=UTF-8");
	header("Acces-Control-Allow-Method: POST");
	require_once("../Database/Database.php");
	require_once("../Classes/USERS.php");
	require_once("../Constants/Constants_Variable.php");
	include_once ("../JWT/autoload.php");
	include_once ("../JWT/JWT.php");
	include_once ("../JWT/BeforeValidException.php");
	include_once ("../JWT/ExpiredException.php");
	include_once ("../JWT/SignatureInvalidException.php");
	use \Firebase\JWT\JWT;
	$db=new Database();
	$Connection=$db->Connect();
	$student=new Users($Connection);
	if($_SERVER["REQUEST_METHOD"] === "POST")
	{
		$data=json_decode(file_get_contents("php://input"));
		if(!empty($data->coins) && !empty($data->user_id) && !empty($data->fcm_token))
		{
			$student->user_id=$data->user_id;

			try
			{
				$headers=getallheaders();
				if(array_key_exists('Authorization', $headers) && $headers['Authorization'] != '')
				{
					$token=$headers["Authorization"];
					$secret_key="waheedkhan786";
					$decoded_data=JWT::decode($token,$secret_key,array('HS256'));
					$student->user_id=$decoded_data->data->user_id;
					$student->user_name=$decoded_data->data->user_name;
					$student->user_email=$decoded_data->data->user_email;
					$student->fcm_token=$decoded_data->data->fcm_token;
				}
				else
				{
					throwError(ACCESS_TOKEN_ERROR,"Please add headers");
				}

    			if($decoded_data->data->user_id == $data->user_id && $data->fcm_token==$decoded_data->data->fcm_token )
    			{
    			    if($data->coins == 100)
    			    {
    			        
        				$query="SELECT * FROM `tbl_users` WHERE user_id= '$data->user_id' ";
        				$result = $Connection->query($query);
        				if ($result->num_rows > 0) {
        				    while ($rows=$result->fetch_assoc()) 
        				    {
        				      $coins=$rows['coins'];
        				    }
        				}
        				if($coins >=100)
        				{
        					$coin=$coins - $data->coins;
        					$student->coins=$coin;
        					if($student->add_user_coins())
        					{
        						returnResponse(SUCCESS_RESPONSE,'COINS REDUCED SUCCESSFULLY');
        					}
        					else
        					{
        						throwError(UN_SUCCESS_RESPONSE,"ERROR.");
        					}	
        				}
        				else
        				{
        					throwError(UN_SUCCESS_RESPONSE,"YOUR COINS ARE NOT TOO MUCH.");
        				}
    			      
    			    }
    			   else
                    {  
                         throwError(UN_SUCCESS_RESPONSE,"PLEASE CHECK YOUR COINS LIMIT."); 
                    }
    			}
    			else
    			{
    				throwError(UN_SUCCESS_RESPONSE,"Please check your fcm token or user id");
    			}
			}
			catch(DomainException $ex)
			{
				throwError(TOKEN_UPDATE_ERROR,$ex->getMessage());
			}
			catch(UnexpectedValueException $ex)
			{
				throwError(UN_SUCCESS_RESPONSE,$ex->getMessage());
			}
			catch (InvalidArgumentException $e) 
			{
				throwError(ACCESS_TOKEN_ERROR,$e->getMessage());
			}
		}	
		else
		{
			throwError(UN_SUCCESS_RESPONSE,"All parameters are required.");
		}
	}
	else
	{
		throwError(ACCESS_DENIED_RESPONSE,"Access Denied!... Please check method.");
	}
	 function throwError($code,$message)
		{
			header("content-type:application/json");
			$errorMessage=json_encode(['error'=>['status'=>$code,'message'=>$message]]);
			echo $errorMessage;
			exit;
		}
	 function returnResponse($code,$data)
		{
			header("content-type:application/json");
			$errorMessage=json_encode(['response'=>['status'=>$code,'result'=>$data]]);
			echo $errorMessage;
			exit;
		}
?>