<?php 
	error_reporting(E_ALL);
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	
	include 'inc/database.php';
	include 'requestFunctions.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*/

    $file_data = array();


	$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"],
	);

    $file_data["postfields"] = $data;
    
	$postfields = http_build_query($data);

	$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);
	// print_r($output);
	$obj = json_decode($output);
    $file_data["res_obj"] = $obj;
    
	$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);
	
	
	$API_PATH = 'https://api.bigcommerce.com/stores/'.$store['id'];
	$channel_url = $API_PATH."/v3/channels";
	
	$headers = array(
		"accept: application/json",
		"content-type: application/json",
		"x-auth-client: ".CLIENT_ID,
		"x-auth-token: ".$access_token
	);
	
	$file_data["header"] = $headers;
	
	$channel_data = curlGetRequest($channel_url, $headers);
	$file_data["channel_data"] = $channel_data;

	if($channel_data["data"]){
	    $file_data["in_channel_data_if"] = "yes";
		foreach ($channel_data["data"] as $key => $channel) {
			$file_data["in_channel_data_each"][$key] = "yes";
			
			$channel_id = $channel["id"];
			$channel_name = $channel["name"];
			if($channel["platform"] == "bigcommerce" && $channel["type"] == "storefront"){
			    
				$file_data["in_channel_data_each_if"][$key] = "yes";
				
				$url = $API_PATH."/v3/sites?channel_id:in=$channel_id";
				$result_site = curlGetRequest($url, $headers);
				
				$file_data["result_site"][$key] = $result_site;
				
				if($result_site["data"] && $result_site["data"][0]){
					$store_url = $result_site["data"][0]["url"];
				}  
				
				$store_data						= array();
				$store_data['access_token']		= $access_token;
				$store_data['store_id']			= $store['id'];
				$store_data['store_url']		= addslashes($store_url);
				$store_data['store_name']		= addslashes($channel_name);
				$store_data['channel_id']		= addslashes($channel_id);
				$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;
				
				$check = $db->getSingleColumn("stores", "attempt", array( "store_id" => $store['id'], "channel_id" => $channel_id) );
				if(!$check) {
					$store_data['created_at'] = date("Y-m-d H:i:s");
					$store_settings = $db->insert( "stores", $store_data );
				} else {
					$store_data['updated_at'] = date("Y-m-d H:i:s");
					$store_data['attempt']		= $check+1;
					$store_settings = $db->update( "stores", $store_data, array("store_id" => $store['id'], "channel_id" => $channel_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
				
				
				$file_data["query_data"][$key] = $store_data;
			}
			else{
			    $file_data["in_channel_data_each_else"][$key] = "yes";
			}
		}
	}
	else{
	    $file_data["in_channel_data_else"] = "yes";
	}
	
	$filename		= "logs/store_".time().".txt";
	file_put_contents($filename, print_r($file_data, true));
	chmod($filename, 0777);
	

	
	$URL=BASE_PATH."load.php?store_hash=".str_replace("stores/","", $_GET["context"])."";
	echo ("<script>location.href='$URL'</script>");
?>
