<?php 
	error_reporting(E_ALL & ~E_NOTICE);
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	
	include 'inc/database.php';
	global $conn;

	require_once __DIR__ . '/vendor/autoload.php';

	use Bigcommerce\Api\Client as Bigcommerce;
	
		/*klaviyo function start*/
	
	function create_klaviyo_profile($email,$fname,$lname,$store_Hash)
    {
        global $conn,$db;
    
        $curl = curl_init();
    
        curl_setopt_array($curl, [
            CURLOPT_URL => KLAVIYO_ENDPOINT.'profiles',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                 'Authorization: Klaviyo-API-Key ' . KLAVIYO_PRIVATE_KEY,
                'accept: application/vnd.api+json',
                'content-type: application/vnd.api+json',
                'revision: 2025-01-15',
            ],
            CURLOPT_POSTFIELDS => json_encode([
                'data' => [
                    'type' => 'profile',
                    'attributes' => [
                        'email' => $email,
                            'first_name' => $fname,
                            'last_name' => $lname
                        
                    ]
                ]
            ]),
        ]);
    
          /*  print_r([
                    'data' => [
                        'type' => 'profile',
                        'attributes' => [
                            'properties' => [
                                'email' => $email,
                                'first_name' => $fname,
                                'last_name' => $lname
                            ]
                        ]
                    ]
                ]);*/
    
    
            /*echo "<hr>";
                print_r([
                         'Authorization: Klaviyo-API-Key ' . KLAVIYO_PRIVATE_KEY,
                        'accept: application/vnd.api+json',
                        'content-type: application/vnd.api+json',
                        'revision: 2025-01-15',
                    ]);*/
    
        //exit();
    
        $k_response = curl_exec($curl);
    
        //echo "klaiyvo res:<hr>".$k_response;
    
        //echo "profile api end<hr>";
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
    
        curl_close($curl);
    
        if ($error) {
            echo "cURL Error: " . $error;
        } else {
            
               $store_update_data=array();
                $stmt = $db->prepare("UPDATE stores SET klaviyo_profile_api_res = ? WHERE store_id = ?");
                $stmt->bind_param("ss", $k_response, $store_Hash);
                $stmt->execute();
                $stmt->close();

            //echo "HTTP Code: " . $httpCode . "\n";
           // echo "Response: " .  $k_response;
    
            $klaviyo_res=json_decode($k_response,true);
           /* echo "<pre>";
            print_r($klaviyo_res);
            echo "</pre>";  */      
    
            // when first time profile create assign the profile to list
            if(isset($klaviyo_res["data"]["id"]))
            {
                //echo "first time id set";
                $k_profile_id=$klaviyo_res["data"]["id"];
                
                assign_profile_to_list($k_profile_id,$store_Hash);
    
            }
            else if(isset($klaviyo_res["errors"][0]["meta"]["duplicate_profile_id"]) && $httpCode===409){
    
                //echo "profile already created error";
    
                        // when  profile already create then we get the error message and in error we get already created profile id so get the id and assign it to list
                $k_profile_id=$klaviyo_res["errors"][0]["meta"]["duplicate_profile_id"];
                assign_profile_to_list($k_profile_id,$store_Hash);
    
            }
        }
    }
    
    function assign_profile_to_list($profile_id,$store_has)
    {
        global $conn,$db;
        $curl = curl_init();
    
        curl_setopt_array($curl, [
            CURLOPT_URL => KLAVIYO_ENDPOINT.'lists/'.KLAVIYO_LIST_ID.'/relationships/profiles',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                 'Authorization: Klaviyo-API-Key ' . KLAVIYO_PRIVATE_KEY,
                'accept: application/vnd.api+json',
                'content-type: application/vnd.api+json',
                'revision: 2025-01-15',
            ],
            CURLOPT_POSTFIELDS => json_encode([
                'data' => [
                    [
                        'type' => 'profile',
                        'id'=>$profile_id
                    ]
                ]
            ]),
        ]);
    
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
    
        curl_close($curl);
    
        if ($error) {
            echo "cURL Error: " . $error;
        } else {

                $stmt = $db->prepare("UPDATE stores SET klaviyo_list_api_res = ? WHERE store_id = ?");
                $stmt->bind_param("ss", $response, $store_has);
                $stmt->execute();
                $stmt->close();
                
           // echo "HTTP Code: " . $httpCode . "\n";
            //echo "Response: " . $response;
    
            if($httpCode===204)
            {
                $store_update_data1=array();
                $store_update_data1['is_created_on_klaviyo']=1;
               
                
                $db->update( "stores", $store_update_data1, array("store_id" =>$store_has));	
               // echo "profile assign to list ";
    
            }
        }
    }
	
	/*klaviyo function end*/

	$data = array(
	  "client_id" 		=> CLIENT_ID,
	  "client_secret" 	=> CLIENT_SECRET,
	  "redirect_uri" 	=> REDIRECT_URL,
	  "grant_type" 		=> GRANT_TYPE,
	  "code" 			=> $_GET["code"],
	  "scope" 			=> $_GET["scope"],
	  "context" 		=> $_GET["context"],
	);


	$postfields = http_build_query($data);
	
	$data["get"] = $_GET;
	$filename		= "logs/data_".time().".txt";
	file_put_contents($filename, print_r($data, true));
	chmod($filename, 0777);
	
	$ch = curl_init();                    
	$url = "https://login.bigcommerce.com/oauth2/token";
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$output = curl_exec ($ch);
	curl_close ($ch);

	$obj = json_decode($output);

	$access_token = $obj->access_token;

	Bigcommerce::configure(array(
		'client_id'  =>  CLIENT_ID,
		'auth_token' => $access_token,
		'store_hash' => str_replace("stores/","", $_GET["context"])
	));

	Bigcommerce::verifyPeer(false);
	
	// $ping = Bigcommerce::getTime();

	$store = (array)Bigcommerce::getConnection()->get(Bigcommerce::$api_path . '/store');	
	
	//print_r($store);
	$store_data						= array();
	$store_data['access_token']		= $access_token;
	$store_data['store_id']			= $store['id'];
	$store_data['store_url']		= addslashes($store['secure_url']);
	$store_data['store_name']		= preg_replace('/[^A-Za-z0-9\-]/', ' ', $store['name']);
	$store_data['admin_first_name']	= addslashes($store['first_name']);
	$store_data['admin_last_name']	= addslashes($store['last_name']);
	$store_data['country']			= $store['country'];
	$store_data['country_code']		= $store['country_code'];
	$store_data['phone']			= $store['phone'];
	$store_data['admin_email']		= $store['admin_email'];
	$store_data['currency']			= $store['currency'];
	$store_data['currency_symbol']	= $store['currency_symbol'];
	$store_data['stencil_enabled']	= $store['features']->stencil_enabled ? 1 : 0;
	$store_data['uninstall']		= 0;

	$filename		= "logs/app_installed_store_data".time().".txt";
	file_put_contents($filename, print_r($store_data, true));
	chmod($filename, 0777);
	
	$check = $db->getSingleColumn("stores", "attempt", array( "store_id" => $store['id']) );
	if(!$check) {
		$store_settings = $db->insert( "stores", $store_data );
		if($store['id'] != "1pzmyikofr")
		sendSGEmail($store_data['admin_email'],"Thank you for Installing Wishlist Analytics by Web Ecommerce Pros",$store_data['admin_first_name'],"Wishlist Analytics");
	} else {
		$store_data['attempt']		= $check+1;
		$store_settings = $db->update( "stores", $store_data, array("store_id" => $store['id']));	
	}
	
	// call the klaviyo function
				
		$is_created_on_klaviyo = $db->getSingleColumn("stores", "is_created_on_klaviyo", array( "store_id" => $store['id'], "is_created_on_klaviyo" =>0));
		
		if(!$is_created_on_klaviyo)
		{
		    // when profile not assign on klayviyo this conditon run only once when first time install
		    create_klaviyo_profile($store['admin_email'],$store['first_name'],$store['last_name'],$store['id']);
		    
		}
		
		// call the klaviyo function ENNNND
	
	$URL="https://wishlist.appsserver.net/bigcommerce_apps/wishlist/load.php?store_hash=".str_replace("stores/","", $_GET["context"])."";
	echo ("<script>location.href='$URL'</script>");
	
