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

class Package_model extends CI_Model
{
    
    public function __construct()
    {
        date_default_timezone_set('Europe/Prague');
        parent::__construct();
    }
    

    // instalacni metoda volana pri instalaci samotneho doplnku
    function install($eshop_id){
        if(!$this->package_table_exist($eshop_id)){
            $this->dbe->set('package', ["eshop_id" => $eshop_id,"hash" => md5($eshop_id."tajne".rand(999,9999)),"settings" => "{}"]);
            $this->db->insert('package');
        }
        
    }
    // inicializacni funkce pro kazdou stranku. Kontroluje prihlaseni a opraveni pro tento doplnek
    function init(){
        $this->client_model->check_login();
        if(!isset($this->uri["eshop_id"])) redirect("/");
        $settings = $this->package_model->get_settings(["eshop_id" => $this->uri["eshop_id"]]);
        if(count($settings) != 1) redirect("/");
        $settings = $settings[0];
        if($settings["org_id"] != $this->client_model->current["org_id"]) die("Nemáš právo.");
        return $settings;
    }

    // kontrola zda jiz pro dany eshop doplnek neni nainstalovan
    function package_table_exist($eshop_id){
        $this->db->from("package");
        $this->db->where("eshop_id", $eshop_id);
        $q = $this->db->get();
        $u = $q->result_array();
        return !empty($u);
    }
    // ziskani nastaveni doplnku
    function get_settings($data =[])
    {   $data["module"] = "package-filter";
        $this->db->from("eshop_module");
        $this->db->join("eshop", "eshop.eshop_id=eshop_module.eshop_id");
        $this->db->join("package", "package.eshop_id=eshop_module.eshop_id");
        $this->dbe->where("eshop_module", $data);
        $this->dbe->where("eshop", $data);
        $this->dbe->where("package", $data);
        $q = $this->db->get();
        $u = $q->result_array();
        
        return $u;
    }
    // ulozeni nastaveni doplneku
    function save_settings($data){
        $this->db->from('package');
    
        $this->db->where('eshop_id', $data["eshop_id"]);
        unset($data["eshop_id"]);
        $this->dbe->set('package', $data);
        $this->db->update('package');
    }
    
    // ziskani objednavek. Lze volat i s filtrem
    function get_orders($eshop_id, $page=0, $filter = []){
        $items_per_page = 50;
        $this->db->from("eshop_module_orders");
        $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
        $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
        foreach ($filter as $fn => $fv){
            if(is_array($fv)){
                $this->db->where_in($fn, $fv);
            }else{
                $this->db->where($fn, $fv);
            }
        }
        $this->db->order_by("order_code", "DESC");
        $this->db->limit($items_per_page, ($page)*$items_per_page);
        $q = $this->db->get();
        $u = $q->result_array();

        return $u;
    }
    // ziskani vybrane objednavky podle cisla poradi
    function get_selected_orders_by_row($eshop_id, $row_num){
        $this->db->from("eshop_module_orders");
        $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
        $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
        $this->db->where("(package_selected = ".$this->client_model->current["client_id"]." OR package_packed_selected = ".$this->client_model->current["client_id"].")");

        $this->db->order_by("eshop_module_orders.order_code");
        $this->db->limit(1, $row_num);
        $q = $this->db->get();
        $u = $q->result_array();
         
        return $u;
    }

    // ziskani vsech oznacenych objednavek
    function get_selected_orders($eshop_id, $client_id, $order_by_date=False){
        $this->db->from("eshop_module_orders");
        $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
        $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
        $this->db->where("package_selected", $client_id);
        if($order_by_date === True) $this->db->order_by("package_selected.package_selected_date");
        else $this->db->order_by("eshop_module_orders.order_code");
        
        $q = $this->db->get();
        $u = $q->result_array();

        return $u;
    }
    // ziskani konrketni objednavky
    function get_order($eshop_id, $order_code){
        $this->db->from("eshop_module_orders");
        $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
        $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
        $this->db->where("eshop_module_orders.order_code", $order_code);
        $q = $this->db->get();
        $u = $q->result_array();
        return $u;
    }
    // pocet vybranych objednavek
    function count_selected_orders($eshop_id, $packed=False){
        $this->db->from("package_selected");
        $this->db->where("package_eshop_id", $eshop_id);
        $this->db->where("package_selected", $this->client_model->current["client_id"]);
        if($packed === True){
            $this->db->where('package_packed_date is NOT NULL', NULL, FALSE);
        }
        return $this->db->count_all_results();
    }

