<?php

include_once("inc/config.php");


define("BC_ACCOUNT_PARTNER_ACCESS_TOKEN", "ravmaa3vpsio27hiqp39rrdiwtcssi0"); // this is from devloper portal 
//define("DEFAULT_PRICE2", 0);


function create_ub_checkout($user_store_hash,$user_account_id)
{
    global $bc_ub_apiUrl;
    
    /*echo "url is",$bc_ub_apiUrl;
    
    
    exit();
    */
    $graphqlQuery = <<<GRAPHQL
    mutation (\$checkout: CreateCheckoutInput!) {
      checkout {
        createCheckout(input: \$checkout) {
          checkout {
            id
            accountId
            status
            checkoutUrl
            items(first: 1) {
              edges {
                node {
                  subscriptionId
                  status
                  product {
                    id
                    type
                    productLevel
                  }
                  scope {
                    id
                    type
                  }
                  pricingPlan {
                    interval
                    price {
                      value
                      currencyCode
                    }
                    trialDays
                  }
                  redirectUrl
                  description
                }
              }
            }
          }
        }
      }
    }
GRAPHQL;

    
    $variables = [
        "checkout" => [
            "accountId" => "bc/account/account/".$user_account_id,
            "items" => [
                [
                    "product" => [
                        "id" => "bc/account/product/".APP_ID,
                        "type" => "APPLICATION",
                        "productLevel" => null
                    ],
                    "scope" => [
                        "id" => "bc/account/scope/".$user_store_hash,
                        "type" => "STORE"
                    ],
                    "pricingPlan" => [
                        "interval" => "MONTH",
                        "price" => [
                            "value" =>DEFAULT_PRICE,
                            "currencyCode" => "USD"
                        ],
                        "trialDays" => 0
                    ],
                    "description" => "App Subscription - Standard",
                    "redirectUrl" => BASE_PATH."UB_subscriptions_success.php?store_hash=".$user_store_hash
                ]
            ]
        ]
    ];

   /* print_r($variables);
    
    exit();*/

   
    $payload = json_encode([
        'query' => $graphqlQuery,
        'variables' => $variables
    ]);
    
    $ch = curl_init($bc_ub_apiUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-Auth-Token: ' .BC_ACCOUNT_PARTNER_ACCESS_TOKEN,
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

    
    $response = curl_exec($ch);

    
    if (curl_errno($ch)) {
        echo 'cURL Error: ' . curl_error($ch);
    } else {
        /*echo "Response 3:\n";
        echo $response,"<pre>";*/

        //exit();

       

        $ub_checkout_res=json_decode($response,true);
        /* print_r($ub_checkout_res);
        echo "</pre>";*/

        if(isset($ub_checkout_res["data"]["checkout"]["createCheckout"]["checkout"]["id"]))
        {
            $return_array=array();
            $res_ub_checkout_id=$ub_checkout_res["data"]["checkout"]["createCheckout"]["checkout"]["id"];
            $res_ub_checkout_url=$ub_checkout_res["data"]["checkout"]["createCheckout"]["checkout"]["checkoutUrl"];

            $return_array[]=$res_ub_checkout_id;
             $return_array[]=$res_ub_checkout_url;

             return $return_array;
        }
        else{
            return [];
        }
    }

    curl_close($ch);
}

function get_ub_checkout($ub_checkout_id)
{


    global $bc_ub_apiUrl;
    $checkoutId = $ub_checkout_id;

    //echo "id is",$checkoutId;

    // GraphQL Query
    $graphqlQuery = <<<GRAPHQL
    query Account(\$checkoutId: ID!) {
      account {
        checkout(id: \$checkoutId) {
          id
          accountId
          checkoutUrl
          status
          items {
            edges {
              node {
                description
                status
                product {
                  id
                  productLevel
                  type
                }
                scope {
                  id
                  type
                }
                pricingPlan {
                  price {
                    value
                    currencyCode
                  }
                  interval
                  trialDays
                }
                subscriptionId
                redirectUrl
              }
            }
          }
        }
      }
    }
GRAPHQL;

    // Variables
    $variables = [
        'checkoutId' => $checkoutId
    ];

    // Payload
    $payload = json_encode([
        'query' => $graphqlQuery,
        'variables' => $variables
    ]);

    // cURL setup
    $ch = curl_init( $bc_ub_apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
       'Accept: application/json',
        'X-Auth-Token: ' .BC_ACCOUNT_PARTNER_ACCESS_TOKEN,
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

    // Execute request
    $response = curl_exec($ch);

    // Handle errors
    if (curl_errno($ch)) {
        echo 'cURL Error: ' . curl_error($ch);
    } else {
        /*echo "Response:\n";
        echo $response;*/

        $checkout_response=json_decode($response,true);
        $bc_subscription_id="";

        /*print_r($checkout_response);
        exit();*/
        if(isset($checkout_response["data"]["account"]["checkout"]["status"]) && $checkout_response["data"]["account"]["checkout"]["status"]=="COMPLETE")
        {
            $bc_subscription_id=$checkout_response["data"]["account"]["checkout"]["items"]["edges"][0]["node"]["subscriptionId"];
            return $bc_subscription_id;

        }else{
           return $bc_subscription_id;
        }
    }

    curl_close($ch);


}

function UB_cancel_subscription($subscription_id,$store_hash)
{
    global $bc_ub_apiUrl,$conn_db;


    $subscriptionInput = [
        'subscription' => [
            'subscriptionId' => $subscription_id
        ]
    ];

    $mutation = <<<'GRAPHQL'
    mutation ($subscription: CancelSubscriptionInput!) {
        subscription {
            cancelSubscription(input: $subscription) {
                subscriptionId
                cancelledAt
            }
        }
    }
GRAPHQL;

    $requestData = [
        'query' => $mutation,
        'variables' => $subscriptionInput
    ];

    $ch = curl_init($bc_ub_apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json',
       'X-Auth-Token: ' .BC_ACCOUNT_PARTNER_ACCESS_TOKEN,
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);
    //print_r($responseData);
    
    

    if(isset($responseData["data"]["subscription"]["cancelSubscription"]["subscriptionId"]))
    {
        $bc_cancel_at=$responseData["data"]["subscription"]["cancelSubscription"]["cancelledAt"];
        mysqli_query($conn_db,"UPDATE `bc_ubSubscription` SET bc_cancelledAt='$bc_cancel_at' WHERE `store_id`='$store_hash'");
        
        return true;

    }else{
        
        return false;
    }


}
?>