<?php
	require_once("includes/ohshopify/shopify.php");
	require_once("includes/config.php");
	require_once("includes/mandrill-api-php/src/Mandrill.php");
	require_once("includes/sendgrid/sendgridphp.php");


	// $conn = new mysqli($host, $username, $password, $dbname);

	// Check connection
	if ($conn->connect_error) {
		// TODO: Add some logging and email notification here
		die("Connection failed: " . $conn->connect_error);
	}
	mysqli_set_charset($conn, "utf8");

	if(isset($_GET['charge_id'])){
		try { 

			$charge_id = $_GET['charge_id'];
			$plan = $_GET['type'];
			$result = $conn->query("select u.id, u.shopurl,u.ownername 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'];
			$ownername = $row['ownername'];
			$email = $row['email'];

			// $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());
			$query = <<<QUERY
			query GetRecurringApplicationCharges {
				currentAppInstallation {
				activeSubscriptions {
					id
					name
					status
					lineItems {
					id
					plan {
						pricingDetails {
						__typename
						}
					}
					}
				}
				}
			}
			QUERY;

			$status = 'pending';
			$response= callShopifyGraphQL($shopurl, $token, $query);
			if ((isset($response['data']['currentAppInstallation']['activeSubscriptions'][0]['id']) && (!empty($response['data']['currentAppInstallation']['activeSubscriptions'][0]['id'])))) {
			print_r($response['data']['currentAppInstallation']['activeSubscriptions'][0]['id']);
			$shopifychargeidGID = $response['data']['currentAppInstallation']['activeSubscriptions'][0]['id'];

			$shopifychargeid = str_replace("gid://shopify/AppSubscription/", "",$shopifychargeidGID );
				if ($shopifychargeid == $charge_id) {
					 $status = $response['data']['currentAppInstallation']['activeSubscriptions'][0]['status'];
				}
			}
			// $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);
				send_mail($ownername,$email,$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 = trim($_GET['key']);
		$type = trim($_GET['type']);

		$result = $conn->query("select * from users where tempcode = '".mysqli_real_escape_string($conn, $tempcode)."'");
		if($result->num_rows == 0){
			die("Unauthorized Access!");
		}
		$row = $result->fetch_assoc();
		$user_id = $row['id'];
		$shopurl = $row['shopurl'];
		$token = $row['token'];
		$discount = $row['discount'];

		$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 == 2766 ){
			$uprice = 70;
			$name = "Gold Plan (Handle upto 6000 products)";
		}
		$sc = new ShopifyClient($shopurl, $token, SHOPIFY_API_KEY, SHOPIFY_API_PASSWORD);
		try {        
			// Create a new new charge
			$charge = array
				(
				"application_charge"=>array
				(
					"price"=>$price,
					"name"=>$name,
					"return_url"=>"https://apps.infoshoreapps.com/etsyimport/upgrade1.php?type=".$type,
					"test"=>false
				)
				);
			if($user_id == 5  || $user_id == 3198){
				// Create a new new charge
				$charge = array
				(
				"application_charge"=>array
				(
					"price"=>$price,
					"name"=>$name,
					"return_url"=>"https://apps.infoshoreapps.com/etsyimport/upgrade1.php?type=".$type,
					"test"=>false
				)
				);
			}
			try {
				$priceField = $charge['application_charge']['price']; 
				$nameField = $charge['application_charge']['name'];  
				$returnUrlField = $charge['application_charge']['return_url'];
				$testField = $charge['application_charge']['test'];
				$query = "
				mutation appPurchaseOneTimeCreate(\$name: String!, \$price: MoneyInput!, \$returnUrl: URL!, \$test: Boolean) {
				  appPurchaseOneTimeCreate(name: \$name, price: \$price, returnUrl: \$returnUrl, test: \$test) {
					appPurchaseOneTime {
					  status
					  id
					  test
					  createdAt
					}
					confirmationUrl
					userErrors {
					  field
					  message
					}
				  }
				}
				";
				$variables = [
					"name" => $nameField,
					"returnUrl" => $returnUrlField,
					"test"=> $testField,
					"price" => [
						"amount" => $priceField,
						"currencyCode" => "USD"
					]
				];
				
				
				$response = callShopifyGraphQL($shopurl, $token, $query, $variables);
				$api_client_id =str_replace("gid://shopify/AppPurchaseOneTime/", "",$response['data']['appPurchaseOneTimeCreate']['appPurchaseOneTime']['id']);

				$confirmationUrl = $response['data']['appPurchaseOneTimeCreate']['confirmationUrl'];
				$createdAt = $response['data']['appPurchaseOneTimeCreate']['appPurchaseOneTime']['createdAt'];

				$pattern = "/charges\/(\d+)\//";

				if (preg_match($pattern,$response['data']['appPurchaseOneTimeCreate']['confirmationUrl'] ,$matches)) {
					$chargeId = $matches[1]; 
					echo "Charge ID: " . $chargeId . PHP_EOL;
				} else {
					echo "Charge ID not found." . PHP_EOL;
				}

				$shopifychargeid = str_replace("gid://shopify/AppPurchaseOneTime/", "",$response['data']['appPurchaseOneTimeCreate']['appPurchaseOneTime']['id']);
					$status = $response['data']['appPurchaseOneTimeCreate']['appPurchaseOneTime']['status'];
					$status = strtolower($status);

				$pattern = "/charges\/(\d+)\//";


                // $application_charge = $sc->call('POST', '/admin/api/2024-04/application_charges.json', $charge);
				$conn->query("
				INSERT INTO chargerequest (
					user_id, charge_id, api_client_id, price, `status`, created_at, updated_at, response
				) VALUES (
					$user_id, 
					'".mysqli_real_escape_string($conn, $shopifychargeid)."', 
					'".mysqli_real_escape_string($conn, $api_client_id)."', 
					'".mysqli_real_escape_string($conn, $priceField)."', 
					'".mysqli_real_escape_string($conn, $status)."', 
					'".mysqli_real_escape_string($conn, $createdAt)."', 
					NOW(), 
					'".mysqli_real_escape_string($conn, serialize($response))."'
				)
			");			
				header("Location: ". $confirmationUrl);
			} catch (ShopifyApiException $e) {
				//print_r($e);
				// If you're here, either HTTP status code was >= 400 or response contained the key 'errors'
			}
		} catch (ShopifyApiException $e) {
			//print_r($e);
			/* 
				$e->getMethod() -> http method (GET, POST, PUT, DELETE)
				$e->getPath() -> path of failing request
				$e->getResponseHeaders() -> actually response headers from failing request
				$e->getResponse() -> curl response object
				$e->getParams() -> optional data that may have been passed that caused the failure
	        */
		} catch (ShopifyCurlException $e) {
			//print_r($e);
			// $e->getMessage() returns value of curl_errno() and $e->getCode() returns value of curl_ error()
		}
	}


	function send_mail($ownername,$to,$type){

		$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";
		}
		
		   $subject = "Plan Confirmation: $name";
		   
	
		   $body = "
		   <html>
		   <body>
			   <h2>Plan Confirmation</h2>
			   <p>Hi $ownername,</p>
			   <p>Thank you for choosing the <strong>$name</strong>.</p>
			   <p>The total cost is <strong>$price</strong>.</p>
			   <p>If you have any questions, feel free to contact us at support@yourdomain.com.</p>
			   <p>Best regards,</p>
			   <p>Your Company Name</p>
		   </body>
		   </html>
	   ";
	   
	   
	   $email = new \SendGrid\Mail\Mail(); 
	   $email->setFrom("shopifyapps@infoshore.biz", "Rohit from InfoshoreApps");
	   $email->setSubject($subject);
	   $email->addTo($to);
	   $email->addBcc("pankajnarang81@gmail.com");
	   $email->addBcc("khariwal.rohit@gmail.com");
	   $email->addCc('epihelp@infoshore.biz');
	   $email->addContent(
			"text/html", $body
			  );
	   $sendgrid = new \SendGrid('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');
	   try {
		   $response = $sendgrid->send($email);
		   return true;
	   } catch (Exception $e) {
		   return false;
	   }
	}

	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);

		$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;
	}
?>