    // pocet jiz zabalenych zvolenych objednavek
    function count_packed_selected_orders($eshop_id, $packed=False){
        $this->db->from("package_selected");
        $this->db->where("package_eshop_id", $eshop_id);
        $this->db->where("package_packed_selected", $this->client_model->current["client_id"]);
        if($packed === True){
            $this->db->where('package_packed_date is NOT NULL', NULL, FALSE);
        }
        return $this->db->count_all_results();
    }

    // transformace dat o eshopu pro ruzne prvky na strance jako jsou dropdowny nebo preklady ID na nazvy
    function process_eshop_data($data, $show_type=True)
    {
        $velkoobchod = "";
        $maloobchod = "";
        if ($show_type) {
            $velkoobchod = " (Velkoobchod)";
            $maloobchod = " (Maloobchod)";
            $rs["payments_dropdown"] = ["Maloobchod" => [], "Velkoobchod" => []];
            $rs["shippings_dropdown"] = ["Maloobchod" => [], "Velkoobchod" => []];
        }
        $rs = ["statuses" => [], "payments" => [], "shippings" => []];
        foreach ((array)$data["data"]["orderStatuses"]["statuses"] as $s) {
            $rs["statuses"][$s["id"]] = $s["name"];
        }
        foreach ((array)$data["data"]["paymentMethods"]["wholesale"]["methods"] as $pw) {
            $rs["payments"][$pw["guid"]] = $pw["name"] . $velkoobchod;
            if($show_type) $rs["payments_dropdown"]["Velkoobchod"][$pw["guid"]] = $pw["name"] . $velkoobchod;
            else $rs["payments_dropdown"][$pw["guid"]] = $pw["name"] . $velkoobchod;
            
        }
        foreach ((array)$data["data"]["paymentMethods"]["retail"]["methods"] as $pr) {
            $rs["payments"][$pr["guid"]] = $pr["name"] . $maloobchod;
            if($show_type) $rs["payments_dropdown"]["Maloobchod"][$pr["guid"]] = $pr["name"] . $maloobchod;
            else $rs["payments_dropdown"][$pr["guid"]] = $pr["name"] . $maloobchod;
        }
    
        foreach ((array)$data["data"]["shippingMethods"]["wholesale"]["methods"] as $sw) {
            $rs["shippings"][$sw["guid"]] = $sw["name"] . $velkoobchod;
            if($show_type) $rs["shippings_dropdown"]["Velkoobchod"][$sw["guid"]] = $sw["name"] . $velkoobchod;
            else $rs["shippings_dropdown"][$sw["guid"]] = $sw["name"] . $velkoobchod;
        }
        foreach ((array)$data["data"]["shippingMethods"]["retail"]["methods"] as $sr) {
            $rs["shippings"][$sr["guid"]] = $sr["name"] . $maloobchod;
            if($show_type) $rs["shippings_dropdown"]["Maloobchod"][$sr["guid"]] = $sr["name"] . $maloobchod;
            else $rs["shippings_dropdown"][$sr["guid"]] = $sr["name"] . $maloobchod;
        }
        if (isset($data["stocks"])) {
            $rs["stocks"] = [];
            foreach ($data["stocks"]["data"]["stocks"] as $s) {
                $rs["stocks"][$s["id"]] = $s["title"];
            }
        } else {
            $rs["stocks"] = False;
        }
        if ($show_type) {

            if($rs["payments_dropdown"]["Velkoobchod"]) asort($rs["payments_dropdown"]["Velkoobchod"]);
            if($rs["payments_dropdown"]["Maloobchod"]) asort($rs["payments_dropdown"]["Maloobchod"]);
            if($rs["shippings_dropdown"]["Velkoobchod"]) asort($rs["shippings_dropdown"]["Velkoobchod"]);
            if($rs["shippings_dropdown"]["Maloobchod"]) asort($rs["shippings_dropdown"]["Maloobchod"]);
            if($rs["shippings_dropdown"]) ksort($rs["shippings_dropdown"]);
            if($rs["payments_dropdown"]) ksort($rs["payments_dropdown"]);
        }else{
            if($rs["payments_dropdown"]) asort($rs["payments_dropdown"]);
            if($rs["shippings_dropdown"]) asort($rs["shippings_dropdown"]);
        }
        return $rs;
    }
    
