<?php

namespace SmartMob;


class Billing
{
    private $package = "";
    private $market_params = null;
    private $post_data = array();

    public function __construct($package = "", $market_params = null)
    {
        $this->package = $package;
        if($market_params)
        $this->market_params = $market_params;

    }

    public function getProductId(){
        return $this->post_data["product_id"];
    }
    public function getToken(){
        return $this->post_data["token"];
    }
    public function getUserId(){
        return $this->post_data["user_id"];
    }
    public function getMarket(){
        return $this->post_data["market"];
    }
    public function setCafeBazaarParams($client_id, $client_secret, $refresh_code){
        $this->setMarketParams("cafe-bazaar", $client_id, $client_secret, $refresh_code);
    }

    public function setIranAppsParams($client_id, $client_secret, $refresh_code){
        $this->setMarketParams("iranapps", $client_id, $client_secret, $refresh_code);
    }

    public function setMarketParams($market_name, $client_id, $client_secret, $refresh_code){
        if(!$this->market_params){
            $this->market_params = array();
        }
        $this->market_params[$market_name] = array('grant_type' => 'refresh_token', 'client_id' => $client_id, 'client_secret' => $client_secret, 'refresh_token' => $refresh_code);
    }

    public function isValidRequest()
    {
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
            $response = $this->checkData($input);

        return $response && isset($response->purchaseState ) && $response->purchaseState == 0;
    }

    public function isValidData($data)
    {
            $response = $this->checkData($data);

        return $response && isset($response->purchaseState ) && $response->purchaseState == 0;
    }

    public function isValid($product_id, $purchase_token, $market = "cafe-bazaar", $user_id = "")
    {
        $response = $this->check($product_id, $purchase_token, $market,$user_id);
        return $response && isset($response->purchaseState ) && $response->purchaseState == 0;

    }

    public function successResponse($message = "",$echo = true){
        return $this->makeResponse(true, $echo,$message);
    }
    public function failResponse($echo = true){
        return $this->makeResponse(false, $echo);
    }
    private function makeResponse($valid, $echo = true, $message = ""){
        $data = array("purchaseState"=>$valid?"valid":"invalid", "message"=>$message);
        if($echo){
            echo json_encode($data);
        }
        return $data;
    }

    public function checkData($data)
    {
        return $this->check($data["product_id"], $data["purchase_token"], $data["market_name"], $data["user_id"], isset($data["package_name"])?$data["package_name"]:null);
    }

    public function check($product_id, $purchase_token, $market = "cafe-bazaar", $user_id = "", $package_name)
    {
        if($package_name != null){
            $this->package = $package_name;
        }
        $this->post_data = array("product_id"=>$product_id, "token"=>$purchase_token, "user_id"=>$user_id, "market"=>$market, "package_name" => $package_name);
        if ($market == "cafe-bazaar") {
            $url = 'https://pardakht.cafebazaar.ir/devapi/v2/auth/token/';
            $data = $this->market_params[$market];

            $ch = curl_init($url);
            $postString = http_build_query($data, '', '&');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);

            $jsonResponse = json_decode($response, true);
            $access_token = $jsonResponse['access_token'];
            $ch2 = curl_init("https://pardakht.cafebazaar.ir/devapi/v2/api/validate/$this->package/inapp/$product_id/purchases/$purchase_token/?access_token=$access_token");
            curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch2);
            curl_close($ch2);

        } else if ($market == "myket") {
            try {
                $url = "https://api.myket.ir/IapService.svc/getpurchases?";
                $data = array(
                    "packagename" => $this->package,
                    "productId" => $product_id,
                    "token" => $purchase_token,
                );
                $postString = http_build_query($data, '', '&');
                $ch2 = curl_init($url . $postString);
                curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
                $result = curl_exec($ch2);
                curl_close($ch2);
            } catch (\Exception $e) {
                return false;
            }
        } else if ($market == "iranapps") {
            $url = 'http://api.iranapps.ir/v2/auth/token/';
            $data = $this->market_params[$market];

            $ch = curl_init($url);
            $postString = http_build_query($data, '', '&');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            $jsonResponse = json_decode($response, true);
            $access_token = $jsonResponse['access_token'];
            $result = file_get_contents("http://api.iranapps.ir/v2/applications/$this->package/purchases/products/$product_id/tokens/$purchase_token?access_token=$access_token");

        } else {
            return false;
        }

        $res = json_decode($result);
        return $res;

    }

}

