<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Package extends CI_Controller
{
    /*
    * Konstruktor
    */
    function __construct()
    {
        parent::__construct();
        $this->TPL = array();
        $this->uri = $this->uri->uri_to_assoc();
    }
    
    /*
    * Stranka s nastavenim doplnku
    */
    function settings(){
        $settings = $this->package_model->init(); //inicializace
        $this->TPL["settings_json"] = json_decode($settings["settings"], true);
        $this->TPL["eshop_data"] = $this->package_model->process_eshop_data(json_decode($settings["eshop_data"], true));
        // Ulozeni nastaveni
        if($_POST["settings"]){
            $this->package_model->save_settings(["eshop_id" => $settings["eshop_id"], "settings" => json_encode($_POST["settings"])]);
            if($this->TPL["settings_json"]["split_set_products"] != $_POST["settings"]["split_set_products"] or $this->TPL["settings_json"]["xml_export_url"] != $_POST["settings"]["xml_export_url"]){
                if($_POST["settings"]["split_set_products"] and $_POST["settings"]["xml_export_url"]){
                    jenkins_trigger("shoptet__module-products-set", "BRANI_PRODUCT_SET_UPDATE", "ESHOP_ID=". $settings["eshop_id"]); // spusteni externiho skriptu pro aktualizaci polozek sad
                }
            }
            refresh();
        }
        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/settings', $this->TPL);
        $this->load->view('footer', $this->TPL);
    }
    /*
    * Vykresleni objednavek dle zadanych filtru
    */
    function list_items_part(){
        
        $settings = $this->package_model->init();//inicializace
        
        if(isset($this->uri["order"])){
            // hledani konkretni objednavky dle jejiho cisla
            $orders = $this->package_model->search_order($settings["eshop_id"], $this->uri["order"]);
        }else{
            // ziskani objednavek dle nastaveneho filtru s session
            $settings["saved_filters"] = json_decode($settings["saved_filters"], true);
            if(isset($_SESSION["filter"]) and isset($_SESSION["filter"][$settings["eshop_id"]])){
                if(is_array($_SESSION["filter"][$settings["eshop_id"]])){
                    $settings["filter"] = $_SESSION["filter"][$settings["eshop_id"]];
                }else{
                    $settings["current_filter"] = $_SESSION["filter"][$settings["eshop_id"]];
                    $settings["filter"] = $settings["saved_filters"][$_SESSION["filter"][$settings["eshop_id"]]]["filter"];
                }
                
            }else{
                $settings["filter"] = [];
            }
            
            $page = 0;
            if(isset($this->uri["page"])) $page = $this->uri["page"];
            
            if(!empty($settings["filter"])){
                $orders = $this->package_model->get_orders($settings["eshop_id"], $page, $settings["filter"]); // filtr je aktivni
            }else{
                $orders = $this->package_model->get_orders($settings["eshop_id"], $page); // filtr aktivni neni
            }
        }
        if(count($orders) == 0){
            return false;
        }
        
        $settings["settings"] = json_decode($settings["settings"], true);
        $this->TPL["settings"] = $settings;
        $this->TPL["orders"] = $orders;
        $this->TPL["package_filter"] = $settings["filter"];
        $this->TPL["eshop_translate"] = $this->package_model->process_eshop_data(json_decode($settings["eshop_data"], true), $settings["settings"]["show_pay_ship_type"]); //prevodnik dopravy, stavu z ID na jejich nazvy
        $this->load->view('tools/package/list_items', $this->TPL);
        
    }
    /*
    * Vraci text tlacitka dle poctu oznacenych objednavek
    */
    function list_main_button_text(){
        $selected_counter = $this->package_model->count_selected_orders($this->uri["eshop_id"]);
        switch ($selected_counter){
            case 1:
                echo "Zabalit 1 objednávku";
                break;
            case 2:
            case 3:
            case 4:
                echo "Zabalit ".$selected_counter." objednávky";
                break;
            default:
                echo "Zabalit ".$selected_counter." objednávek";
                break;
        }
    }


    /*
    * Vykresleni stranky se seznamem objenavek
    */
    function list()
    {
        $settings = $this->package_model->init(); //inicializace
        
        if(isset($_SESSION["package_filter"][$settings["eshop_id"]])) {
            $package_filter = $_SESSION["package_filter"][$settings["eshop_id"]];
        }
        
        $settings["settings"] = json_decode($settings["settings"], true);
        $settings["saved_filters"] = json_decode($settings["saved_filters"], true);
        $settings["filter"] = $_SESSION["filter"][$settings["eshop_id"]];
        $this->TPL["eshop_translate"] = $this->package_model->process_eshop_data(json_decode($settings["eshop_data"], true), $settings["settings"]["show_pay_ship_type"]);
        if(isset($this->uri["unselect_all"])){
            $this->package_model->unselect_all_orders($this->uri["eshop_id"]);
            redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
        }

        // nastaveni filtru
        if(isset($this->uri["set_filter"])){
            if($_SESSION["filter"][$settings["eshop_id"]] == $this->uri["set_filter"]){
                $_SESSION["filter"][$settings["eshop_id"]] = [];
                $settings["filter"] = [];
            }else{
                $_SESSION["filter"][$settings["eshop_id"]] = $this->uri["set_filter"];
                $settings["current_filter"] = $this->uri["set_filter"];
                $settings["filter"] = $settings["saved_filters"][$this->uri["set_filter"]]["filter"];
            }
            
            
            $this->TPL["package_filter"] = $settings["filter"];
            $this->TPL["settings"] = $settings;
            echo $this->load->view('tools/package/list_filter', $this->TPL, true);
            exit();
        }
        if(is_array($settings["filter"])){
            $this->TPL["package_filter"] = $settings["filter"];
        }else{
            $settings["current_filter"] = $settings["filter"];
            $settings["filter"] = $settings["saved_filters"][$settings["filter"]]["filter"];
            $this->TPL["package_filter"] = $settings["filter"];
        }

        $this->TPL["settings"] = $settings;
        $this->TPL["selected_counter"] = $this->package_model->count_selected_orders($this->uri["eshop_id"]);
        
        // zruseni aktivniho filtru
        if(isset($this->uri["unset_filters"])){
            $_SESSION["filter"][$settings["eshop_id"]] = [];
            redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
        }

        // ulozeni filtru
        if($_POST["package-filter-form"]){
            unset($_POST["package-filter-form"]);
            if(isset($_POST["filter_save"]) && $_POST["filter_save"]["delete"]){
                unset($settings["saved_filters"][$_POST["filter_save"]["delete"]]);
                $this->package_model->save_settings(["eshop_id" => $settings["eshop_id"], "saved_filters" => json_encode($settings["saved_filters"]), "filter" => "[]"]);
                exit();
            }
            if(isset($_POST["filter_save"]) && $_POST["filter_save"]["button_trigger"]){
                $filter_save = $_POST["filter_save"];
                unset($_POST["filter_save"]);
                if(!isset($filter_save["filter_id"])){
                    $filter_save["filter_id"] = md5($filter_save["filter_name"].$_POST.date("Y-m-d H:i:s"));
                }
                $settings["saved_filters"][$filter_save["filter_id"]] = ["name" => $filter_save["filter_name"], "filter" => $_POST];
                $_SESSION["filter"][$settings["eshop_id"]] = $filter_save["filter_id"];
                $this->package_model->save_settings(["eshop_id" => $settings["eshop_id"], "saved_filters" => json_encode($settings["saved_filters"])]);
            }else{
                unset($_POST["filter_save"]);
                $_SESSION["filter"][$settings["eshop_id"]] = $_POST;
            }
            exit();
        }
 
        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/list', $this->TPL);
        $this->load->view('footer', $this->TPL);
    }

    /*
    * Endpoint pro pridani objednavky na seznam pro baleni
    */
    function select_order(){
        if($_POST){
            if(isset($_POST["order_codes"])){
                $_POST["package_selected_number"] = json_decode($_POST["package_selected_number"],true);
                foreach (json_decode($_POST["order_codes"], true) as $code) {
                    $data = [
                            "package_eshop_id" => $_POST["eshop_id"],
                            "package_order_code" => $code,
                            "package_selected" => $_POST["selected"],
                            "package_selected_date" => date("Y-m-d H:i:s"),
                            "package_client_start" =>$this->client_model->current["client_id"],
                        ];
                    $this->dbe->on_duplicate_key_update("package_selected" , $data);
                    if($_POST["selected"] == "0"){
                        $this->package_model->del_all_package_selected_number(["eshop_id" => $_POST["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"][$code]]);
                    }
                }
            }else{
                $data = [
                        "package_eshop_id" => $_POST["eshop_id"],
                        "package_order_code" => $_POST["order_code"],
                        "package_selected" => $_POST["selected"],
                        "package_selected_date" => date("Y-m-d H:i:s"),
                        "package_client_start" =>$this->client_model->current["client_id"],
                    ];
                $this->dbe->on_duplicate_key_update("package_selected" , $data);
                if($_POST["selected"] == "0"){
                    $this->package_model->del_all_package_selected_number(["eshop_id" => $_POST["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"]]);
                }
            }
        }
    }

    /*
    * Vykresleni stranky se seznamem produktu potrebnych pro vybrane objednavky
    */
    function picking_list(){
        // pokud jde o pristup primo z IS
        if($this->uri["eshop_id"]){
            $settings = $this->package_model->init(); //inicializace
            $this->TPL["client_id"] = $this->client_model->current["client_id"];
        }else{
            // pokud jde o pistup pres hash, neni potreba prihlaseni
            if($this->uri["h"]){
                $settings = $this->package_model->get_settings(["hash" => $this->uri["h"]]);
                if(count($settings) != 1) redirect("/");
                $settings = $settings[0];
                $this->uri["eshop_id"] = $settings["eshop_id"];
                $this->TPL["client_id"] = $this->uri["c"];
            }
        }
        $settings["eshop_data"] = json_decode($settings["eshop_data"], true);
        $this->TPL["image_prefix"] = "";
        foreach ($settings["eshop_data"]["data"]["imageCuts"] as $img_cut) {
            $this->TPL["image_prefix"] =  $img_cut["urlPath"];
            break;
        }

        // pokud chceme jen prvni, aktivni produkt, tak se vykresli jen ten. Vyuziva se pro AJAX nacteni noveho aktivniho produktu
        if(isset($this->uri["active_item"])){

            $selected_orders = $this->package_model->get_selected_orders($settings["eshop_id"], $this->TPL["client_id"]);
            $picking_items = $this->package_model->get_picking_list($settings["eshop_id"], $selected_orders, $this->uri["active_item"], json_decode($settings["settings"], true)["split_set_products"]);
            $ITEM_DATA["package_selected_number"] = $this->package_model->transform_package_selected_number($this->package_model->get_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->TPL["client_id"]]));

            $ITEM_DATA["c"] = $this->uri["active_item"];
            $ITEM_DATA["i"] = $picking_items[$ITEM_DATA["c"]];
            $ITEM_DATA["image_prefix"] = $this->TPL["image_prefix"];

            echo $this->load->view('tools/package/picking_list_active_item', $ITEM_DATA, true);
            exit();
        }
        

        $this->TPL["selected_counter"] = $this->package_model->count_selected_orders($this->uri["eshop_id"]);
        $this->TPL["settings"] = $settings;
        // aktualizovat cisla krabcia a nacist oznacene objednavky
        $this->package_model->reload_selected_numbers($settings["eshop_id"], $this->TPL["client_id"]);
        $selected_orders = $this->package_model->get_selected_orders($settings["eshop_id"], $this->TPL["client_id"]);
        
        // z vybranych objednavek vygenerovat seznam potrebnych produktu
        $this->TPL["picking_items"] = $this->package_model->get_picking_list($settings["eshop_id"], $selected_orders, False, json_decode($settings["settings"], true)["split_set_products"]);
        uasort($this->TPL["picking_items"], function ($a, $b) {
            if($a["stock_location"] == "") return 0;
            return -strcmp($a["stock_location"], $b["stock_location"]);
        });
        $this->TPL["package_selected_number"] = $this->package_model->transform_package_selected_number($this->package_model->get_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->TPL["client_id"]]));


        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/picking_list', $this->TPL);
        $this->load->view('footer', $this->TPL);

    }


    /*
    * Nacteni chybejicich produktu v picking listu
    */
    function ajax_get_package_selected_number(){
        $settings = $this->package_model->init();
        $selected_orders = $this->package_model->get_selected_orders($this->uri["eshop_id"], $this->client_model->current["client_id"]);
        $picking_items = $this->package_model->get_picking_list($this->uri["eshop_id"], $selected_orders, False, json_decode($settings["settings"], true)["split_set_products"]);
        $package_selected_number = $this->package_model->transform_package_selected_number($this->package_model->get_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"]]));
        $result = [];
        foreach ($picking_items as $code => $item) {
            foreach ($item["package_selected_numbers"] as $num => $amount) {
                if(isset($package_selected_number[$code][$num])){
                    $amount -= $package_selected_number[$code][$num];
                }
                if(!isset($result[$code])) $result[$code] = [];
                for ($x = 1; $x <= $amount; $x++) {
                    $result[$code][] = $num;
                }
            }
            sort($result[$code]);
        }
        
        echo json_encode($result);
    }

    /*
    * Produkt v picking listu byl naksenovan. Kompletovat tento produkt v picking listu
    */ 
    function ajax_package_selected_number(){
        if(!isset($this->uri["eshop_id"])) return;
        if($_POST["code"]){

            if($_POST["add"] && $_POST["add"] == "1"){
                $this->package_model->add_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"], "code" => $_POST["code"] ]);
            }elseif($_POST["minus"] && $_POST["minus"] == "1"){
                $this->package_model->del_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"], "code" => $_POST["code"] ]);
            }elseif($_POST["all_add"]){
                for ($i=0; $i < $_POST["all_add"]; $i++) { 
                    $this->package_model->add_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"], "code" => $_POST["code"] ]);
                }
            }elseif ($_POST["all_minus"]) {
                for ($i=0; $i < $_POST["all_minus"]; $i++) { 
                     $this->package_model->del_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $_POST["package_selected_number"], "code" => $_POST["code"] ]);
                }
            }
        
            $package_selected_number = $this->package_model->transform_package_selected_number($this->package_model->get_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->TPL["client_id"]]));
            if(!isset($package_selected_number[$_POST["code"]][$_POST["package_selected_number"]])) $package_selected_number[$_POST["code"]][$_POST["package_selected_number"]] = 0;
            
            echo $this->package_model->get_package_selected_number_amount_text($package_selected_number[$_POST["code"]][$_POST["package_selected_number"]], $_POST["total_amount"]);
        }
    }
    
    /*
    * Vykresleni stranky pro kompletaci objednavky
    */
    function packaging(){
        $settings = $this->package_model->init(); // inicializace
        $settings["settings"] = json_decode($settings["settings"], true);
        $settings["eshop_data"] = json_decode($settings["eshop_data"], true);
        $this->TPL["settings"] = $settings;

        // Bylo zvoleno zrusit baleni vsech objednavek
        if($this->uri["cps"]){
            $this->package_model->clean_packed_selected_order($this->uri["eshop_id"]);
        }
        
        $this->TPL["image_prefix"] = "";
        foreach ($settings["eshop_data"]["data"]["imageCuts"] as $img_cut) {
            $this->TPL["image_prefix"] =  $img_cut["urlPath"];
            break;
        }
        // resetovat zabaleni objednavky
        if(isset($this->uri["reset"])){
            $this->package_model->update_selected_order([
                                                        "package_eshop_id" => $this->uri["eshop_id"],
                                                        "package_order_code" =>$this->uri["reset"],
                                                        "package_packed_selected" => "0",
                                                        "package_packed_date" => "NULL",
                                                        "package_client_end" => "0",
                                                    ]);
            redirect(str_replace("/reset/".$this->uri["reset"], "",$_SERVER['REQUEST_URI']));
            
        }

        //provedeni akce
        if(isset($this->uri["do_action"])){
            if($this->uri["do_action"] == "cancel_packaging") {
                $data = [
                    "package_eshop_id" => $this->uri["eshop_id"],
                    "package_order_code" => $this->uri["order"],
                    "package_selected" => "0",
                ];
                $this->dbe->on_duplicate_key_update("package_selected" , $data);
            }else{
                $this->package_model->do_action($this->uri["eshop_id"], $settings["settings"][$this->uri["do_action"]], $this->uri["order"]);
            }
            
            $next_page = $this->package_model->is_all_selected_packed($this->uri["eshop_id"]);
            if($next_page === False){
                redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
            }else{
                redirect("package/packaging/eshop_id/".$this->uri["eshop_id"]."/r/".$next_page);
            }
        }

        
        // nacteni konkretni objednavky
        if(isset($this->uri["order"])){
            $this->dbe->on_duplicate_key_update("package_selected" ,
                ["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $this->uri["order"]],
                ["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $this->uri["order"], "package_client_start" =>$this->client_model->current["client_id"]]);
            $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"]);
        }else{
            // nacteni objednavky dle poradi
            if(!isset($this->uri["r"])) $this->uri["r"] = 0;
            $order = $this->package_model->get_selected_orders_by_row($this->uri["eshop_id"], $this->uri["r"]);
            $_SESSION["packaging_last_page"] = $this->uri["r"];
        }
        if(!empty($order)) $order = $order[0];
        elseif(!isset($this->uri["packed"])) redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
        
        // objednavka byla zabalena
        if(isset($this->uri["packed"])){
            $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["packed"]);
            if(!empty($order)) $order = $order[0];
            $this->package_model->del_all_package_selected_number(["eshop_id" => $this->uri["eshop_id"], "client_id" => $this->client_model->current["client_id"], "package_selected_number" => $order["package_selected_number"]]);
    
    
            if(isset($settings["settings"]["balikobot_switch"]) && ($settings["settings"]["balikobot_switch"] == "only_print" || $settings["settings"]["balikobot_switch"] == "generate_print")){
                // má se tisknout a generovat stitek
                redirect("package/print_package_label/eshop_id/".$this->uri["eshop_id"]."/order/".$order["order_code"]);
            }else{
                // stitek se netiskne
                $this->package_model->update_selected_order([
                                                        "package_eshop_id" => $this->uri["eshop_id"],
                                                        "package_order_code" =>$this->uri["packed"],
                                                        "package_packed_date" => "NOW()",
                                                        "package_selected" => "0",
                                                        "package_packed_selected" => $this->client_model->current["client_id"],
                                                        "package_client_end" => $this->client_model->current["client_id"],
                                                        ]);
                $this->package_model->do_action($this->uri["eshop_id"], $settings["settings"]["packaging_finish_actions"], $this->uri["packed"]);

                // prechod na dalsi objednavku nebo na seznam vsechn objednavek
                $next_page = $this->package_model->is_all_selected_packed($this->uri["eshop_id"]);
                if($next_page === False){
                    redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
                }else{
                    redirect("package/packaging/eshop_id/".$this->uri["eshop_id"]."/r/".$next_page);
                }
            }
          
        }
        
        $order["package_client_start"] = $this->client_model->get_client(["client_id" => $order["package_client_start"]]);
        $order["package_client_end"] = $this->client_model->get_client(["client_id" => $order["package_client_end"]]);
    
        $order["data"] = json_decode($order["data"], true);
        $order_items_json = [];
        $order_packed_json = [];
        $order_items_ean_to_code = [];

        // rozdeleni sad na polozky sady, pokud je to takto nastaveno
        if($settings["settings"]["split_set_products"]){
            foreach($order["data"]["items"] as $index => $item){
                if($item["code"] == "") continue;

                if($item["itemType"] == "product-set"){
                    $shoptet_product = $this->eshop_module_products_model->get_products(["eshop_id" => $eshop_id, "product_guid" => $item["productGuid"]]);
                    if(empty($shoptet_product)) continue;
                    $shoptet_product = $shoptet_product[0];
                    if(!$shoptet_product["data_set"]) continue;

                    $set_items = json_decode($shoptet_product["data_set"], true);
                    foreach ($set_items as $sitem) {
                        $new_item = $item;
                        $new_item["code"] = $sitem["code"];
                        $new_item["productGuid"] = $sitem["guid"];
                        $new_item["amount"] = $sitem["amount"]*$item["amount"];
                        $new_item["itemType"] = "product-from-set";
                        
                        $order["data"]["items"][] = $new_item;
                    }
                    unset($order["data"]["items"][$index]);
                }
            }
        }

        // nacteni potrebnych dat o produktech k polozkam objednavky
        foreach($order["data"]["items"] as $index => $item){
            if(!$item["code"]) continue;
            if($item["productGuid"]) $shoptet_product = $this->eshop_module_products_model->get_products(["eshop_id" => $this->uri["eshop_id"], "product_guid" => $item["productGuid"]]);
            else $shoptet_product = [];
            
            if(!empty($shoptet_product)){
                $shoptet_product = $shoptet_product[0];
                $shoptet_product["data"] = json_decode($shoptet_product["data"],true);
                foreach ($shoptet_product["data"]["variants"] as $vk => $vv) {
                    if($vv["code"] != $item["code"]) unset($shoptet_product["data"]["variants"][$k]);
                }
                $order["data"]["items"][$index]["product_detail"] = $shoptet_product;
                if($item["itemType"] == "product-from-set"){
                    $order["data"]["items"][$index]["name"] = $shoptet_product["data"]["name"];
                    $order["data"]["items"][$index]["variantName"] = $shoptet_product["data"]["variants"][0]["name"];
                    
                }
            }
            $order["data"]["items"][$index]["packed"] = $this->package_model->get_packed_items(["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $order["order_code"], "package_item_code" => $item["code"]]);
            $order_items_json[$item["code"]] = $item["amount"];
            if(!empty($order["data"]["items"][$index]["product_detail"]["data"]["variants"]) && $order["data"]["items"][$index]["product_detail"]["data"]["variants"][0]["ean"] ){
                $order_items_ean_to_code[$order["data"]["items"][$index]["product_detail"]["data"]["variants"][0]["ean"]] = $item["code"];
            }
        
            $order_packed_json[$item["code"]] = count($order["data"]["items"][$index]["packed"]);
        }
    
        $this->TPL["order"] = $order;
        $this->TPL["order_items_json"] = json_encode($order_items_json);
        $this->TPL["order_packed_json"] = json_encode($order_packed_json);
        $this->TPL["order_items_ean_to_code"] = json_encode($order_items_ean_to_code);
        $this->TPL["selected_counter"] = $this->package_model->count_selected_orders($this->uri["eshop_id"]) + $this->package_model->count_packed_selected_orders($this->uri["eshop_id"]);
        $this->TPL["eshop_translate"] = $this->package_model->process_eshop_data($settings["eshop_data"], $settings["settings"]["show_pay_ship_type"]);
        $this->TPL["country_codes"] = $this->config->item('states_and_codes_full');
     
        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/packaging', $this->TPL);
        $this->load->view('footer', $this->TPL);
        
    }
    // volani pro ulozeni poznamky do shoptetu
    function ajax_save_remark(){
        $settings = $this->package_model->init();
        
        if($_POST["eshop_remark"]){
            $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"]);
            if(!empty($order)) $order = $order[0];
            $order["data"] = json_decode($order["data"], true);
            $order["data"]["notes"]["eshopRemark"] = $_POST["eshop_remark"];
            $order["data"] = json_encode($order["data"]);
            $this->eshop_module_orders_model->add_or_update_orders(["eshop_id" => $this->uri["eshop_id"], "order_code" => $this->uri["order"], "data" =>  $order["data"] ]);
            $eshop_module = $this->shoptet_model->get_shoptet_module_for_api_call($this->uri["eshop_id"], "package-filter"); // ziskani potrebnych dat (tokenu) pro volani API
            $this->shoptet_model->set_order_eshop_remark($eshop_module,$this->uri["order"], $_POST["eshop_remark"]); // ulozeni poznamky do shoptetu pomocí jejich API
        }
    }

    // kompletace produktu v objednavce
    function ajax_add_packed(){
        $settings = $this->package_model->init();
        
        if($_POST["item_code"]){
            // zsikani dane objednavky a nalezeni produktu
            $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"])[0];
            $order["data"] = json_decode($order["data"], true);

            if($_POST["item_guid"] === NULL) {
                foreach($order["data"]["items"] as $index => $item){
                    if($item["code"] == $_POST["item_code"]){
                        $_POST["item_guid"] = $item["productGuid"];
                    }
                }
            }
            // zkompletovat dany pocet
            if($_POST["all_add"]){
                for ($i=0; $i < $_POST["all_add"]; $i++) { 
                    $result["id"] = $this->package_model->add_packed_item($this->uri["eshop_id"], $this->uri["order"], $_POST["item_code"], $_POST["item_guid"]);
                }
                
            }elseif ($_POST["all_minus"]) {
                for ($i=0; $i < $_POST["all_minus"]; $i++) { 
                    $this->package_model->rm_packed_item($this->uri["eshop_id"], $this->uri["order"], $_POST["item_code"]);
                }
            }else{
                if($_POST["minus"]){
                     $this->package_model->rm_packed_item($this->uri["eshop_id"], $this->uri["order"], $_POST["item_code"]);
                }else{
                     $result["id"] = $this->package_model->add_packed_item($this->uri["eshop_id"], $this->uri["order"], $_POST["item_code"], $_POST["item_guid"]);
                }
            }
            $result["html"] = "";

           
            
            // vygenerovani pocitadla kompleace pro stranku s kompletaci
            foreach($order["data"]["items"] as $index => $item){
                if($item["code"] == $_POST["item_code"]){

                    $order["data"]["items"][$index]["packed"] = $this->package_model->get_packed_items(["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $order["order_code"], "package_item_code" => $item["code"]]);
                    $this->TPL["i"] = $order["data"]["items"][$index];
                    $result["html"] = $this->load->view('tools/package/packaging_counter', $this->TPL, true);
                    echo json_encode($result);
                    exit();
                }else{
                    continue;
                }
            }
        }
        echo "false";
        
    }

    // kontrola zda je objednavka zkompletovana nebo ne
    function ajax_completed_packed_check(){
        $settings = $this->package_model->init();
        $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"])[0];
        $order["data"] = json_decode($order["data"], true);
        $result_flag = "true";
        foreach($order["data"]["items"] as $index => $item){
            if($order["order_code"] != ""){
                $packed = $this->package_model->get_packed_items(["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $order["order_code"], "package_item_code" => $item["code"]]);
                if(count($packed) < floatval($item["amount"])){
                    $result_flag = "false";
                    echo $result_flag;
                    return;
                } 
            }
            
        }   
        echo $result_flag;
        return;
    }
    
    // aktualizace kompletace v detailu baleni objednavky
    function ajax_reload_packed(){
        $settings = $this->package_model->init();
        
        if($_POST["item_code"]){
            $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"]);
            $order["data"] = json_decode($order["data"], true);
            foreach($order["data"]["items"] as $index => $item){
                if($item["code"] == $_POST["item_code"]){
                    $order["data"]["items"][$index]["packed"] = $this->package_model->get_packed_items(["package_eshop_id" => $this->uri["eshop_id"], "package_order_code" => $order["order_code"], "package_item_code" => $item["code"]]);
                    $this->load->view('tools/package/packaging_counter', ["i" => $order["data"]["items"][$index]]);
                    exit();
                }else{
                    continue; 
                } 
            }
        }
        echo "false";
    }

    // ulozeni fotografie porizene z webkamery pri baleni
    function ajax_save_photo(){
        if($_POST){
            //nacteni metadat o fotografii
            $eshop_id = $this->uri["eshop_id"];
            $order_code = $this->uri["order"];
            $photo_type = $this->uri["type"];
            $custom_id = $this->uri["custom_id"];
            $client_id = $this->client_model->current["client_id"];

            $data = $_POST["base64"]; // fotografie je zde prijata ve formatu base64
            list($type, $data) = explode(';', $data);
            list(, $data)      = explode(',', $data);
            $data = base64_decode($data); // nasledne je dekodovana
            $tmpfname = tempnam("./img_tmp", "BALIC"); // ulozena jako tempomary file
            $handle = fopen($tmpfname, "w"); 
            fwrite($handle, $data);
            fclose($handle);
            $photo_url = md5($eshop_id)."/".md5($photo_type.$order_code.strtotime("now").rand(0,100)).".jpg"; //vygenerovani URL pro danou fotografii
            $this->digital_ocean_model->save_image("./img_tmp/".end(explode("/", $tmpfname)), $photo_url); // jeji ulozeni na digital ocean uloziste
            unlink($tmpfname); // odstraneni tempomary file
            $this->package_model->add_package_photo(["eshop_id" => $eshop_id, "order_code" => $order_code, "package_photo_type" => $photo_type, "package_photo_custom_id" => $custom_id, "package_photo_url" => $photo_url]); // ulozeni URL adresy a jejich atributu do DB

        }
    }
    
    // Nacteni PDF stitku a jeho naservirovani pro tisk
    function load_pdf(){

       header("Content-type:application/pdf");
        $pdf = file_get_contents($_GET["b"]);
        echo $pdf;
    }

    // Stranka zajistující tisk stitku
    function print_package_label(){
        
        if(!isset($this->uri["eshop_id"]) || !isset($this->uri["order"])){
            die("parameters missing.");
        }
        $settings = $this->package_model->init();

        $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"])[0];
        $order["data"] = json_decode($order["data"], true);
        $settings["settings"] = json_decode($settings["settings"], true);

        $total_weight = 0;
         
        foreach ($order["data"]["items"] as $item) {

            $total_weight += $item["weight"]*$item["amount"];
        }

        $order_url_id = end(explode( "?id=", $order["data"]["adminUrl"]));
        
        $shipping_guid = $order["data"]["shipping"]["guid"];

        if(!isset($settings["settings"]["balikobot_types"][$shipping_guid])) die("Není definována přepravní společnost v balíkobotu");
        if(!isset($settings["settings"]["balikobot_services"][$shipping_guid])) die("Není definována konkrétní typ přepravy u této společnost v balíkobotu");
        $shipping_company = $settings["settings"]["balikobot_types"][$shipping_guid];
        $shipping_service = $settings["settings"]["balikobot_services"][$shipping_guid];
        if($order["data"]["addressesEqual"] == "1"){
            $addr = $order["data"]["billingAddress"];

        }else{
            $addr = $order["data"]["deliveryAddress"];
        }

        //TODO - jak poznat dobirku?
        if($order["paymentMethod"]["name"] == "Dobírkou"){
            $cod_price = $order["price"]["toPay"];
        }else{
            $cod_price = 0;
        }
   
        
        if(!isset($settings["settings"]["balikobot_switch"]) || $settings["settings"]["balikobot_switch"] == "only_print"){
            // tisknou se stitky, ktere byly v balikobotu vygenerovany pres Shoptet
            $rs = $this->balikobot_model->find_package($settings["settings"]["balikobot_user"].":".$settings["settings"]["balikobot_key"], $shipping_company, $settings["eshopId"]."-".$order_url_id);
            if(!isset($rs["label_url"])){
                 $this->TPL["error_msg"] = "Štítek nebyl nalezen. Zkontrolujte zda jste pro tuto objednávku šítek vygenerovali.";
                 $this->log_model->add(["level" => "ERROR", "service" => "package", "message_short" => $this->uri["order"]." - ".$this->TPL["error_msg"],"message_long" => json_encode($rs), "message_private" => $settings["eshopId"]."-".$order_url_id]);
            }else{
                $this->TPL["label_url"] = $rs["label_url"];
            }
            
            
        }else{
            // generuji se stitky v balikobotu dle nastavene dopravy atd...
            $branch_id = NULL;
            $service_type = NULL;
            if(isset($order["data"]["shippingDetails"]) && isset($order["data"]["shippingDetails"]["branchId"])) $branch_id = $order["data"]["shippingDetails"]["branchId"];
            if($shipping_company == "zasilkovna" && $shipping_service != "zasilkovna") $branch_id = $shipping_service; // zasilkovna potrebuje branch_id
            if($shipping_company != "zasilkovna") $service_type = $shipping_service;

            $data = [
                'eid' => $settings["eshopId"]."-".$order_url_id,
                'vs' => $order["data"]["code"],
                'rec_country' => $addr["countryCode"],
                'cod_currency' => $order["data"]["price"]["currencyCode"],
                'cod_price' => $cod_price,
                'price' => $order["data"]["price"]["withVat"],
                'rec_phone' => $order["data"]["phone"],
                'rec_name' => $addr["fullName"],
                'rec_street' => $addr["street"]." ".$addr["houseNumber"],
                'rec_city' => $addr["city"],
                'rec_email' => $order["data"]["email"],
                'rec_zip' => $addr["zip"],
                'del_evening' => true,
                "weight" => $total_weight,
            ];
            if($branch_id !== NULL) $data["branch_id"] = $branch_id;
            if($service_type !== NULL) $data["service_type"] = $service_type;

            $rs = $this->balikobot_model->add_package($settings["settings"]["balikobot_user"].":".$settings["settings"]["balikobot_key"], $shipping_company, [$data]);

            if(isset($rs["label_url"])){
                $this->TPL["label_url"] = $rs["label_url"];
                $this->package_model->update_selected_order([
                                                "package_eshop_id" => $this->uri["eshop_id"],
                                                "package_order_code" =>$this->uri["order"],
                                                "package_order_carrier_id" => $rs["carrier_id"],
                                                ]);
            }else{
                $this->TPL["error_msg"] = "Objednávka se neodeslala do Balíkobotu a štítek nebyl vytvořen!";
                $this->log_model->add(["level" => "ERROR", "service" => "package", "message_short" => $this->uri["order"]." - ".$this->TPL["error_msg"], "message_long" => json_encode($rs)]);
            }
           
        }
        $this->TPL["redirect_url_pass"] = base_url("package/print_done/eshop_id/".$this->uri["eshop_id"]."/order/".$this->uri["order"]);

        $next_page = $this->package_model->is_all_selected_packed($this->uri["eshop_id"]);
        if($next_page === False){
            $this->TPL["redirect_url_err"] = base_url("package/packaging/eshop_id/".$this->uri["eshop_id"]."/order/".$this->uri["order"]);
        }else{
            $this->TPL["redirect_url_err"] = base_url("package/packaging/eshop_id/".$this->uri["eshop_id"]."/r/".$next_page);
        }
        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/label_print', $this->TPL);
        $this->load->view('footer', $this->TPL);



    }
    // akce po vytisknuti stitku, oznaceni ze je objednavka zabalena a prechod na dalsi
    function print_done(){
        
        if(!isset($this->uri["eshop_id"]) || !isset($this->uri["order"])){
            die("parameters missing.");
        }
        $settings = $this->package_model->init();

        $order = $this->package_model->get_order($this->uri["eshop_id"], $this->uri["order"])[0];
        $order["data"] = json_decode($order["data"], true);
        $settings["settings"] = json_decode($settings["settings"], true);
        
        $this->package_model->update_selected_order([
                                                "package_eshop_id" => $this->uri["eshop_id"],
                                                "package_order_code" =>$this->uri["order"],
                                                "package_packed_date" => "NOW()",
                                                "package_selected" => "0",
                                                "package_packed_selected" => $this->client_model->current["client_id"],
                                                "package_client_end" => $this->client_model->current["client_id"],
                                                ]);
        $this->package_model->do_action($this->uri["eshop_id"], $settings["settings"]["packaging_finish_actions"], $this->uri["order"]);



        $next_page = $this->package_model->is_all_selected_packed($this->uri["eshop_id"]);
        if($next_page === False){
            redirect("package/list/eshop_id/".$this->uri["eshop_id"]);
        }else{
            redirect("package/packaging/eshop_id/".$this->uri["eshop_id"]."/r/".$next_page);
        }

    }

    //ziskani trasovani objednavky v balikobotu
    function get_balikobot_tracking(){
        if(!isset($this->uri["eshop_id"]) || !isset($this->uri["package_id"]) || !isset($this->uri["shipping"]) ){
            die("parameters missing.");
        }
        $settings = $this->package_model->init();
        $settings["settings"] = json_decode($settings["settings"], true);
        if(!isset($settings["settings"]["balikobot_types"][$this->uri["shipping"]])) {
            echo "<div style='color: red; font-size: 20px;'>Není definována přepravní společnost pro tuto dopravu v nastavení pro Balíkobot</div>";
            exit();
        }
        $shipping_company = $settings["settings"]["balikobot_types"][$this->uri["shipping"]];
        $this->TPL["tracking_stats"] = $this->balikobot_model->get_tracking($settings["settings"]["balikobot_user"].":".$settings["settings"]["balikobot_key"], $shipping_company, $this->uri["package_id"]);
        $this->load->view('tools/package/balikobot_tracking', $this->TPL);
        
    }
    // stranka s fotogalerii objednavky
    function packaging_photos(){
        if(!isset($this->uri["eshop_id"]) || !isset($this->uri["order"])){
            die("parameters missing.");
        }
        $settings = $this->package_model->init();
        $this->TPL["photos"] = $this->package_model->get_package_photos(["eshop_id" => $this->uri["eshop_id"], "order_code" => $this->uri["order"]]);
        $settings["eshop_data"] = json_decode($settings["eshop_data"], true);
        $this->TPL["image_prefix"] = "";
        foreach ($settings["eshop_data"]["data"]["imageCuts"] as $img_cut) {
            $this->TPL["image_prefix"] =  $img_cut["urlPath"];
            break;
        }
        // stazeni vsech fotografii a zabaleni do archivu ZIP
        if(isset($this->uri["download_zip"])){
            $zip = new ZipArchive;
            $tmpfname = tempnam("./img_tmp", "BALIC_ZIP");
            $zip->open($tmpfname,  ZipArchive::CREATE);
            $unlink_list = [];
            foreach ($this->TPL["photos"] as $photo) {
                $product = False;
                if($photo["package_photo_custom_id"] && $photo["package_photo_type"] == "ITEM-SCAN"){
                    $product = $this->package_model->get_packed_items(["package_packed_items_id" => $photo["package_photo_custom_id"]], true);
                    if(count($product) == 0) {
                        $product = False;
                    }else {
                        $product = $product[0];
                        $product_data = json_decode($product["product_data"], true);
                        
                    } 
                }

                $tmpfname_photo = tempnam("./img_tmp", "BALIC_PHOTO_ZIP");
                $handle = fopen($tmpfname_photo, "w"); 

                fwrite($handle, file_get_contents(get_balic_photo($photo["package_photo_url"]))); 

                fclose($handle);

                $filename = $this->uri["order"].'_'.normalizeString($photo['package_photo_datetime'].'_'.$photo["package_photo_type"]);
                if($product) $filename .= "_".normalizeString($product["package_item_code"]);
                $filename .= ".jpg";

                $zip->addFile("./img_tmp/".end(explode("/", $tmpfname_photo)), $filename); 

                $unlink_list[] = $tmpfname_photo;
   
              
            }

            $zip->close();
            header('Content-disposition: attachment; filename='.$this->uri["order"].'_BRANI_BALIC.zip'); 
            header('Content-type: application/zip');
            readfile($tmpfname);
            unlink($tmpfname);
            foreach ($unlink_list as $uf) {
                unlink($uf);
            }

            exit();
        }


        $this->TPL["title"] = "Fotogalerie objednávky číslo ".$this->uri["order"];
        $this->load->view('header', $this->TPL);
        $this->load->view('tools/package/packaging_photos', $this->TPL);
        $this->load->view('footer', $this->TPL);
    }
    // stazeni fotografie pro uzivatele z jeji URL, ktera je ulozena externe
    function download_image(){
        header("Content-type:image/jpeg");
        $image = file_get_contents($_GET["l"]);
        echo $image;
    }
    
}