    //Nalezeni objednavky pri jejim skenovani dle cisla nebo cisla baliku
    function search_order($eshop_id, $scan){
        
        $this->db->from("eshop_module_orders");
        $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
        $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
        
        $this->db->where("eshop_module_orders.order_code", $scan);
        
        $q = $this->db->get();
        $u = $q->result_array();
        if(count($u) == 0){
            $this->db->from("eshop_module_orders");
            $this->db->join("package_selected", "package_selected.package_eshop_id=eshop_module_orders.eshop_id AND package_selected.package_order_code=eshop_module_orders.order_code", "left");
            $this->db->where("eshop_module_orders.eshop_id", $eshop_id);
            
            $this->db->where("eshop_module_orders.package_number", $scan);
            $q = $this->db->get();
            $u = $q->result_array();

        }
        return $u;
    }

    // odznaceni objednavek co jsou vybrany a jsou i zabaleny    
    function clean_packed_selected_order($eshop_id){
        $this->db->from('package_selected');
    
        $this->db->where('package_eshop_id', $eshop_id);
        $this->db->where('package_packed_selected', $this->client_model->current["client_id"]);
         $this->db->set('package_packed_selected', "0");
        $this->db->update('package_selected');

    }

    // odznaceni vybranych objednavek
    function unselect_all_orders($eshop_id){
        $this->db->from('package_selected');
    
        $this->db->where('package_eshop_id', $eshop_id);
        $this->db->where('package_selected', $this->client_model->current["client_id"]);
         $this->db->set('package_selected', "0");
        $this->db->update('package_selected');

    }
    // aktuaualizace dat o vybrane objednavce
    function update_selected_order($data){
        $this->db->from('package_selected');
    
        $this->db->where('package_eshop_id', $data["package_eshop_id"]);
        $this->db->where('package_order_code', $data["package_order_code"]);
        unset($data["package_order_code"]);
        unset($data["package_eshop_id"]);
        
        if($data["package_packed_date"]){
            $this->db->set('package_packed_date', $data["package_packed_date"], false);
            unset($data["package_packed_date"]);
        }
        $this->dbe->set('package_selected', $data);
        $this->db->update('package_selected');
    }
    
