<?php
 $INC_DIR = $_SERVER['DOCUMENT_ROOT']."/v2/app/";
 include $INC_DIR."src/common.php";

$pages_path=[
    'dindex'=>['success'=>"{$configs->root_path}payment.php",'error'=>"{$configs->root_path}index.php"],
    'dcheckout'=>['success'=>"{$configs->root_path}upsell.php",'error'=>"{$configs->root_path}payment.php"],
    'dupsell'=>['success'=>"{$configs->root_path}confirmation.php",'error'=>"{$configs->root_path}confirmation.php"],
    'mindex'=>['success'=>"{$configs->mobile_path}qualify.php",'error'=>"{$configs->mobile_path}index.php"],
    'mqualify'=>['success'=>"{$configs->mobile_path}choose.php",'error'=>"{$configs->mobile_path}qualify.php"],
    'mshipping'=>['success'=>"{$configs->mobile_path}payment.php",'error'=>"{$configs->mobile_path}shipping.php"],
    'mcheckout'=>['success'=>"{$configs->root_path}upsell.php",'error'=>"{$configs->mobile_path}payment.php"],
    'mupsell'=>['success'=>"{$configs->root_path}confirmation.php",'error'=>"{$configs->root_path}confirmation.php"]
];

try{
    if((isset($pages_path[$_POST['pgtag']]))
    && (in_array($_POST['pgtag'],['dcheckout','dindex','mindex','mqualify','mshipping','mcheckout','dupsell','mupsell'])) 
    && !empty($_SESSION['s2_purchase_completed'])){
        $_POST['pgtag'] = str_replace(['index','qualify','shipping','checkout'],['upsell','upsell','upsell','upsell'],$_POST['pgtag']);
        $response['prospectId']=$_SESSION['prospectId'];
        $response['orderId']=$_SESSION['orderId'];
        $out = http_build_query($response);
    }elseif((isset($pages_path[$_POST['pgtag']]))
    && (in_array($_POST['pgtag'],['dcheckout','dindex','mindex','mqualify','mshipping','mcheckout'])) 
    && !empty($_SESSION['s1_purchase_completed'])){
        $_POST['pgtag'] = str_replace(['index','qualify','shipping'],['checkout','checkout','checkout'],$_POST['pgtag']);
        $response['prospectId']=$_SESSION['prospectId'];
        $response['orderId']=$_SESSION['orderId'];
        $out = http_build_query($response);
    }else{
        $out = create_customer($configs);
    }

    $exit_page=(isset($pages_path[$_POST['pgtag']]))?$pages_path[$_POST['pgtag']]['success']:"confirmation.php";

    $message=[
        'status'=>'success',
        'goTo'=>"$exit_page?$out",
        'success'=>true,
        'redirect'=>"$exit_page?$out"
    ];
}catch(Exception $e){
    $exit_page=(isset($pages_path[$_POST['pgtag']]))?$pages_path[$_POST['pgtag']]['error']:"confirmation.php";

    $message=[
        'status'=>'error',
        'message'=>$e->getMessage(),
        'goTo'=>"$exit_page?error=".$e->getMessage(),
        'success'=>true,
        'redirect'=>"$exit_page?error=".$e->getMessage()
    ];
}finally{
    $ajax = false;
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
        && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
            $ajax = true;
    }
    if($ajax)echo json_encode($message);
    else{
        header('Location: '.$message['goTo']);
        exit;
    }
}
?>