<?php

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

    function checkEmailDomain($email) {
    // Allowed domains
    $not_allowed_domains = [
        '@bigcommerce.com',
        '@Webecommercepros.com',
        '@pgcjrw.edu.pk'
    ];

    // Extract domain from email
    $domain = substr(strrchr($email, "@"), 0); // Get @domain.com

    // Check if domain is in the allowed list (case insensitive)
    foreach ($not_allowed_domains  as $not_allowed) {
        if (strcasecmp($domain, $not_allowed) === 0) {
            return true;
        }
    }

    return false;
}

    $data = array(
    "table" => "stores",
    "where" => array(
        "is_created_on_klaviyo" => 0
               
            )
        );

    $all_users=$db->get($data);
    
    //print_r($all_users);
    
    
    $counter=1;
    
  

    foreach($all_users as $row)
    {
        $firstName=trim($row["admin_first_name"]);
        $Lastname=trim($row["admin_last_name"]);
        $adminEmail=strtolower(trim($row["admin_email"]));
        $storeHash=trim($row["store_id"]);

        $check_email=checkEmailDomain($adminEmail);

        if($check_email==false)
        {
            echo "email not exist in specific domain call the function<hr>$adminEmail<br>";
            
            create_klaviyo_profile($adminEmail,$firstName,$Lastname, $storeHash);

        }
        else{
            echo "email  exist in specific domain not call fun <hr>$adminEmail<br>";
            
              $store_update_data3=array();
                $store_update_data3['is_created_on_klaviyo']=3;
               
                
                $db->update( "stores", $store_update_data3, array("store_id" =>$storeHash));	
        }
        
        $counter++;
        
        /*if($counter==2)
        {
          exit();  
        }*/
        
        

    }

/*klaviyo function start*/
	
	function create_klaviyo_profile($email,$fname,$lname,$store_Hash)
    {
        echo "<hr><br>create_klaviyo_profile fun call for $email<hr><br>";
        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*/


?>