    // kontrola zda jsou vsechny vybrane objednavky zabaleny
    function is_all_selected_packed($eshop_id){
    
        $this->db->from("package_selected");
        $this->db->where("package_eshop_id", $eshop_id);
        $this->db->where("(package_selected =".$this->client_model->current["client_id"]. " OR package_packed_selected =".$this->client_model->current["client_id"].")");
        $this->db->order_by("package_order_code");
        $q = $this->db->get();
        $u = $q->result_array();
        $first_skip_page = NULL;
        $page = 0;
        foreach ($u as $i){
            if($i["package_packed_date"] === NULL) {
                if(isset($_SESSION["packaging_last_page"]) and $_SESSION["packaging_last_page"] > $page){
                    if($first_skip_page === NULL) $first_skip_page = $page;
                }else{
                    return $page;
                } 
            }
            $page++;
        }
        if($first_skip_page !== NULL) return $first_skip_page;
        
        //pokud je vse zabaleno, odznaci se tyto objednavky
        $this->db->from('package_selected');
        $this->db->where('package_eshop_id', $eshop_id);
        $this->db->set('package_selected', "0");
        $this->db->update('package_selected');
        
        return False;
    }
    // provedeni akce - napriklad pri stisku akcniho tlaickta
    // navrzeno tak, aby bylo mozne pridat dalsi typy akci v budoucnu
    function do_action($eshop_id, $action, $order){
        $eshop_model = $this->shoptet_model->get_shoptet_module_for_api_call($eshop_id, "package-filter");
        foreach ($action as $name => $value){
            switch ($name){
                case "change_status":
                    if($this->shoptet_model->change_order_status($eshop_model,$order, $value)){
                        $this->update_order_status($eshop_id, $order, $value);
                    }
                    break;
            }
        }
    }
    // pridani nacteneho produktu do tabulky
    function add_packed_item($eshop_id, $order_code, $item_code, $item_guid){
        $this->db->set("package_eshop_id", $eshop_id);
        $this->db->set("package_order_code", $order_code);
        $this->db->set("package_item_code", $item_code);
        $this->db->set("package_item_guid", $item_guid);
        $this->db->set("packed_item_datetime", "NOW()", false);
        $this->db->set("packed_item_client_id", $this->client_model->current["client_id"]);
        
        $this->db->insert('package_packed_items');

        return $this->db->insert_id();
    }
    // odstraneni nacteneho produktu z tabulky
    function rm_packed_item($eshop_id, $order_code, $item_code){
        $this->db->where("package_eshop_id", $eshop_id);
        $this->db->where("package_order_code", $order_code);
        $this->db->where("package_item_code", $item_code);
        $this->db->limit(1);
        $this->db->delete('package_packed_items');
    }
    // odstraneni kompletovanych produktu
    function rm_packed_items($data){
        $this->dbe->where('package_packed_items', $data);
        $this->db->delete('package_packed_items');
    }
    // ziskani jiz kompletovanych produktu z objednavky
    function get_packed_items($data, $join_product = False){
        $this->db->from('package_packed_items');
        $this->dbe->where("package_packed_items", $data);
        $this->db->join("client", "packed_item_client_id=client_id");
        if($join_product){
                $this->db->join("eshop_module_products", "eshop_module_products.eshop_id=package_eshop_id AND eshop_module_products.product_guid=package_item_guid");
        }
        $q = $this->db->get();
        $u = $q->result_array();
        return $u;
    }
    // vygenerovani seznamu poroduktu potrebnych pro dane objednavky
    function get_picking_list($eshop_id, $orders, $only_one_product = False, $split_set_products = False){
        $picking_item = [];

        foreach ($orders as $o) {
            $o["data"] = json_decode($o["data"], true);
            // rozdeleni sady na samotne polozky sady, pokud je to nastaveno
            if($split_set_products){
                foreach($o["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";
                            
                            $o["data"]["items"][] = $new_item;
                        }
                        unset($o["data"]["items"][$index]);


                    }
                }
            }
            
            foreach($o["data"]["items"] as $index => $item){
                if($item["code"] == "") continue;
                if($only_one_product and $only_one_product != $item["code"]) continue;
                if(!isset($picking_item[$item["code"]])){
                    $shoptet_product = $this->eshop_module_products_model->get_products(["eshop_id" => $eshop_id, "product_guid" => $item["productGuid"]]);
                    if(!empty($shoptet_product)){
                        $shoptet_product = $shoptet_product[0];
                        $shoptet_product["product_data"] = json_decode($shoptet_product["data"],true);
                        if($shoptet_product["product_data"]["type"] == "product-set"){

                        }
                        foreach ($shoptet_product["product_data"]["variants"] as $vk => $vv) {
                            if($vv["code"] != $item["code"]) unset($shoptet_product["product_data"]["variants"][$k]);
                        }
                    }
                    $picking_item[$item["code"]] = ["shoptet_product" => $shoptet_product, "total_amount" => 0, "for_orders" => [], "stock_location" => "", "package_selected_numbers" => []];
                }
                $picking_item[$item["code"]]["total_amount"] += $item["amount"];
                $o["current_item"] = $item;
                $picking_item[$item["code"]]["for_orders"][] = $o;
                if(!isset($picking_item[$item["code"]]["package_selected_numbers"][$o["package_selected_number"]])) $picking_item[$item["code"]]["package_selected_numbers"][$o["package_selected_number"]] = 0;
                $picking_item[$item["code"]]["package_selected_numbers"][$o["package_selected_number"]] += $item["amount"];
                if($item["stockLocation"] != "") $picking_item[$item["code"]]["stock_location"] = $item["stockLocation"];
            }
        }
        return $picking_item;

    }
    // generace nastaveni pro akce na custom tlacitkach
    function generate_action_settings($title, $name, $values, $statuses, $custom_button=false){
        $html = "";
        $html .= "<h3 class='action_settings_title'>".$title."</h3>";
        $html .= "<div class='action_settings_general'>";
        if($custom_button == true){
            $html .= label_input('Název tlačítka', form_input('settings['.$name.'][button_name]',  $values['button_name'], 'id="'.$name.'_button_name" class="form-control"'), ['help'=>'Název tlačítka zobrazovaný při balení (max 50 znaků).', "first_col" => 3, "second_col" => 4]);
        }
        $html .= label_input('Změna stavu', form_dropdown('settings['.$name.'][change_status]', ["none" => "Nepřepínat"] +$statuses, $values['change_status'], 'id="'.$name.'_change_status" class="form-control"'), ['help'=>'Při dané akci se změní stav objednávky na zvolený.', "first_col" => 3, "second_col" => 4]);

        if($name == "packaging_finish_actions"){
            $html .= label_input('Upozornit na nedokončenou kompletaci', form_checkbox('settings['.$name.'][incomplete_alert]', '1', $values['incomplete_alert'], 'id="incomplete_alert" class="switch_1 blue" style="margin-top:14px;"'), ['help'=>'Při dokončení kompletace se zkontroluje, zda byly všechny produkty zkompletovány a pokud ne, zobrazí se upozornění.', "first_col" => 3, "second_col" => 4]);
        }

        $html .= "</div>";

        return $html;
    }

    // aktualizace stavu objednavky v DB
    function update_order_status($eshop_id, $order_code, $status_id){

        $this->db->where('eshop_id', $eshop_id);
        $this->db->where('order_code', $order_code);
        $this->db->set("order_status_id", $status_id);
        $this->db->update("eshop_module_orders");
    }
    
    // pridani zaznamu o nove fotografii
    function add_package_photo($data){
        $data["client_id"] = $this->client_model->current["client_id"];
        $this->dbe->set("package_photo", $data);
        $this->db->set("package_photo_datetime", "NOW()", false);
        
        $this->db->insert('package_photo');

        return $this->db->insert_id();
    }
    // ziskani fotografii
    function get_package_photos($data){
        $this->db->from("package_photo"); 
        $this->dbe->where("package_photo", $data);
        $this->db->join("client", "client.client_id=package_photo.client_id");
        $this->db->order_by("package_photo_datetime");
        $q = $this->db->get();
        return $q->result_array();
    }
    // aktualizace cisel krabic
    function reload_selected_numbers($eshop_id, $client_id){
         $selected_orders = $this->package_model->get_selected_orders($eshop_id, $client_id, true);

         foreach ($selected_orders as $key => $value) {
             $this->update_selected_order(["package_eshop_id" => $value["package_eshop_id"], "package_order_code"=> $value["package_order_code"], "package_selected_number" => $key+1]);
         }

    }
    // ziskani ckompletace v picking listu
    function get_package_selected_number($data){
        $this->db->from("package_selected_number"); 
        $this->dbe->where("package_selected_number", $data);
        $q = $this->db->get();
        return $q->result_array();
    }
    // pridani kompletace v picking listu
    function add_package_selected_number($data){
        $this->dbe->set("package_selected_number", $data);
        $this->db->set("selected_date", "NOW()", false);
        
        $this->db->insert('package_selected_number');
    }

    // smazani kompletace v picking listu
    function del_package_selected_number($data){
        $one_item = $this->get_package_selected_number($data);
        if(empty($one_item)) return False;
        else $one_item = $one_item[0];
        $this->dbe->where('package_selected_number', $one_item);
        $this->db->delete('package_selected_number');
    }
    // vyresetovani kompletace v picking listu
    function del_all_package_selected_number($data){
        $this->dbe->where('package_selected_number', $data);
        $this->db->delete('package_selected_number');
    }
    

    function transform_package_selected_number($selected_numbers){
        $final_array = [];
        foreach ($selected_numbers as $key => $value) {
            if(!isset($final_array[$value["code"]])) $final_array[$value["code"]] = [];
            if(!isset($final_array[$value["code"]][$value["package_selected_number"]])) $final_array[$value["code"]][$value["package_selected_number"]] = 0;
            $final_array[$value["code"]][$value["package_selected_number"]] += 1;
        }

        return $final_array;
    }
    // ziskat text kompletace dle barvy
    function get_package_selected_number_amount_text($amount, $total){
        if($amount == $total){
            return "<span style='color:#26B99A;'>".$amount." / ".$total." ks</span>";
        }
        return "<span style='color:#ff3333;'>".$amount." / ".$total." ks</span>";
    }

    // ziskani vahy objednavky - secteni vahy vsech polozek
    function get_order_weight($order){
        if(!is_array($order["data"])) $order["data"] = json_decode($order["data"], true);
        $total_weight = 0;

        foreach ($order["data"]["items"] as $key => $value) {
            $total_weight += (float)$value["weight"]*(float)$value["amount"];
        }
        return $total_weight;
    }
}