<?php
set_time_limit(0);
ini_set('memory_limit', '-1');
require_once("includes/config.php");

	if(isset($_GET['charge_id'])){
		try { 
			$charge_id = $_GET['charge_id'];
           
			$plan = $_GET['type'];
			$result = $conn->query("select u.id, u.shopurl, u.token from users u, chargerequest c where u.id = c.user_id and c.charge_id = '".mysqli_real_escape_string($conn, $charge_id)."'");
			if($result->num_rows == 0){
				die("Unauthorized access!");
			}
			$row = $result->fetch_assoc();
			$user_id = $row['id'];
			$shopurl = $row['shopurl'];
			$token = $row['token'];
			//$sc = new ShopifyClient($shopurl, $token, SHOPIFY_API_KEY, SHOPIFY_API_PASSWORD);
			$application_charge = $sc->call('GET', '/admin/api/2024-04/application_charges/'.$charge_id.'.json', array());
			$status = $application_charge['status'];
			$tempcode = GenCode(10);
			if($status == "active"){
				// activate
			  //	$response = $sc->call('POST', '/admin/application_charges/'.$charge_id.'/activate.json', $application_charge);
				$additionalSKUs = 0;
				if($plan == 1){
					$additionalSKUs = 500;
				} else if($plan == 2){
					$additionalSKUs = 2000;
				} else if($plan == 3){
					$additionalSKUs = 5000;
				}
				$conn->query("update users set membershiptype = 'paid', plan = ".$plan.", tempcode = '".$tempcode."', skulimit = (skulimit + ".$additionalSKUs."), paid_at = now() where id = ".$user_id);
				@mail("khariwal.rohit@gmail.com", "Shopify APP [Etsy] - New Payment Received", "User id - ".$user_id.', plan - '.$plan);
				$conn->query("insert into ipn_requests(status, type, user_id, created_at, updated_at) values('pending', 'fullsync_initial', ".mysqli_real_escape_string($conn, $user_id).", now(), now())");
			} else {
				$conn->query("update users set tempcode = '".$tempcode."' where id = ".$user_id);		
			}
			header("Location: https://apps.infoshoreapps.com/etsyimport/cp/#/login/".$tempcode);
		} catch (ShopifyApiException $e) {
			//print_r($e);
            // If you're here, either HTTP status code was >= 400 or response contained the key 'errors'
        }
	} else {
		if(!isset($_GET['key']) || !isset($_GET['type'])){
			die("Unauthorized Access!");
		}
		$tempcode  = 3198;
		$type =3;
        echo "select * from users where id = ".$tempcode;
		$result = $conn->query("select * from users where id = ".$tempcode);
		if($result->num_rows == 0){
			echo "hghdfkg";
			die("Unauthorized Access!");
		}
		$row = $result->fetch_assoc();
		$user_id = $row['id'];
		$shopurl = $row['shopurl'];
		$token = $row['token'];
		$discount = $row['discount'];
          echo "gjdflgdfg";
		$price = 14.95;
		$name = "Bronze Plan - Limited time offer";
		if($type == 1){
			$price = 14.95;
			$name = "Bronze Plan - Limited time offer";
		} else if($type == 2){
			$price = 24.95;
			$name = "Silver Plan - Limited time offer";
		} else if($type == 3) {
			$price = 39.95;
			$name = "Gold Plan - Limited time offer";
		}
		
		if($discount > 0){
			$price = $price - $price*$discount/100;
			$name = $name." - ".$discount."% Discount";
		}
		if($user_id == 3198 ){
			$uprice = 70;
			$name = "Gold Plan (Handle upto 6000 products)";
		}
		$rurl='https://php7crons.infoshore.biz/update1.php?type=3';
		$jsonStr = 'mutation {
			appSubscriptionCreate(
				name: "'.$name.'"
				returnUrl: "'.$rurl.'"
				lineItems: [
				{
					plan: {
						appRecurringPricingDetails: {
							price: { amount: '.$uprice.', currencyCode: USD }
							interval: ANNUAL
							
						}
					}
				}
				]
				test:true
			) {
			appSubscription {
				id
				
			}
			confirmationUrl
			userErrors {
				field
				message
			}
			}
		}';
		print_r( $jsonStr);
	 $re =	callShopifyGraphQL($shopurl, $token, $jsonStr);
	// }
	function callShopifyGraphQL($shopUrl, $accessToken, $query, $variables = []) {
		$ch = curl_init("https://$shopUrl/admin/api/2024-10/graphql.json");
		$payload = [
			'query' => $query
		];

		if (!empty($variables)) {
			$payload['variables'] = $variables;
		}

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			"Content-Type: application/json",
			"X-Shopify-Access-Token: $accessToken"
		]);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

		$response = curl_exec($ch);
  
		if (curl_errno($ch)) {
			$errorMsg = curl_error($ch);
			curl_close($ch);
			return [
				'error' => true,
				'message' => "cURL error: $errorMsg"
			];
		}

		curl_close($ch);
		print_r($response);
		$responseDecoded = json_decode($response, true);
		
		if (json_last_error() !== JSON_ERROR_NONE) {
			return [
				'error' => true,
				'message' => 'Invalid JSON response',
				'rawResponse' => $response
			];
		}
		return $responseDecoded;
	}
	function GenCode($size=10){
		global $conn;
		$code = '';
		$validchars = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
		mt_srand ((double) microtime() * 1000000);
		for ($i = 0; $i < $size; $i++) {
			$index = mt_rand(0, strlen($validchars));
			$code .= $validchars[$index];
		}
		$result = $conn->query("select * from users where tempcode = '".mysqli_real_escape_string($conn, $code)."'");
		if($result->num_rows > 0){
			return GenCode(10);
		}
		return $code;
	}
?>