<?php
/*
 #########################################################################
 #                       xt:Commerce Shopsoftware
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 #
 # Copyright 2021 xt:Commerce GmbH All Rights Reserved.
 # This file may not be redistributed in whole or significant part.
 # Content of this file is Protected By International Copyright Laws.
 #
 # ~~~~~~ xt:Commerce Shopsoftware IS NOT FREE SOFTWARE ~~~~~~~
 #
 # https://www.xt-commerce.com
 #
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 #
 # @copyright xt:Commerce GmbH, www.xt-commerce.com
 #
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 #
 # xt:Commerce GmbH, Maximilianstrasse 9, 6020 Innsbruck
 #
 # office@xt-commerce.com
 #
 #########################################################################
 */

defined('_VALID_CALL') or die('Direct Access is not allowed.');

if (isset ($_POST['action']) || isset ($_GET['action'])) {

    global $page, $xtLink, $xtPlugin, $currency, $store_handler, $language, $info, $filter;

	$post_data = array();
	$post_data = $_POST;
	$get_data = array();
	$get_data = $_GET;
		
	$data_array = array_merge($post_data, $get_data);

	($plugin_code = $xtPlugin->PluginCode('form_handler.php:data_array_top')) ? eval($plugin_code) : false;

	switch ($data_array['action']) {

		case 'change_currency' :

            $code = $filter->_char($data_array['new_currency']);
			if($currency->_checkStore($code, $store_handler->shop_id)==true)
			    $_SESSION['selected_currency'] = $code;

			$link_array = array('page'=>$page->page_name, 'params'=>$xtLink->_getParams(array('action', 'new_currency')));
			if(isset($_POST['paction'])){
				$link_array['paction']=$_POST['paction'];
			}
            if (($page->page_name == 'checkout' || $page->page_name == 'customer' ) && _SYSTEM_SSL == true) {
                $link_array['conn']='SSL';
            }
            ($plugin_code = $xtPlugin->PluginCode('form_handler.php:change_currency_bottom')) ? eval($plugin_code) : false;
            $xtLink->_redirect($xtLink->_link($link_array));

		break;

		case 'add_product' :
			// für mgl iterationen in form_handler.php:add_product_top damit customers_discount form_handler.php:add_product_bottom greift
            $cart_product_group_discount_allowed = false;

			($plugin_code = $xtPlugin->PluginCode('form_handler.php:add_product_top')) ? eval($plugin_code) : false;

            // absicherung $data_array
            $data_array['product'] = (int)$data_array['product'];
            $data_array['gotoCart'] = (int)$data_array['gotoCart'];
            $data_array['qty'] = (float)$data_array['qty'];
            if($data_array['qty'] == (int)$data_array['qty']) $data_array['qty'] = (int)$data_array['qty'];
            if(empty($data_array['qty'])) $data_array['qty'] = 1;
            //negative quantity
            if($data_array['qty'] < 0){
                $data_array['qty'] = -$data_array['qty'];
            }

            $cart_product = sessionCart()->_addCart($data_array);
			if($cart_product)
			{
			    $info->_addInfoSession(sprintf(SUCCESS_PRODUCT_ADDED, $cart_product->data['products_name']),'success');

			    // für mgl iterationen in form_handler.php:add_product_top damit customers_discount form_handler.php:add_product_bottom greift
                if($cart_product_group_discount_allowed == 1) $cart_product->data['group_discount_allowed'] = 1;

                $_SESSION['cartChanged'] = true;
            }

            $link_array = array('page'=>'cart');
            if(array_key_exists('gotoCart', $data_array) && ($data_array['gotoCart'] == '0' || empty($data_array['gotoCart'])))
            {
                $link_array = array('page'=>$page->page_name, 'params'=>$xtLink->_getParams());
            }

            if($cart_product)
            {
                sessionCart()->_refresh();
            }
            ($plugin_code = $xtPlugin->PluginCode('form_handler.php:add_product_bottom')) ? eval($plugin_code) : false;
			$xtLink->_redirect($xtLink->_link($link_array));

		break;

		case 'update_product' :
			($plugin_code = $xtPlugin->PluginCode('form_handler.php:update_product_top')) ? eval($plugin_code) : false;

            $cartChanged = false;

            if(!is_data($data_array['cart_delete']))
                $data_array['cart_delete'] = array();

			for ($i = 0, $n = sizeof($data_array['cart_delete']); $i < $n; $i++) {
                if(array_key_exists($data_array['cart_delete'][$i], sessionCart()->content)) {
                    sessionCart()->_deleteContent($data_array['cart_delete'][$i]);
                    $cartChanged = true;
                }
			}

			if(!is_data($data_array['products_key']))
			$data_array['products_key'] = array();

			for ($i = 0, $n = sizeof($data_array['products_key']); $i < $n; $i++) {

					($plugin_code = $xtPlugin->PluginCode('form_handler.php:update_product_update')) ? eval($plugin_code) : false;

					if(!in_array($data_array['products_key'][$i], $data_array['cart_delete'])){
						$data = array('products_key'=>$data_array['products_key'][$i], 'qty'=>$data_array['qty'][$i]);
						if(array_key_exists($data['products_key'], sessionCart()->content))
                        {
                            sessionCart()->_updateCart($data);
                            $cartChanged = true;
                        }
					}

			}
            $_SESSION['cartChanged'] = $cartChanged;

			$link_array = array('page'=>$page->page_name);

            sessionCart()->_refresh();
            ($plugin_code = $xtPlugin->PluginCode('form_handler.php:update_product_bottom')) ? eval($plugin_code) : false;
			$xtLink->_redirect($xtLink->_link($link_array));

		break;

		case 'select_address' :
			($plugin_code = $xtPlugin->PluginCode('form_handler.php:select_address_top')) ? eval($plugin_code) : false;
			sessionCustomer()->_setAdress($data_array['adID'],$data_array['adType']);

			if($data_array['adType']=='payment')
			unset($_SESSION['selected_payment']);

			if($data_array['adType']=='shipping')
			unset($_SESSION['selected_shipping']);

			$link_array = array('page'=>$page->page_name, 'paction'=>$data_array['adType'], 'conn'=>'SSL');
			($plugin_code = $xtPlugin->PluginCode('form_handler.php:select_address_bottom')) ? eval($plugin_code) : false;
			$xtLink->_redirect($xtLink->_link($link_array));

		break;

        case 'repeat_order' :

            global $db;

            if(!$_SESSION['registered_customer'])
                $xtLink->_redirect($xtLink->_link(array('page'=>'customer', 'paction'=>'login')));

            $_GET['oid'] = (int)$_GET['oid'];
            $order = new order($_GET['oid']);

            $check_order = $order->_checkOrderId($_GET['oid']);

            if($check_order != true){
                $xtLink->_redirect($xtLink->_link(array('page'=>'customer')));
            }

            $missing_products = [];
            foreach($_REQUEST['orders_products_id'] as $key => $opid)
            {
                if (array_key_exists('rpo_add_product_'.$opid, $_REQUEST))
                {
                    $pid = $db->getOne('SELECT products_id FROM '.TABLE_ORDERS_PRODUCTS .' WHERE orders_products_id = ?', [$opid]);
                    $check_product_avail = product::getProduct($pid);
                    if(USER_POSITION == 'store' && !$check_product_avail || $check_product_avail->data['allow_add_cart']===false || $check_product_avail->is_product===false)
                    {
                        $missing_products[$opid] = $check_product_avail;
                        continue;
                    }

                    $data_array = [
                        'product' => $pid,
                        'qty' => $_REQUEST['qty'][$key],
                    ];

                    // für products_options
                    $order_product = [];
                    if ( isset($xtPlugin->active_modules['xt_product_options']) && defined('XT_PRODUCT_OPTIONS_ACTIVE') &&
                        (XT_PRODUCT_OPTIONS_ACTIVE == 1 || XT_PRODUCT_OPTIONS_ACTIVE == 'true'))
                    {
                        foreach ($order->order_products as $op) {
                            if ($op['orders_products_id'] == $opid) {
                                $order_product = $op;
                                break;
                            }
                        }

                        $products_data = unserialize($order_product["products_data"]);
                        $products_info[$pid] = $products_data['options'];
                        $data_array['products_info'] = $products_info;
                        $data_array['xt_po_exception'] = true;
                        // für products_options
                    }

                    // für mgl iterationen in form_handler.php:add_product_top damit customers_discount form_handler.php:add_product_bottom greift
                    $cart_product_group_discount_allowed = false;

                    try {
                        ($plugin_code = $xtPlugin->PluginCode('form_handler.php:add_product_top')) ? eval($plugin_code) : false;
                    }
                    catch(XtpoException $e) {
                        $tmp = new product(0);
                        $tmp->data = $order_product;
                        $missing_products[$opid] = $tmp;
                        continue;
                    }
                    //negative quantity
                    if ($data_array['qty'] < 0)
                    {
                        $data_array['qty'] = -$data_array['qty'];
                    }

                    $cart_product = sessionCart()->_addCart($data_array);
                    if ($cart_product)
                    {
                        $info->_addInfoSession(sprintf(SUCCESS_PRODUCT_ADDED, $cart_product->data['products_name'].' '.$order_product['products_model']), 'success');

                        // für mgl iterationen in form_handler.php:add_product_top damit customers_discount form_handler.php:add_product_bottom greift
                        if ($cart_product_group_discount_allowed == 1)
                        {
                            $cart_product->data['group_discount_allowed'] = 1;
                        }

                        $_SESSION['cartChanged'] = true;
                    }
                }
            }
            if(count($missing_products))
            {

                //$info->_addInfoSession(__text('ERROR_NOT_ALLOWED_TO_PURCHASE'),'error');
                $msg = __text('ERROR_NOT_ALLOWED_TO_PURCHASE').'<br />';
                foreach($missing_products as $opid => $missing_product)
                {
                    $msg .= $missing_product->data['products_name'].' ('.$missing_product->data['products_model'].') <br />';
                }
                $info->_addInfoSession($msg,'error');
            }

            $link_array = array('page'=>'customer', 'paction' => 'order_info', 'params'=>$xtLink->_getParams());

            ($plugin_code = $xtPlugin->PluginCode('form_handler.php:add_product_bottom')) ? eval($plugin_code) : false;
            $xtLink->_redirect($xtLink->_link($link_array));
            break;

		default:


	    ($plugin_code = $xtPlugin->PluginCode('form_handler.php:data_array_bottom')) ? eval($plugin_code) : false;
	}
}