function sendSGEmail($email,$subject,$fname,$appName) {

	$url = 'https://api.sendgrid.com/v3/mail/send';
	//$user = 'bwoodall@revivalhome.com';
	//$pass = 'Rev2652656'; 
	$sgAPI = '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';
	
	/*$contentHTML = '<p style="font-family:Arial, Helvetica, sans-serif; font-size:13px">Hi '. $fname .',<br /><br />Thank you for installing '. $appName .', we hope you will enjoy using our app. My name is Ali Usman and I will be here to help you for any customization or issues you might have with the app.<br /><br />WebEcommercePros.com is a full-service ecommerce agency offering design, development, migration, marketing and SEO services. We are partnered with all major shopping cart platforms including Shopify, BigCommerce, 3dCart and Volusion.<br /><br />We also have some fantastic BigCommerce apps that are not listed on BigCommerce app store but you can have a look at them on the following link.<br />
	https://www.webecommercepros.com/shop<br /><br />Feel free to reply to this email if you have any questions, and I will be happy to help.<br /><br />I look forward to working with you.<br /><br />
	<strong style="font-size:16px; color:#3d85c6">Ali Usman</strong><br />
	Technical Account Manager / WebEcommercePros<br />
	<strong style="font-size:16px; color:#3d85c6">A:</strong> 1910 Thomes Avenue Cheyenne, WY<br />
	<strong style="font-size:16px; color:#3d85c6">P:</strong>  888.711.2347<br />
	<strong style="font-size:16px; color:#3d85c6">E:</strong> ali@webecommercepros.com<br />
	</p>';*/
    
	$contentHTML = '<p style="font-size:13px">Hi '. $fname .',<br /><br /></p><p>We sincerely appreciate your decision to install <strong>'.$appName.'</strong> and would like to extend a warm welcome to our platform. My name is Ali Usman, and I am pleased to introduce myself as your dedicated point of contact for any inquiries, customization requests, or concerns you may encounter while utilizing our application.</p><p>Since we are connected, I would like to take an opportunity to let you know that we are a full-service ecommerce agency, serving online merchants for over 17 years. Here are a few of our top selling services. Please contact us if you need any assistance right now or in future.</p><ol><li><strong>Theme Designing: </strong>Basic facelift to brand new custom theme.</li><li><strong>Custom Development: </strong>We have wide experience of building front-end Bigcommerce features as well API based solutions and apps.</li><li><strong>Ecommerce Migration: </strong>We are experienced and partner with all major shopping carts including but not limited to Bigcommerce, Shopify, Volusion and Shift4Shop. We offer migration services from one platform to another.</li><li><strong>Catalog Management: </strong>Some of our clients have a very large catalog (e.g.  from tools and equipment industry). They need help to manage their inventory on a day-to-day basis. So, we have a team who work with their suppliers and make sure the products are up to date.</li><li><strong>Ecommerce Maintenance: </strong> Some of our clients buy a bucket of hours and use our services for small routine tasks and we also keep eye on their website e.g., checking speed optimization and SEO audits and fixes etc.</li><li><strong>Ecommerce SEO </strong></li><li><strong>SMM </strong> Social Media Management</li><li><strong>Paid Advertising </strong> Google & Bing Ad & Shopping feed management</li></ol><p>We are pleased to introduce our exceptional collection of BigCommerce apps, available exclusively on our platform. Although not listed on the BigCommerce app store, these apps have been carefully designed to enhance your e-commerce experience.</p><p>To explore our offerings, please visit: <a href="https://www.webecommercepros.com/shop">https://www.webecommercepros.com/shop</a>.</p><p>Feel free to reply to this email if you have any questions, and I will be happy to help.</p><p>I look forward to working with you.</p><h2 style="color: #4F90CB; margin-bottom: 0">Ali Usman</h2><span>Technical Account Manager / WebEcommercePros</span><p style="margin: 5px 0"><span style="color: #4F90CB; font-size:16px; font-weight: bold;">A: </span> 1910 Thomes Avenue Cheyenne, WY</p><p style="margin: 5px 0"><span style="color: #4F90CB; font-size:16px; font-weight: bold;">P: </span><a href="tel:888.711.2347"> 888.711.2347</a></p><p style="margin: 5px 0"><span style="color: #4F90CB; font-size:16px; font-weight: bold;">E: </span> <a href="mailto:ali@webecommercepros.com"> ali@webecommercepros.com</a></p>';
	$params = array(
        "personalizations" => array(
            array(
                "to" => array(
                    array("email" => $email)
                ),
				"cc" => array(
                    array("email" => "billing@webecommercepros.com")
                ),
                "subject" => $subject
            ),
        ),
        "content" => array(
            array(
                "type" => "text/html",
                "value" => $contentHTML
            )
        ),
        "from" => array(
            "email" => "ali@webecommercepros.com",
            "name" => "Web Ecommerce Pros",
        ),

    );

	$curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.sendgrid.com/v3/mail/send",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($params),
    CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . $sgAPI,
    "Content-Type: application/json"
    ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    //return $response;
	
	//echo $response;

}
	
?>
