<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of StockAjax
 *
 * @author Ola
 */
class StockAjax extends mainController {

    private $db;

    public function __construct() {
        parent::__construct();
        $this->year_id = Session::getCurrentYearID();
        $this->load->model('Stock');
        $this->controller_permission = Session::getPermissionsObject();
        $this->db = DBConnectorFactory::loadDriver();
    }

    public function landing() {

    }

    public function DamagedItemsRequest() {
        $cond = '';
        $from_date = $_GET['From_Date'];
        $to_date = $_GET['To_Date'];
        $depot_id = smc_escape($_GET['depot_id']);
        $cond .= '  Adjust_Date <= "' . $to_date . '" AND Adjust_Date >= "' . $from_date . '"';
        if ($depot_id !== 'All') {
            $cond .= ' AND Depot_ID = "' . $depot_id . '"';
        }
        if (!empty($_GET['category_id'])) {
            $cond .= ' AND category_id = "' . $_GET['category_id'] . '"';
        }
        if (!empty($_GET['brand_id'])) {
            $cond .= ' AND brand_id = "' . $_GET['brand_id'] . '"';
        }
        if (is_numeric($_GET['customer_id']))
            $cond .= ' and customer_id = "' . $_GET['customer_id'] . '"';
        $columns = array(
            'Name', 'Depot_Name', 'Damaged_Reason', 'Adjust_Date', 'Customer_Name',
            array('Item_Quantity_Current', 'formatter' => function($d, $row) {
                return $d . ' ' . $row['UOM_Name'];
            })
        );
        if ($this->controller_permission->hasPermission('show_cost_column_damaged'))
            $columns[] = array('db' => 'total_cost', 'formatter' => function($d, $row) {
            return CommonFunctions::formatNumber($d) . ' ' . smc_session()['local_currency_symbol'];
        });
        //        $columns[] = array('db' => 'Damaged_ID',
        //                           "formatter" => function($d, $row) {
        //                               if (empty($row['app_damage_id']) && empty($row['return_detail_id'])) {
        //                                   $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => false, "data_id" => $d,
        //                                                                  "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
        //                                                                                      "class" => "delete",
        //                                                                                      "icon" => "fa-trash",
        //                                                                                      "permission" => "delete_damage",
        //                                                                                     ]]]);
        //                               } else {
        //                                   $html = CommonLanguage::getMessage('noauthactions');
        //                               }
        //                               return $html;
        //                           });
        $columns[] = 'app_damage_id';
        $columns[] = 'return_detail_id';
        $columns[] = 'UOM_Name';
        $key = 'Damaged_ID';
        $table = 'damaged_products';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function ListDepotRequest() {
        $columns = array(
            array('db' => 'Depot_Code', 'dt' => 0),
            array('db' => 'Depot_Name', 'dt' => 1),
            array('db' => 'Category_Name', 'dt' => 2),
            array('db' => 'Depot_Type_Of_Storage', 'dt' => 3),
            array('db' => 'Employee_Name', 'dt' => 4),
            array('db' => 'Depot_ID', 'dt' => 5,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => false,
                                                     "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                                                         "class" => "View",
                                                                         "icon" => "fa-eye",
                                                                         "href" => "Stock/ViewDepot/{$d}"
                                                                        ]]]);
                      return $html;
                  })
        );
        $key = 'Depot_ID';
        $table = 'depot_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function submitDepot() {
        $submit = $_POST['Depot_ID'] == 0 ? $this->_registry->depot->setData($_POST)->addDepot() : $this->_registry->depot->setData($_POST)->updateDepot();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getDepotDetails() {
        $data = $this->_registry->depot->getDepotInfo($_GET['Depot_ID']);
        die(json_encode($data));
    }

    //    public function EditDepotAjax() {
    //        if ($_POST["CheckEdit"]) {
    //            $RET = $this->_registry->depot->setData($_POST)->updateDepot();
    //            //            die(print_r($RET));
    //            if (empty($RET)) {
    //                //$data = $this->_registry->depot->getDepotProfile($_POST['Depot_ID']);
    //                //$form = Forms::viewProfiles($data);
    //                die(json_encode(['ok', ''/* $form */]));
    //            } else {
    //                die(json_encode(['', $RET[0]]));
    //            }
    //        } else {
    //            $RET = $this->_registry->depot->setData($_POST)->addDepot();
    //            die(json_encode(empty($RET) ? 'ok' : $RET[0]));
    //        }
    //    }

    public function ProductLocationListRequest() {
        $cond = '';
        if (isset($_GET['cat']) && $_GET['cat'] != '') {
            $cond = ' Category_ID = "' . $_GET['cat'] . '"';
        }
        if (isset($_GET['depot_id']) && $_GET['depot_id'] != '') {
            $cond = ' Depot_ID = "' . $_GET['depot_id'] . '"';
        }
        $columns = array('Product_Code');
        if (smc_session()['default_setting']['activate_search_product_second_code'] == 1) {
            array_push($columns, 'product_second_code');
        }
        array_push($columns, 'Product_Name', 'Depot_Name', 'Product_Quantity');
        $key = 'Product_ID';
        $table = 'product_location';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function ProductLocationListAjax() {
        if (isset($_GET['code_id'])) {
            $code = $_GET['code_id'];
            $ProductLocation = $this->_registry->depot->getProductLocationInfo(null, $code);
            die(json_encode($ProductLocation));
        }
        if (isset($_POST["GetID"])) {
            $logged_id = Session::getUserID();
            $Procut_Location_ID = $_POST["GetID"];
            $delete_product_location = $this->_registry->depot->DeleteProductLocation($Procut_Location_ID, $logged_id);
            die($delete_product_location ? "OK" : "error");
        }
    }

    public function RequestListRequest() {
        $cond = '1=1';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and (Request_Date between "' . smc_escape($_GET['from_date']) . '" and "' . smc_escape($_GET['to_date']) . '" )  ';
        if (!empty($_GET['is_transfer']))
            $cond .= ' and Status_ID = 3 ';
        $columns = array(
            array('db' => 'req_nb', 'formatter' => function($d, $row) {
                return '<input type="checkbox" data-id="' . $row['Request_ID'] . '" data-nb="' . $d . '"  class="req_del_td pull-left multi_delete"/>' . $d;
            })
        );
        if (empty($_GET['is_transfer'])) {
            $columns[] = 'Delivery_Date';
            $columns[] = 'Req_From';
            $columns[] = 'Req_To';
            $columns[] = array('db' => 'Status_ID',
                               'formatter' => function($d) {
                                   $Statuses = [StatusCodes::getStatus(19) . "#label-inverse", StatusCodes::getStatus(20) . "#label-warning", StatusCodes::getStatus(21) . "#label-info", StatusCodes::getStatus(22) . "#label-danger"];

                                   return '<span class="label ' . explode("#", $Statuses[$d - 1])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d - 1])[0] . '</span>';
                               });
        } else {
            $columns[] = 'Req_To';
            $columns[] = 'Req_From';
        }

        $columns[] = array('db' => 'Request_ID',
                           "formatter" => function($d, $row) {
                               $common_actions = [["title" => CommonLanguage::getMessage("View"),
                                                   "class" => "print_request",
                                                   "icon" => "fa-eye"
                                                  ]];
                               if($row['Status_ID'] == 1){
                                   $common_actions[] = ["title" => CommonLanguage::getMessage("transfer"),
                                                        "class" => "ViewRequest",
                                                        "href" => "Stock/RequestOrder/transfer/convert/{$d}",
                                                        "permission"=>"confirm_request",
                                                        "icon" => "fa-check"
                                                       ];
                               }
                               if(!empty($_GET['is_transfer'])){
                                   $common_actions[] = ["title" => CommonLanguage::getMessage("delivered"),
                                                        "class" => "confirm_delivered",
                                                        "href" => "Stock/confirm_delivered_items/{$d}",
                                                        "permission"=>"confirm_delivered_items",
                                                        "icon" => "fa-check"
                                                       ];
                               }
                               if (empty($row['app_request_id']) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {
                                   $common_actions[] = ["title" => CommonLanguage::getMessage("Delete"),
                                                        "class" => "delete_request",
                                                        "attr" => "data-ticketing-id='{$row['ticketing_id']}'",
                                                        "permission" => $row['Status_ID'] == 3 ? "delete_transfer" : "delete_Request",
                                                        "icon" => "fa-trash"
                                                       ];
                                   if ($row['Status_ID'] != 4) {
                                       $common_actions[] = ["title" => CommonLanguage::getMessage("Edit"),
                                                            "class" => "Edit",
                                                            "permission" => "editTransfer",
                                                            "icon" => "fa-pencil",
                                                            "href" => "Stock/RequestOrder/" . ($row['Status_ID'] == 3 ? 'transfer/' : '') . "{$d}"
                                                           ];
                                   }
                               }
                               $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => true, "data_id" => $d,
                                                              "ActionOption" => $common_actions]);
                               return $html;
                           });
        $columns[] = 'is_main_transfer';
        $columns[] = 'app_request_id';
        $columns[] = 'Status_ID';
        $columns[] = 'ticketing_id';

        $cond .= '  ORDER BY Request_ID desc ';
        $key = 'Request_ID';
        $table = 'request_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    } 


    public function RequestOrderAjax() {
        if (isset($_POST['Request_To'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->depot->setData($_POST)->createRequest();
            die(json_encode(is_numeric($result[0]) ? ['OK', $result[0], $result[1]] : $result ));
        }
    }
  


    public function editRequestOrderAjax() {
        if (isset($_POST['Products'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->depot->setData($_POST)->editRequest();
            die(json_encode(is_numeric($result[0]) ? ['OK', $result[0], $result[1]] : $result ));
        } else {
            die(json_encode(["error"]));
        }
    }

    public function StockDashboardAjax() {
        if (isset($_GET["Material_Category_ID"])) {
            die(json_encode($this->_registry->material->getType($_GET["Material_Category_ID"])));
        }
    }

    public function StockDashboardRequest() {
        $cond = '';
        if (isset($_GET['Material_Code'])) {
            $cond .= 'Product_ID = "' . smc_escape($_GET['Material_Code']) . '" ';
        }
        if (isset($_GET['freq'])) {
            $freq = $_GET['freq'];
            $date = $_GET['Report_Date'];
            if ($freq == 1) {
                $cond .= ' AND Date = "' . smc_escape($date) . '"';
            } else if ($freq == 3) {
                $cond .= ' AND MONTH(Date) = "' . smc_escape($date[1]) . '" AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
            } else if ($freq == 4) {
                $cond .= ' AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
            }
        }
        $columns = array(
            array('db' => 'DepotFrom', 'dt' => 0),
            array('db' => 'DepotTo', 'dt' => 1),
            array('db' => 'SUM(Quantity)', 'dt' => 2),
        );
        $group = 'GROUP BY From_To';
        $key = 'From_To';
        $table = 'transfered_items';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);

        echo json_encode($data);
    }

    public function TransferGoodsAjax() {
        if (isset($_POST['Request_ID']) && isset($_POST['Status_ID'])) {
            $Status = $_POST['Status_ID'];
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            //                                                            if ($Status == 2) {
            $depot = $this->_registry->depot->setData($_POST)->confirmTransfer();
            //                                                            } else {
            //                                                                $depot = $this->_registry->depot->setData($_POST)->createTransfer();
            //                                                            }
            die(empty($depot) ? "ok" : "error");
        }
        if (isset($_GET['Rejection_Comment']) && isset($_GET['Request_ID'])) {
            $depot = $this->_registry->depot->setData($_GET)->rejectTransfer();
            die(empty($depot) ? "ok" : "error");
        }




        if (isset($_POST['Product_ID']) && isset($_POST['Category_ID'])) {
            $Products_ID = $_POST['Product_ID'];
            $Categories_ID = $_POST['Category_ID'];
            $Depot_ID = $_POST['Depot_ID'];
            $Expiry = $this->_registry->depot->getExpiryAmounts($Products_ID, $Categories_ID, $Depot_ID);
            die(json_encode($Expiry));
        }
        if (isset($_GET['PID'])) {
            //    die("okk");
            $data = $this->_registry->product->viewProductExpiryQuantity($_GET['PID'], 0, $_GET['DID']);
            die(json_encode($data));
        }
    }

    public function TransferListRequest() {
        $cond = ' Status_ID = 3';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and  (Request_Date between "' . smc_escape($_GET['from_date']) . '" and "' . smc_escape($_GET['to_date']) . '" )  ';

        $columns = array(
            array('db' => 'req_nb', 'dt' => 0),
            array('db' => 'Req_To', 'dt' => 1),
            array('db' => 'Req_From', 'dt' => 2),
            array('db' => 'Request_ID', 'dt' => 3,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => false,
                                                     "ActionOption" => [["title" => "",
                                                                         "class" => "ViewTransfer",
                                                                         "href" => "Stock/ViewTransfer/{$d}",
                                                                         "icon" => "fa-eye"
                                                                        ]]]);
                      return $html;
                  })
        );
        $key = 'Request_ID';
        $table = 'request_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function UploadExcelFileAjax() {
        if (isset($_FILES['Document_File_Name'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $uploadExcel = $this->_registry->material->setdata($_POST)->uploadExcelSheet();
            die(json_encode($uploadExcel));
        }
    }

    public function addDepotCategoryAjax() {
        $RET = $this->_registry->depot->setData($_POST)->addDepotCategory();
        if (empty($RET)) {
            $cat = $this->_registry->depot->getLastOfType('tbl_stock_categories', 'Category_ID');
            die(json_encode($cat));
        } else {
            die(json_encode($RET[0]));
        }
    }

    public function addUOMAjax() {
        $RET = $this->_registry->material->setData($_POST)->addUOM();
        if (empty($RET)) {
            $uom = $this->_registry->material->getLastOfType('tbl_stock_uom', 'UOM_ID');
            die(json_encode(empty($RET) ? $uom : 'error'));
        } else {
            die(json_encode($RET[0]));
        }
    }

    //    public function assignProductLocationAjax() {
    //        if (isset($_POST["Product_Code"])) {
    //            $type = $_POST['Transaction_Type_ID'];
    //            $logged_id = Session::getUserID();
    //            array_push($_POST, $logged_id);
    //            $RET = $this->_registry->depot->setData($_POST)->addProductLocation();
    //
    //            die(empty($RET) ? "OK" : "error");
    //        }
    //    }

    public function LoadingListRequest() {
        if (isset($_GET['Loaded_List_Date'])) {

            $header = [CommonLanguage::getMessage('Code'),
                       CommonLanguage::getMessage('Item'),
                       CommonLanguage::getMessage('Quantity'),
                       CommonLanguage::getMessage('Price')];

            $curDate = $_GET['Loaded_List_Date'];
            $loadingList = $this->_registry->LoadingOrder->viewTotalLoadByDate($curDate, null, 1);
            $form = Forms::CreateDatatable(['TableHeaders' => $header,
                                            'ArrayContent' => $loadingList,
                                            'Color_Value' => '4c0870']);
            die($form);
        }
    }

    public function StockCardAjax() {
        if (isset($_POST['Product_ID'])) {
            $product_id = $_POST['Product_ID'];
            $type = $_POST['Type'];
            $exp_from = $_POST['From_Date'];
            $exp_to = $_POST['To_Date'];
            $depot_id = $_POST['depot_id'];
            $currency_id = $_POST['currency_id'];
            $stock = $this->_registry->depot->stockCard($product_id, $type, $exp_from, $exp_to, $depot_id,$currency_id);



            if (file_exists(upload_path . 'products_photos/' . $product_id . '.jpg')) {
                $filename_card = upload_url . 'products_photos/' . $product_id . '.jpg';
            } else {
                $filename_card = SITE_LINK . 'img/profiles/product.png';
            }

            die($stock ? json_encode([$stock, $filename_card]) : "error");
        }
    }

    public function DepotContentRequest() {
        $DepotID = 0;
        $cond = '';
        if (!empty($_GET['Depot_ID'])) {
            $cond .= !empty($_GET['Depot_ID']) ? ' and Depot_ID in (' . ($_GET['Depot_ID']) . ')  ' : '';
        } 
        if (!empty($_GET['brand_id'])) {
            $brand_id = $_GET['brand_id'];
            $cond .= '  and brand_id = "' . smc_escape($brand_id) . '"';
        }
        if (isset($_GET['cat']) && $_GET['cat'] != '') {
            $cond .= ' and Category_ID = "' . $_GET['cat'] . '"';
        }
        if (!empty($_GET['operation']))
            $cond .= ' and Quantity - sys_qty ' . ( $_GET['operation'] == 'neg' ? ' < 0 ' : ' > 0 ');
        if ($_GET['is_data_collector'] == 1) {
            $cond .= ' and file_id ="' . $_GET['file_id'] . '"';
        }
        if (isset($_GET['supplier_id']) && $_GET['supplier_id'] != '') {
            $cond .= ' and main_supplier_id = "' . $_GET['supplier_id'] . '"';
        }
        
        $columns = array('Code', 'default_view_Bar_Code',
                         array('db' => 'Name', 'full_search' => true), 'brand_name',
                         array('db' => $_GET['uom_filter'] == 1 ?'Quantity_default':'Quantity', "formatter" => function($d, $row, $is_export) {
                             if ($is_export)
                                 return CommonFunctions::public_round_number($d);
                             return "<span class='sys_qty_label'>{$d}</span>";
                         }),
                         array('db' => $_GET['uom_filter'] == 1 ? 'Quantity_default' : 'Quantity', "formatter" => function($d, $row, $is_export) {
                             $input = "<div class='print-only'>" . $d . " " . "</div><span class='Hint no-print'>" . $row[ $_GET['uom_filter'] == 1 ?'default_view_uom':'default_uom_name']
                                 . "</span><input  type='text' class='QuantityVal no-print'  data-id='{$row['ID']}' value='" . $row[ $_GET['uom_filter'] == 1 ?'Quantity_default':'Quantity'] . "'"
                                 . " product-uom='" . $row['Product_UOM'] . "' data-rate='" . ( $_GET['uom_filter'] == 1 ?$row['default_view_rate']:1) . "' data-qty='" . $row[ $_GET['uom_filter'] == 1 ?'sys_qty_default':'sys_qty'] . "' data-expiry='" . $row['is_expiry'] . "' data-lot='" . $row['is_lot'] . "' data-serial='" . $row['is_serial'] . "'"
                                         . " data-uom='" . $row['UOM_ID'] . "' "
                                 . ($_GET['Depot_ID'] == 0 ? " disabled" : "") . "/>";
                             if ($is_export)
                                 return CommonFunctions::public_round_number($d);
                             return $input;
                         }),
                         array('db' => 'Quantity_default', "formatter" => function($d, $row, $is_export) {
                             if ($is_export)
                                 return CommonFunctions::public_round_number($d - $row['sys_qty_default']);
                             return "<span class='sys_qty_diff_label'>" . ($d - $row['sys_qty_default']) . "</span>";
                         }));
        if ($this->controller_permission->hasPermission('show_cost_column_depot_content')) {
            $columns[] = array('db' => 'ID', "formatter" => function($d, $row, $is_export) {
                $cost = CommonBusiness::viewCurrentProductCost($d) * $row['default_view_rate'];
                if ($is_export)
                    return CommonFunctions::public_round_number($cost);
                return '<span class="cost" data-cost="' . $cost . '">' . CommonFunctions::public_round_number($cost) . '</span>';
            });
            $columns[] = array('db' => 'ID', "formatter" => function($d, $row, $is_export) {
                $cost = CommonBusiness::viewCurrentProductCost($d) * ($row['Quantity_default'] - $row['sys_qty_default'] == 0 ? $row['Quantity_default'] :$row['Quantity_default'] - $row['sys_qty_default']) * $row['default_view_rate'];
                if ($is_export)
                    return CommonFunctions::public_round_number($cost);
                return '<span class="total_cost">' . CommonFunctions::public_round_number($cost) . '</span>';
            });
        }
        $columns [] = array('db' => 'ID',
                            "formatter" => function($d, $row) {
                                $option_array = [
//                                                                        ["title" => CommonLanguage::getMessage("Damage"),
//                                                                                      "class" => "Damage",
//                                                                                      "icon" => "fa-exclamation-triangle",
//                                                                                      "attr" => "data-id='{$d}'",
//                                                                                      "permission" => "depot_content_damage"
//                                                                                     ]
                                ];
                                if ($row['is_expiry'] == 1 || $row['is_lot'] == 1 || $row['is_serial'] == 1) {
                                    $option_array [] = ["title" => CommonLanguage::getMessage("others"),
                                                        "class" => "expiry-btn bg-complete-darker white",
                                                        "icon" => "fa-calendar",
                                                        "attr" => "data-id='{$d}'"
                                                       ];
                                    $html = Forms::action_snippet(["color" => "bg-complete-darker",
                                                                   "isDropDown" => false,
                                                                   "data_id" => $d,
                                                                   "btn-attr" => ($_GET['Depot_ID'] == 0 ? 'disabled' : ''),
                                                                   "ActionOption" => $option_array]);
                                }else{
                                    $html = CommonLanguage::getMessage('noauthactions');

                                }

                                return $html;
                            });


        $columns[] = 'UOM_ID';
        $columns[] = 'Product_UOM';
        $columns[] = 'is_expiry';
        $columns[] = 'default_view_rate';
        $columns[] = 'default_view_uom';
        $columns[] = 'is_lot';
        $columns[] = 'is_serial';
        $columns[] = 'default_uom_name';
        $columns[] = 'sys_qty';
        $columns[] = 'sys_qty_default';

        $key = empty($_GET['Depot_ID']) || $_GET['is_data_collector'] == 1 ? 'ID' : 'cond';
        $table = $_GET['is_data_collector'] == 1 ? 'data_collecter_adjust' : (empty($_GET['Depot_ID']) ? 'depot_content_all' : 'depot_content');
        $data = DataTable::complex($_GET, $table, $key, $columns, ' Status_ID = 1 and is_service <> 1 ' . $cond);

        echo json_encode($data);
    }

    public function DepotContentAjax() {
        if (isset($_GET['DepotID'])) {
            $content = $_GET['DepotID'] == 0 ? $this->_registry->depot->viewItemsForAllStock() : $this->_registry->depot->getDepotContent($_GET['DepotID']);
            die(json_encode($content));
        }
        if (isset($_POST['Products'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $Ret = $this->_registry->depot->setData($_POST)->adjustQuantities();
            die(empty($Ret) ? "OK" : "error");
        }


        //        if (isset($_POST['Damaged_Reason'])) {
        //            $logged_id = Session::getUserID();
        //            $_POST['logged_id'] = Session::getUserID();
        //            $result = $this->_registry->depot->setData($_POST)->addDamagedQuantities();
        //            die(empty($result) ? "OK" : "error");
        //        }

        if (isset($_GET['PID'])) {
            $data = $this->_registry->product->viewProductExpiryQuantity($_GET['PID'], $_GET['CID'], $_GET['DID']);
            die(json_encode($data));
        }
    }

    public function getProductUOM() {

        $data = $this->_registry->product->getUOMByProduct($_GET['pid']);
        die(json_encode($data));
    }

    public function importProducts() {
        $Ret = $this->_registry->product->setData($_POST)->uploadExcelSheet();
        //        die(empty($Ret) ? "OK" : "error");
        die(json_encode($Ret));
    }

    public function adjustmentFiles() {
        $cond = ' type_id = 2';
        $columns = array(
            array('db' => 'file_name', 'dt' => 0),
            array('db' => 'date_time', 'dt' => 1),
            array('db' => 'employee_name', 'dt' => 2),
            array(
                'db' => 'file_id',
                'dt' => 3,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => true, "data_id" => $d,
                                                   "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                                                       "class" => "View",
                                                                       "icon" => "",
                                                                       "href" => "Stock/appAdjustment/{$d}"
                                                                      ],
                                                                      ["title" => CommonLanguage::getMessage("go_adjust"),
                                                                       "class" => "go_adjust",
                                                                       "icon" => "",
                                                                       "permission" => "convert_file_to_adjust",
                                                                       "href" => "Stock/DepotContent/collector/{$d}"
                                                                      ]
                                                                     ]]);
                    return $html;
                }
            )
        );
        $key = 'file_id';
        $table = 'app_files';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function appAdjustment() {

        $cond = ' file_id = "' . smc_escape($_GET['file_id']) . '" ';

        $columns = array(
            array('db' => 'Bar_Code', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1),
            array('db' => 'quantity', 'dt' => 2)
        );
        $key = 'temp_id';
        $table = 'app_temp_adjustments';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function exportAppAdjustment() {
        $data = $this->_registry->depot->exportAppAdjustment($_GET['id']);
    }

    public function ConsumedItemAjax() {
        $start_Date = $_POST['start_Date'];
        $end_Date = $_POST['end_Date'];
        $cat_id = $_POST['Category_ID'];
        $depot_id = $_POST['depot_id'];
        $type_id = $_POST['type_id'];
        $type = $_POST['type'];
        $pur_cat = $_POST['pur_cat'];
        $data = $this->_registry->depot->getConsumedProduct($start_Date, $end_Date, $cat_id, $depot_id, $type, $type_id, $pur_cat);
        die(json_encode($data));
    }

    public function check_product_expiry() {
        $data = $this->_registry->product->check_product_expiry($_GET['id']);
        die(json_encode($data));
    }

    public function searchDamageReason() {
        $data = $this->_registry->depot->setData($_GET)->searchDamageReason($_GET['term']);
        die(json_encode($data));
    }

    public function adjustment_report() {
        $data = $this->_registry->depot->adjustment_report($_GET['date_from'], $_GET['date_to'], $_GET['grouped'], $_GET['depot_id'], $_GET['cat']);
        $html = Forms::build_table_html($data['html']);
        die(json_encode(["html" => $html, "total_cost" => $data['total_cost']]));
    }

    public function multiProductLocation() {
        $cond = '';
        if (!empty($_GET['category_id'])) {
            $cond .= ' and Category_ID = "' . $_GET['category_id'] . '"';
        }
        $_GET['expiry_date_col'] = '';
        $columns = array();
        array_push($columns, 'Product_Code');
        if (smc_session()['default_setting']['activate_search_product_second_code'] == 1) {
            array_push($columns, 'product_second_code');
        }
        array_push($columns, 'Product_Name', 'Bar_Code', 'UOM_Name');
        $columns[] = array('db' => 'Product_ID', "formatter" => function($d, $row) {
            $input = "<input  type='number' min='0' class='QuantityVal' data-product-id='" . $d . "' data-uom-id='" . $row['UOM_ID'] . "' data-is-expiry ='" . (empty($_GET['expiry_date_col']) ? '0' : $row[$_GET['expiry_date_col']]) . "'  >";
            return $input;
        });
        $columns[] = array('db' => 'UOM_ID', "formatter" => function($d, $row) {
            $input = "<input  type='number' min='0' class='CostVal' />";
            return $input;
        });
        if (smc_session()['default_setting']['activate_product_lot_nb'] == 1)
            $columns[] = array('db' => 'is_lot', "formatter" => function($d, $row) {
            return $d == 1 ? "<input  type='text' min='' class='lot_nb form-control' />" : "";
        });
        if (smc_session()['default_setting']['activate_product_serial_nb'] == 1)
            $columns[] = array('db' => 'is_serial', "formatter" => function($d, $row) {
            return $d == 1 ? "<input  type='text' min='' class='serial_nb form-control' />" : "";
        });
        if (smc_session()['default_setting']['activate_expiry_date'] == 1) {
            $_GET['expiry_date_col'] = count($columns);
            $columns[] = array('db' => 'is_expiry', "formatter" => function($d, $row) {
                return $d == 1 ? "<input  type='text' min='' class='expiry_date_picker form-control' />" : "";
            });
        }

        $key = 'current_key';
        $table = 'products_uom';
        $opts = array('order'=>'Product_ID');
        $data = DataTable::complex($_GET, $table, $key, $columns, ' Status_ID = 1  and is_service <> 1 ' . $cond,null,null,$opts);

        echo json_encode($data);
    }
    public function multiProductDamaged() {
        $cond = '';
        if (!empty($_GET['category_id'])) {
            $cond .= ' and Category_ID = "' . $_GET['category_id'] . '"';
        }
        $columns = array();
        array_push($columns, 'Product_Code');
        if (smc_session()['default_setting']['activate_search_product_second_code'] == 1) {
            array_push($columns, 'product_second_code');
        }
        array_push($columns, 'Product_Name', 'Bar_Code', 'UOM_Name');
        $columns[] = array('db' => 'Product_ID', "formatter" => function($d, $row) {
            $input = "<input  type='number' min='0' class='QuantityVal' data-product-id='" . $d . "' data-uom-id='" . $row['UOM_ID'] . "'  >";
            return $input;
        });
        $columns[] = array('db' => 'UOM_ID', "formatter" => function($d, $row) {
            $input = "<input  type='text' min='0' class='damaged_reason' />";
            return $input;
        });
        if (smc_session()['default_setting']['activate_product_lot_nb'] == 1)
            $columns[] = array('db' => 'is_lot', "formatter" => function($d, $row) {
            return $d == 1 ? "<input  type='hidden' min='' class='lot_nb full-width' />" : "";
        });
        if (smc_session()['default_setting']['activate_product_serial_nb'] == 1)
            $columns[] = array('db' => 'is_serial', "formatter" => function($d, $row) {
            return $d == 1 ? "<input  type='hidden' min='' class='serial_nb full-width' />" : "";
        });
        if (smc_session()['default_setting']['activate_expiry_date'] == 1) {
            $_GET['expiry_date_col'] = count($columns);
            $columns[] = array('db' => 'is_expiry', "formatter" => function($d, $row) {
                return $d == 1 ? "<input  type='hidden' min='' class='expiry_date full-width' />" : "";
            });
        }

        $key = 'current_key';
        $table = 'products_uom';
        $opts = array('order'=>'Product_ID');
        $data = DataTable::complex($_GET, $table, $key, $columns, ' Status_ID = 1  and is_service <> 1 ' . $cond,null,null,$opts);

        echo json_encode($data);
    }

    public function multiProductDamagedAjax() {
        //        echo"<pre>";die(print_r($_POST));
        $Ret = $this->_registry->depot->setData($_POST)->add_damage();
        die(empty($Ret) ? "OK" : $Ret[0]);
    }
    public function multiProductAjax() {
        $Ret = $this->_registry->depot->setData($_POST)->addProductLocation();
        die(empty($Ret) ? "OK" : $Ret[0]);
    }

    public function stock_transactions_ajax() {
        $_GET['is_invntry_orgn'] = (!empty($_GET['origin']) && $_GET['origin'] == 'inventory');
        //
        $cond = ' 1=1 ';
        if (!empty($_GET['cat_id']))
            $cond .= ' and Category_ID = "' . $_GET['cat_id'] . '"';
        if (!empty($_GET['product_id']))
            $cond .= ' and Product_ID = "' . $_GET['product_id'] . '"';
        if (!empty($_GET['depot_id']))
            $cond .= ' and Depot_ID = "' . $_GET['depot_id'] . '"';
        if (!empty($_GET['expiry_from']) && !empty($_GET['expiry_to']))
            $cond .= ' and expiry_date between "' . $_GET['expiry_from'] . '" and "' . $_GET['expiry_to'] . '" ';
        if ($_GET['is_invntry_orgn'])
            $cond .= ' and is_current = 1 ';
        $date_cond = "";
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $date_cond = ' and Transaction_Date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '" ';

        $search_arr = array();
        foreach ($_GET['columns'] as $col_indx => $arg) {
            if (!empty($arg['search']['value']))
                $search_arr[] = $arg['search']['value'];
        }
        if (!empty($_GET['search']['value']))
            $search_arr[] = $_GET['search']['value'];
        $_GET['with_balance'] = empty($search_arr) ? 1 : 0;
        $_GET['balance'] = array();
        if ($_GET['with_balance'] == 1) {
            $prev_cond = $cond;
            if (!empty($_GET['from_date'])) {
                $prev_cond .= ' and Transaction_Date < "' . $_GET['from_date'] . '"';
                $query = $this->db->query('select sum(if(Operation_Type="+",1,-1)*(Product_Quantity/uom_rate)) as total_qty,Product_ID
                     from stock_transactions where ' . $prev_cond . ' group by Product_ID');
                while ($row_data = $this->db->assoc($query)) {
                    $_GET['balance'][$row_data['Product_ID']] = $row_data['total_qty'];
                }
            }

            if (!empty($_GET['start'])) {
                $order_cond = '';
                if ($_GET['is_invntry_orgn'])
                    $order_cond .= ' order by Transaction_Date asc ';
                $query = $this->db->query('select (if(Operation_Type="+",1,-1)*(Product_Quantity/uom_rate)) as total_qty,Product_ID
                     from stock_transactions where ' . $cond . $date_cond . $order_cond . '  limit ' . $_GET['start']);
                while ($row_data = $this->db->assoc($query)) {
                    if (!isset($_GET['balance'][$row_data['Product_ID']]))
                        $_GET['balance'][$row_data['Product_ID']] = 0;
                    $_GET['balance'][$row_data['Product_ID']] += $row_data['total_qty'];
                }
            }
        }
        $cond .= $date_cond;
        $columns = array('CODE','Customer_Name','Supplier_Name', 'NAME', 'Transaction_Date');
        if ($this->controller_permission->hasPermission('show_cost_stock_transaction')) {
            $columns[] = array('db' => 'Unit_Cost', "formatter" => function($d,$row) {
                return CommonFunctions::formatNumber(($_GET['currency_id']==1 ? $d : $row['second_currency_cost'])*$row['uom_rate']);
            });
        }
        $columns = array_merge($columns, array(
            array('db' => 'Item_Quantity_Current', 'formatter' => function($d, $row) {
                return $row['Operation_Type'] . ' ' . $d . ' ' . $row['UOM_Name'];
            }),
            array('db' => 'Product_Quantity', 'formatter' => function($d, $row) {
                if (!isset($_GET['balance'][$row['Product_ID']]))
                    $_GET['balance'][$row['Product_ID']] = 0;
                $_GET['balance'][$row['Product_ID']] += ($row['Operation_Type'] == '+' ? 1 : -1) * ($d / $row['uom_rate']);
                return $_GET['with_balance'] == 1 ? (CommonFunctions::formatNumber($_GET['balance'][$row['Product_ID']]) . ' ' . $row['default_view_uom'] ) : '--';
            }),
            array('db' => 'Transaction_Type', 'formatter' => function($d, $row) {
                //                return $row['main_id'];
                $data_source = '';
                if (in_array($row['Transaction_Type_ID'], [2, 11, 43]))
                    $data_source = "Inventory/ViewInvoice/" . $row['main_id'] . "/" . $row['is_actual'] . "?is_pop=1";
                else if (in_array($row['Transaction_Type_ID'], [1, 12, 35]))
                    $data_source = "Inventory/ViewInvoice/vendor/" . $row['main_id'] . "/" . $row['is_actual'] . "?is_pop=1";
                else if (in_array($row['Transaction_Type_ID'], [8, 13, 36]))
                    $data_source = "Inventory/ViewReturnDebit/vendor/" . $row['main_id'] . "?is_pop=1";
                else if (in_array($row['Transaction_Type_ID'], [9, 14, 37]))
                    $data_source = "Inventory/ViewReturnDebit/" . $row['main_id'] . "?is_pop=1";
                else if (in_array($row['Transaction_Type_ID'], [4]))
                    $data_source = "Stock/TransferGoods/" . $row['main_id'];
                //                $data_source = ($row['Transaction_Type_ID'] == 2 || $row['Transaction_Type_ID'] == 11) ?
                //                    "Inventory/ViewInvoice/" . $row['main_id'] . "/" . $row['is_actual'] . "?is_pop=1" :
                //                ($row['Transaction_Type_ID'] == 1 || $row['Transaction_Type_ID'] == 12 ?
                //                 "Inventory/ViewInvoice/vendor/" . $row['main_id'] . "/" . $row['is_actual'] . "?is_pop=1" :
                //                 (($row['Transaction_Type_ID'] == 8 || $row['Transaction_Type_ID'] == 13 ) ?
                //                  "Inventory/ViewReturnDebit/vendor/" . $row['main_id'] . "?is_pop=1" :
                //                  ($row['Transaction_Type_ID'] == 9 || $row['Transaction_Type_ID'] == 14 ?
                //                   "Inventory/ViewReturnDebit/" . $row['main_id'] . "?is_pop=1" :
                //                   "Stock/TransferGoods/" . $row['main_id'])));
                //$available_types = ["1", "2", "4", "8", "9", "11", "12", "13", "14"];
                $trans_type_label = $_GET['is_invntry_orgn'] ? CommonBusiness::get_stock_trans_type($row['main_type']) : $row['Transaction_Type'];
                return empty($data_source) ? $trans_type_label : '<a data-src="' . $data_source . '" class="openFrame"><span>' . $trans_type_label . '</span></a>';
            }),
            'Depot_Name'));
        if (smc_session()['default_setting']['activate_expiry_date'] == 1)
            $columns[] = 'expiry_date';
        if (smc_session()['default_setting']['activate_product_lot_nb'] == 1)
            $columns[] = 'lot_nb';
        if (smc_session()['default_setting']['activate_product_serial_nb'] == 1)
            $columns[] = 'serial_nb';
        $columns = array_merge($columns, array('second_currency_cost','uom_rate','UOM_Name', 'Operation_Type', 'Product_ID', 'Transaction_Type_ID', 'main_id', 'is_actual', 'uom_rate', 'default_view_uom', 'main_type'));

        $key = 'Transaction_ID';
        $table = 'stock_transactions';
        $options = array();
        if ($_GET['is_invntry_orgn']) {
            $options['order'] = 'Transaction_Date asc,date_time asc';
        }
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond,null,null,$options);

        echo json_encode($data);
    }

    public function delete_request() {
        $delete = $this->_registry->depot->delete_request($_POST['ids']);
        die(json_encode(empty($delete[0]) ? ['OK', $delete[1]] : ['error', $delete[0][0]]));
    }

    public function get_total_damaged_cost() {
        $data = $this->_registry->depot->setData($_GET)->get_total_damaged_cost();
        die(json_encode($data));
    }

    public function delete_damage_ajax() {
        $delete = $this->_registry->depot->delete_damage($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function backdated_stock_ajax() {
        $cond = ' where 1=1 ';
        if (!empty($_GET['cat_id']))
            $cond .= ' and p.Category_ID = "' . $_GET['cat_id'] . '"';
        if (!empty($_GET['product_id']))
            $cond .= ' and t.Product_ID = "' . $_GET['product_id'] . '"';
        if (!empty($_GET['depot_id']))
            $cond .= ' and t.Depot_ID = "' . $_GET['depot_id'] . '"';
        if (!empty($_GET['from_date']))
            $cond .= ' and t.Transaction_Date >= "' . $_GET['from_date'] . '"  ';
        if (!empty($_GET['to_date']))
            $cond .= ' and t.Transaction_Date <= "' . $_GET['to_date'] . '" ';

        //        echo $cond.'<br>';

        $columns = array('CODE', 'NAME',
                         array('db' => 'Product_Quantity', "formatter" => function($d, $row) {
                             return CommonFunctions::formatNumber($d) . ' ' . $row['UOM_Name'];
                         }), 'UOM_Name');

        $key = 'Transaction_ID';
        $table = '(select `t`.`Transaction_ID` AS `Transaction_ID`,`t`.`Product_ID` AS `Product_ID`,
            `t`.`Depot_ID` AS `Depot_ID`,
            sum((`t`.`Product_Quantity`/if(p.default_view_uom_id=0,1,p.default_view_rate))*if(Operation_Type="+",1,-1)) AS `Product_Quantity`,
            `t`.`Transaction_Type_ID` AS `Transaction_Type_ID`,`t`.`Transaction_Date` AS `Transaction_Date`,
            `t`.`Logged_ID` AS `Logged_ID`,`t`.`Operation_Type` AS `Operation_Type`,
            `t`.`Exchange_Rate_ID` AS `Exchange_Rate_ID`,`t`.`Item_Quantity_Current` AS `Item_Quantity_Current`,
            `t`.`UOM_ID` AS `UOM_ID`,`t`.`date_time` AS `date_time`,`t`.`is_actual` AS `is_actual`,
            `p`.`Product_Code` AS `CODE`,`p`.`Product_Name` AS `NAME`,`p`.`Category_ID` AS `Category_ID`,
            `u`.`UOM_Name` AS `UOM_Name`,`p`.`Product_Quantity` AS `Total_Quantity` 
            from `tbl_stock_product_transactions` `t` join `tbl_stock_products` `p` 
            on `p`.`Product_ID` = `t`.`Product_ID`  
            join `tbl_stock_uom` `u` on `u`.`UOM_ID` = if(p.default_view_uom_id=0,p.UOM_ID,p.default_view_uom_id)
            ' . $cond . '
            group by t.Product_ID
            order by `t`.`date_time`,`t`.`Transaction_ID`) as temp';
        //        die($table);
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }
    public function add_damage_ajax() {
        $result = $this->_registry->depot->setData($_POST)->add_damage();
        die(json_encode(is_numeric($result[0]) ? ['OK', $result[0]] : $result[0] ));

    }
    public function edit_damage_ajax() {
        $result = $this->_registry->depot->setData($_POST)->edit_damage();
        die(json_encode(is_numeric($result[0]) ? ['OK', $result[0]] : $result[0] ));
    }
    public function damage_list_ajax() {
        $cond = '';
        $from_date = $_GET['From_Date'];
        $to_date = $_GET['To_Date'];
        $depot_id = smc_escape($_GET['depot_id']);
        $cond .= '  current_year_id = "'.$this->year_id.'" 
            and damage_date <= "' . $to_date . '" AND damage_date >= "' . $from_date . '"';
        if ($depot_id !== 'All') {
            $cond .= ' AND Depot_ID = "' . $depot_id . '"';
        }
        if (is_numeric($_GET['customer_id']))
            $cond .= ' and customer_id = "' . $_GET['customer_id'] . '"';
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        $columns = array(
            'damage_num','Customer_Name', 'Depot_Name', 'damage_note', 'damage_date',
            array('db' => 'damage_id',
                  "formatter" => function($d, $row) {
                      if (empty($row['app_damage_id']) && empty($row['return_id'])) {
                          $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => true, "data_id" => $d,
                                                         "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                                                             "class" => "view_damage openFrame",
                                                                             "icon" => "fa-eye",
                                                                             "attr" => "data-src='Stock/view_damage/{$d}?is_pop=1'",
                                                                             "permission" => ($row['is_actual'] ? "view_act_stock_damage":"view_stock_damage"),
                                                                            ],["title" => CommonLanguage::getMessage("delete"),
                                                                             "class" => "delete",
                                                                             "icon" => "fa-trash",
                                                                             "permission" => ($row['is_actual'] ? "delete_act_stock_damage":"delete_stock_damage"),
                                                                            ],
                                                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                                             "class" => "edit",
                                                                             "icon" => "fa-pencil",
                                                                             "href"=>"Stock/add_damage/".($row['is_actual'] ? 'act/' : '').$row['damage_id'],
                                                                             "permission" => ($row['is_actual'] ? "edit_act_stock_damage":"edit_stock_damage"),
                                                                            ]]]);
                      } else {
                          $html = CommonLanguage::getMessage('noauthactions');
                      }
                      return $html;
                  }),'app_damage_id','return_id','is_actual'

        );
        $key = 'damage_id';
        $table = '(select d.*,concat_ws(d.damage_prefix,d.damage_nb) as damage_num,
            ifnull(c.Customer_Name,"") as Customer_Name,dp.Depot_Name
            from tbl_damage d 
            left join tbl_customers c on c.Customer_ID = d.customer_id
            join tbl_stock_depot_warehouse dp on dp.Depot_ID = d.Depot_ID
            order by damage_id desc) as damage';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond,null,null,['order'=>'damage_id desc']);

        echo json_encode($data);
    }

    public function add_assign_ajax() {
        
        $result = !empty($_POST['is_acc']) ? $this->_registry->depot->setData($_POST)->add_stock_acc_adjust(): $this->_registry->depot->setData($_POST)->add_assign();
        die(json_encode(is_numeric($result[0]) ? ['OK', $result[0]] : $result ));
    }
    public function edit_assign_ajax() {
        $result = !empty($_POST['is_acc']) ? $this->_registry->depot->setData($_POST)->edit_stock_acc_adjust(): $this->_registry->depot->setData($_POST)->edit_assign();
        die(json_encode(is_numeric($result[0]) ? ['OK', $result[0]] : $result[0] ));
    }

    public function assign_list_ajax() {
        $cond = '';
        $from_date = $_GET['From_Date'];
        $to_date = $_GET['To_Date'];
        $depot_id = smc_escape($_GET['depot_id']);
        $cond .= '  current_year_id = "'.$this->year_id.'" 
            and assign_date <= "' . $to_date . '" AND assign_date >= "' . $from_date . '"';
        if ($depot_id !== 'All') {
            $cond .= ' AND Depot_ID = "' . $depot_id . '"';
        }
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        if (isset($_GET['assign_type']))
            $cond .= ' and assign_type = "' . $_GET['assign_type'] . '"';
        $columns = array(
            'assign_nb', 'Depot_Name', 'assign_note', 'assign_date',
            array('db' => 'assign_id',
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => true, "data_id" => $d,
                                                     "ActionOption" => [
                                                                        ["title" => CommonLanguage::getMessage("view"),
                                                                            "class" => "view_adjust openFrame",
                                                                            "icon" => "fa-eye",
                                                                            "attr" => "data-src='Stock/View_adjust/{$d}?is_pop=1'",
                                                                            "permission" => "view_adjust_product_quantity",
                                                                        ],
                                                                        ["title" => CommonLanguage::getMessage("delete"),
                                                                         "class" => "delete",
                                                                         "icon" => "fa-trash",
                                                                         "permission" => ($row['is_actual'] ? ($row['assign_type'] ? "delete_act_adjust_product_quantity" : "delete_act_assign_product_quantity"):($row['assign_type'] ? "delete_adjust_product_quantity":"delete_assign_product_quantity")),
                                                                        ],
                                                                        ["title" => CommonLanguage::getMessage("Edit"),
                                                                         "class" => "edit",
                                                                         "icon" => "fa-pencil",
                                                                         "href"=>"Stock/add_assign/".($row['is_actual'] ? 'act/' : '').($row['assign_type'] ? 'adj/' : '').$row['assign_id'],
                                                                         "permission" => ($row['is_actual'] ? ($row['assign_type'] ? "edit_act_adjust_product_quantity" : "edit_act_assign_product_quantity"):($row['assign_type'] ? "edit_adjust_product_quantity":"edit_assign_product_quantity")),
                                                                        ]]]);

                      return $html;
                  }),'is_actual','assign_type'

        );
        $key = 'assign_id';
        $table = '(select d.*,dp.Depot_Name
            from tbl_assign_product d 
            join tbl_stock_depot_warehouse dp on dp.Depot_ID = d.Depot_ID
            order by assign_id desc) as assign';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond,null,null,['order'=>'assign_id desc']);

        echo json_encode($data);
    }
    public function delete_assign_ajax() {
        $delete = $this->_registry->depot->delete_assign($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }
    public function request_transfer_details_report() {
        $cond = '1=1';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and (Request_Date between "' . smc_escape($_GET['from_date']) . '" and "' . smc_escape($_GET['to_date']) . '" )  ';
        if (!empty($_GET['is_request'])){// is request
            $cond .= ' and Status_ID <> 3';
        }else{//is transfer
            $cond .= ' and Status_ID = 3';  
        }
        if (is_numeric($_GET['customer_id'])){
            $cond .= ' and customer_id =  "'.$_GET['customer_id'].'"';
        }
        if(!empty($_GET['from_depot_id'])){
            $cond .= ' and '.(!empty($_GET['is_request']) ? 'Request_From' : 'Request_To').' =  "'.$_GET['from_depot_id'].'"';
        }
        if(!empty($_GET['to_depot_id'])){
            $cond .= ' and '.(!empty($_GET['is_request']) ? 'Request_To' : 'Request_From').' =  "'.$_GET['to_depot_id'].'"';
        }
        if (!empty($_GET['current_origin']) && $_GET['current_origin'] == 1){
            $cond .= ' and ticketing_id is not null';
        }
        $columns = array('req_nb','Product_Name','UOM_Name');
        if (!empty($_GET['is_request'])) {
            $columns[] = 'depot_from';
            $columns[] = 'depot_to';
            $columns[] = array('db' => 'Status_ID',
                               'formatter' => function($d) {
                                   $Statuses = [StatusCodes::getStatus(19) . "#label-inverse", StatusCodes::getStatus(20) . "#label-warning", StatusCodes::getStatus(21) . "#label-info", StatusCodes::getStatus(22) . "#label-danger"];
                                   return '<span class="label ' . explode("#", $Statuses[$d-1])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d-1])[0] . '</span>';
                               });
        } else {
            $columns[] = 'depot_to';
            $columns[] = 'depot_from';
        }
        $columns[] = 'Request_Date';
        $columns[] = 'Current_Quantity';
        $columns[] = 'Customer_Name';

        $key = 'Entry_ID';
        $table = 'transfer_details_list';
        $data = DataTable::complex($_GET, $table, $key, $columns,$cond);

        echo json_encode($data);
    }
      public function confirm_delivered_items_ajax() {
            $result = $this->_registry->depot->setData($_POST)->confirm_delivered_items();
            die(empty($result) ? 'OK' : $result[0]);
    }
    
     public function transfered_delivered_items_ajax() {
        $cond = ' and r.Status_ID = 3';
        if (!empty($_GET['date_from']) && !empty($_GET['date_to']))
            $cond .= ' and (Request_Date between "' . smc_escape($_GET['date_from']) . '" and "' . smc_escape($_GET['date_to']) . '" )  ';
        
       
        if(!empty($_GET['from_depot'])){
            $cond .= ' and Request_To =  "'.$_GET['from_depot'].'"';
        }
        if(!empty($_GET['to_depot'])){
            $cond .= ' and Request_From =  "'.$_GET['to_depot'].'"';
        }
      
     $_GET['tmp__all_ids'] = array();
        $columns = array('transfer_nb','from_depot','to_depot','Product_Code','Product_Name','Current_Quantity',
            'delivered_current_qty','UOM_Name','delivered_note',
            array('db'=>'Entry_ID','formatter'=>function($d){
                return $_GET['tmp__all_ids'][$d];
            }));
     
        if(!empty($_GET['type_filter'])){
            if($_GET['type_filter']==1)
                $cond.=' and (d.Current_Quantity-d.delivered_current_qty) =0 ';
            else if($_GET['type_filter']==2)
                $cond.=' and (d.Current_Quantity-d.delivered_current_qty) >0 ';
        }
        $key = 'Entry_ID';
        $table = '( select d.Entry_ID,concat_ws(serial_prefix,Request_Number) as transfer_nb,
            p.Product_Code,p.Product_Name,from_dep.Depot_Name as from_depot,to_dep.Depot_Name as to_depot,
            d.Current_Quantity,d.delivered_current_qty,d.delivered_note,u.UOM_Name
            from tbl_stock_request_details d join tbl_stock_request r on r.Request_ID = d.Request_ID
            join tbl_stock_products p on p.Product_ID = d.Product_ID
            join tbl_stock_uom u on u.UOM_ID = d.Request_UOM
            join tbl_stock_depot_warehouse from_dep on from_dep.Depot_ID = r.Request_To
            join tbl_stock_depot_warehouse to_dep on to_dep.Depot_ID = r.Request_From
            where 1=1 '.$cond.' group by d.Entry_ID) as temp';
        $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'trans_del_ftch_row']]
            , 'fetch_all_callback' => ['ft' => [$this, 'trans_del_ftch_all']]];
        $data = DataTable::complex($_GET, $table, $key, $columns,null,null,null,$row_cb);

        echo json_encode($data);
    }
    public function trans_del_ftch_row(&$data, &$row) {

        $_GET['tmp__all_ids'][$row['Entry_ID']] = '';
    }

    public function trans_del_ftch_all(&$data) {
        if (empty($_GET['tmp__all_ids']))
            return true;
          $query = $this->db->query('select criteria.Entry_ID,
                    criteria_main.criteria_name,criteria.criteria_note,
                    group_concat(crit_detail.criteria_detail_name SEPARATOR ",") as TAG
             from tbl_request_product_criteria criteria 
             left join tbl_product_criteria_detail crit_detail on crit_detail.criteria_detail_id=criteria.criteria_detail_id
             left join tbl_product_criteria criteria_main on criteria_main.criteria_id = crit_detail.criteria_id
             where  criteria.Entry_ID in (' . (implode(',',array_keys($_GET['tmp__all_ids']))) . ')
              group by criteria.Entry_ID,crit_detail.criteria_id');
        while ($row = $this->db->assoc($query)) {
            $tag =  $_GET['tmp__all_ids'][$row['Entry_ID']];
            $_GET['tmp__all_ids'][$row['Entry_ID']] .= (empty($tag) ? '' : '<br>') . ('<strong>'.$row['criteria_name'] . ':</strong> ' . $row['TAG']);
        }

    }
     public function stock_acc_adjust_list_ajax() {
        $cond = '';
        $from_date = $_GET['From_Date'];
        $to_date = $_GET['To_Date'];
        $depot_id = smc_escape($_GET['depot_id']);
        $cond .= '  current_year_id = "'.$this->year_id.'" 
            and adjust_date <= "' . $to_date . '" AND adjust_date >= "' . $from_date . '"';
        if ($depot_id !== 'All') {
            $cond .= ' AND depot_id = "' . $depot_id . '"';
        }
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        $columns = array(
            'adjust_nb', 'Depot_Name', 'note', 'adjust_date','debit_acc_name','credit_acc_name',
            array('db' => 'adjust_id',
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(["color" => "complete-darker", "isDropDown" => true, "data_id" => $d,
                                                     "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                                                         "class" => "delete",
                                                                         "icon" => "fa-trash",
                                                                         "permission" => ($row['is_actual'] ? "delete_act_stock_acc_adjust" : "delete_stock_acc_adjust"),
                                                                        ],
                                                                        ["title" => CommonLanguage::getMessage("Edit"),
                                                                         "class" => "edit",
                                                                         "icon" => "fa-pencil",
                                                                         "href"=>"Stock/add_assign/acc/".($row['is_actual'] ? 'act/' : '').$row['adjust_id'],
                                                                         "permission" => ($row['is_actual'] ? "edit_act_stock_acc_adjust" : "edit_stock_acc_adjust"),
                                                                        ]]]);

                      return $html;
                  }),'is_actual'

        );
        $key = 'adjust_id';
        $table = '(SELECT d.adjust_date,adjust_nb,adjust_id,note,is_actual,current_year_id,dp.Depot_Name,cu.*,
            concat_ws(" - ",da.Account_Code,da.Account_Name) as debit_acc_name,
            concat_ws(" - ",ca.Account_Code,ca.Account_Name) as credit_acc_name
            FROM `tbl_stock_acc_adjustment` d 
            join tbl_stock_depot_warehouse dp on dp.Depot_ID = d.depot_id
            join tbl_common_currency cu on cu.Currency_ID = d.Currency_ID
            join tbl_chart_of_accounts da on da.Account_ID = d.debit_acc_id
            join tbl_chart_of_accounts ca on ca.Account_ID = d.credit_acc_id
            order by adjust_id desc) as adjust';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond,null,null,['order'=>'adjust_id desc']);

        echo json_encode($data);
    }
    public function delete_stock_acc_adjust_ajax() {
        $delete = $this->_registry->depot->delete_stock_acc_adjust($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }
}
