<?php

/**
 * Manage Stiore carts
 *
 * PHP version 5.6
 *
 * @category  Carts
 * @package   Store
 * @author    Debashri Bhakat <debashrib@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace CartStoreSpace\Controllers;

use ComponentStoreSpace\Controllers\StoreComponent;

/**
 * Store Carts Controller
 *
 * @category Carts
 * @package  Store
 * @author   Debashri Bhakat <debashrib@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */

class StoreCartsController extends StoreComponent
{
    /**
     * POST: Save Cart data
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   07 Jan 2020
     * @return json response wheather data is saved or any error occured
     */
    public function addToStoreCart($request, $response, $designID) 
    {
        $storeResponse = [];
        $cartParam = [];
        $directAddtocart = false;
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $action = (isset($allPostPutVars['action']) 
            && $allPostPutVars['action'] != '')
            ? $allPostPutVars['action'] : 'add';
        $cartItemId = (isset($allPostPutVars['cart_item_id']) 
            && $allPostPutVars['cart_item_id'] != '')
            ? $allPostPutVars['cart_item_id'] : 0;
        
        try {
            if(isset($allPostPutVars['store_id']) && $allPostPutVars['store_id'] != '') {
                $storeId = $allPostPutVars['store_id'];                
            } else {
                $storeId = 1;
            }
            $settingsPath = path('abs', 'setting') . 'stores/' . $storeId . "/settings.json";
            $deisgnStatePath = path('abs', 'design_state') . 'carts';
            $cartProduct = json_decode($allPostPutVars['product_data'], true);
            $url = "";

            //to add custom size or sheet name for banner and sticker product
            $designData = json_decode($allPostPutVars['design_data'], true);

            foreach ($cartProduct as $key => $cartData) {
                if ($cartData['is_variable_decoration'] == 1 && $cartData['is_sticker_product'] == 0) {
                    $cartProduct[$key]['custom_element'] = 'Banner size -' . $designData['design_product_data'][0]['variable_decoration_size'];
                } elseif ($cartData['is_variable_decoration'] == 1 && $cartData['is_sticker_product'] == 1) {
                    $sheetData =  $cartData['sheet_name'];
                    $cartProduct[$key]['custom_element'] = 'Sheets -' . $sheetData;
                } else {
                    $cartProduct[$key]['custom_element'] = 'default';
                }
            }

            if (file_exists($settingsPath)) {
                $fileContents = file_get_contents($settingsPath);
                $fileData = json_clean_decode($fileContents);
                $cartKey = !empty($fileData['cart']['shopify_cart_settings']) ? $fileData['cart']['shopify_cart_settings']['direct_add_to_cart'] : [];
                $directAddtocart = !empty($cartKey) ? $cartKey['is_enabled'] : false;
            }

            $isAddedPrice = array_column($cartProduct, 'added_price');
            $filteredValues = array_filter($isAddedPrice, function ($value) {
                return $value > 0;
            });
            
            //to get the default variant ID if both product and variant Id is same
            foreach ($cartProduct as $key => $cartData) {
                if ($cartData['variant_id'] == $cartData['product_id']) {
                    $variantId = $this->updateVariantId($cartData);
                    $cartProduct[$key]['variant_id'] = $variantId;
                }
            }

            if (!empty($filteredValues) && (!$directAddtocart)) {
            $cartParam = $this->createAddToCartLink($cartProduct, $designID);
            } else {
                foreach ($cartProduct as $cartData) {
                    if (($cartData['is_variable_decoration'] == 1) && ($cartData['is_sticker_product'] == 1)) {
                        $varDets = $this->getVariantDetails($cartData['variant_id']);
                        $varPrice = isset($varDets['price']) ? $varDets['price'] : 0;
                        $addedPrice = $cartData['added_price'] - $varPrice;
                    } else {
                        $addedPrice = $cartData['added_price'];
                    }
                    $cartParam[] = $designID . '-' . $cartData['variant_id'] . '-' . $cartData['qty'] . '-' . $cartData['variant_id'] . '||' . $addedPrice . '||' . $cartData['custom_element'];
                }
            }


            if (!empty($cartParam)) {
                $getShopDomain = $this->shopDomain();
                $thisShopDomain = !empty($getShopDomain['domain']) ? $getShopDomain['domain'] : SHOPIFY_SHOP . ".myshopify.com";
                $url = 'https://' . $thisShopDomain . '/cart?view=refitem&ref=' . implode('--', $cartParam);
            }
            if (isset($cartItemId) && $cartItemId != 0 && $action == 'update') {
                $url .= "&edit=" . $cartItemId;
            }
          
            if ($url != "") {
                $storeResponse = [
                    'status' => 1,
                    'message' => message('Cart', 'saved'),
                    'url' => $url,
                ];
            } else {
                $storeResponse = [
                    'status' => 0,
                    'message' => message('Cart', 'failed'),
                ];
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store',
                'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Product add to cart',
                    ],
                ]
            );
        }
        return $storeResponse;
    }

    private function createTempProduct($cartArr, $refid)
    {
        try {
            $productId = $cartArr['product_id'];
            $custom_price = $cartArr['added_price'];
            $is_variable_decoration = isset($cartArr['is_variable_decoration']) ? $cartArr['is_variable_decoration'] : 0;
            $cutom_design_refId = $refid;
            $quantity = $cartArr['qty'];
            $variantId = $cartArr['variant_id'];
            //$color1 = $cartArr['simple_product']['color1'];
            $xeColor = $cartArr['options']['Color'];
            $xeSize = $cartArr['options']['Size'];
            $product_data = array(
                "product_id" => $productId,
                "variant_id" => $variantId,
                "options" => array('xe_color' => $xeColor, 'xe_size' => $xeSize),
                "custom_price" => $custom_price,
                "is_variable_decoration" => $is_variable_decoration,
                "ref_id" => $refid,
                "qty" => $quantity,
            );
            // if ($custom_price > 0) {
            $result = $this->addCustomProduct($product_data);
            $product = array(
                "product_id" => $result['new_product_id'],
                "qty" => $quantity,
                "variant_id" => $result['new_variant_id'],
            );
            // }else{
            //  $product = array(
            //                "product_id" => $productId,
            //                "qty" => $quantity,
            //                "simpleproduct_id" => $variantId,
            //                "options"=>array('xe_color'=>$xeColor, 'xe_size'=>$xeSize),
            //                "custom_price" => $custom_price,
            //                "custom_design" => $cutom_design_refId,
            //        );
            // }
            return $product;
        } catch (\Exception $e) {
            $result = array('Caught exception:' => $e->getMessage());
            return $result;
        }
    }

    public function addImprintDataTOShop($thisProdData){
        return $this->addVariantToShopProd($thisProdData);
    }
    public function createCheckout($request, $response,$args){
        $allPostPutVars = $request->getParsedBody();
        $getPrice = json_decode($allPostPutVars['price'],true);
        $getCartData = json_decode($allPostPutVars['data'],true);
        $tierPriceCalculation = $this->tierPriceOfDuplicateProduct($getPrice,$getCartData);
        return $tierPriceCalculation;
    }
}
