<?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 InventoryAjax
 *
 * @author 
 */
class InventoryAjax extends mainController {

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

    public function landing() {
        
    }

    public function InvoiceListRequests() {
        //        $IsVendor = true;
        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        $IsVendor = ($_GET['IsVendor'] == 'true') ? true : false;
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and Date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }

        if (is_numeric($_GET['customer_supplier_id'])) {
            $customer_supplier_id = $_GET['customer_supplier_id'];
            $cond .= ' and Person_ID = "' . $customer_supplier_id . '"';
            if (!empty($_GET['customer_branch_id']) && !$IsVendor)
                $cond .= ' and customer_branch_id = "' . $_GET['customer_branch_id'] . '"';
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['branch_id']) ? ' and branch_id ="' . ($_GET['branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        if (!empty($_GET['class_id'])) {
            $cond .= ' and current_class_id = "' . $_GET['class_id'] . '"';
        }
        if (!empty($_GET['group_id'])) {
            $cond .= ' and current_group_id = "' . $_GET['group_id'] . '"';
        }
        if (!empty($_GET['salesman_id']) && $_GET['IsVendor'] != "true") {
            $cond .= ' and Sales_ID = "' . $_GET['salesman_id'] . '"';
        }
        if (!empty($_GET['depot_id'])) {
            $cond .= ' and Depot_ID = "' . $_GET['depot_id'] . '"';
        }
        if ($_GET['print_filter'] !== '')
            $cond .= ' and is_printed_invoice = "' . $_GET['print_filter'] . '"';

        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        if (!empty($_GET['product_id'])) {
            if ($_GET['IsVendor'] === "true") {
                $cond .= ' and  ID_Auto in (SELECT `Purchase_ID_Auto` FROM `tbl_inventory_purchase_items` where Product_ID ="' . $_GET['product_id'] . '" ) ';
            } else {
                $cond .= ' and  ID_Auto in (SELECT `Invoice_ID_Auto` FROM `tbl_invoice_products_details` where Product_ID ="' . $_GET['product_id'] . '" ) ';
            }
        }
        if (isset($_GET['is_noqty']) && $IsVendor)
            $cond .= ' and disable_qty = "' . $_GET['is_noqty'] . '"';
        if (!empty($_GET['invoice_type_id']) && !$IsVendor)
            $cond .= ' and invoice_type_id = "' . $_GET['invoice_type_id'] . '"';

        if (!empty($_GET['is_converted'])) {
            if ($_GET['is_converted'] == 1) {
                $cond .= ' and ID_Auto not in (SELECT `purchase_id` FROM `tbl_inventory_delivery_report` ) ';
            } else {
                $cond .= ' and ID_Auto  in (SELECT `purchase_id` FROM `tbl_inventory_delivery_report` ) ';
            }
        }
        if(!empty($_GET['search_note'])){
            $cond.=' and inv_desc like "%'.$_GET['search_note'].'%" ';
        }
        $user_id =smc_session()['user_details']['User_ID'];
        if (smc_session()['user_details']['limit_customer_invoice'] == 1) {
            $cond .= ' and Logged_ID = '.$user_id.'';
        }
        $columns = array(
            array('db' => 'ID', "formatter" => function($d, $row) {
                    if ((($_GET['IsVendor'] != "true" && empty($row['is_branch_transfer']) && empty($row['invoice_app_id']) && empty($row['exchange_id'])) || $_GET['IsVendor'] === "true") && empty($row['return_ids']) && empty($row['subscription_fees_id']) && empty($row['ticketing_id'])) {
                        return '<input type="checkbox" data-id="' . $row['ID_Auto'] . '" data-nb="' . $d . '" data-total="' . $row['local_net_total'] . '" class="inv_del_td pull-left multi_delete"/>' . $d;
                    } else
                        return $d;
                }),
            array('db' => 'Name', 'dt' => 1, "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }), 'Date', 'Due_Date', 'user_ref',
            array('db' => 'current_vat', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'shipping_fees', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'current_sub_total', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'current_net_total', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'ID', 'formatter' => function( $d, $row) {
                    if (empty($row['reason_id'])) {
                        $option_arr = [["title" => CommonLanguage::getMessage("view"),
                        "class" => "View openFrame",
                        "permission" => ($_GET['IsVendor'] === 'true' ? ($_GET['is_actual'] == 1 ? ($_GET['is_noqty'] ? "view_actual_purchase_noqty" : "ViewPurchaseInvoiceActual") : ($_GET['is_noqty'] ? "view_purchase_noqty" : "ViewPurchaseInvoice")) : ($_GET['is_actual'] == 1 ? "ViewSalesInvoiceActual" : "ViewSalesInvoice")),
                        "icon" => "fa-eye",
                        "attr" => "data-src='Inventory/ViewInvoice/" . ($_GET['IsVendor'] === 'true' ? 'vendor/' : '') . "{$row['ID_Auto']}/{$row['Person_ID']}?is_pop=1'"
                            ], ["title" => CommonLanguage::getMessage("copy"),
                                "class" => "copy",
                                "permission" => $_GET['IsVendor'] === 'true' ? ($_GET['is_actual'] == 1 ? ($_GET['is_noqty'] == 1 ? 'copy_act_purchase_invoice_noqty' : "copy_act_purchase_invoice") : ($_GET['is_noqty'] == 1 ? 'copy_purchase_invoice_noqty' : "copy_purchase_invoice")) : ($_GET['is_actual'] == 1 ? "copy_act_sales_invoice" : "copy_sales_invoice"),
                                "icon" => "fa-copy",
                                "href" => "Inventory/addpurchase/" . ($_GET['IsVendor'] === 'true' ? '' : 'sales/') . ($_GET['is_actual'] == 1 ? 'act/' : '') . ($_GET['is_noqty'] == 1 ? 'noqty/' : '') . "copy/{$row['ID_Auto']}"
                        ]];
                        if ($row['shipping_status_id'] < 2 && empty($row['sales_purchase_id']) && empty($row['exchange_id']) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {
                            $option_arr[] = ["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "Edit",
                                "permission" => $_GET['IsVendor'] === 'true' ? ($_GET['is_actual'] == 1 ? ($_GET['is_noqty'] == 1 ? 'editPurchaseActual_noqty' : "editPurchaseActual") : ($_GET['is_noqty'] == 1 ? 'editPurchase_noqty' : "editPurchase")) : ($_GET['is_actual'] == 1 ? "editInvoiceActual" : "editInvoice"),
                                "icon" => "fa-pencil",
                                "href" => "Inventory/addpurchase/" . ($_GET['IsVendor'] === 'true' ? '' : 'sales/') . ($_GET['is_actual'] == 1 ? 'act/' : '') . ($_GET['is_noqty'] == 1 ? 'noqty/' : '') . "{$row['ID_Auto']}"
                            ];

                            //                    if ($_GET['IsVendor'] != 'true') {
                            if ((($_GET['IsVendor'] != "true" && empty($row['is_branch_transfer']) && empty($row['sales_purchase_id']) && empty($row['exchange_id'])) || $_GET['IsVendor'] === "true") && empty($row['return_ids'])) {
                                $option_arr[] = ["title" => CommonLanguage::getMessage("delete"),
                                    "class" => "delete_inv",
                                    "attr" => "data-invoice-app-id='{$row['invoice_app_id']}'   data-ticketing-id='{$row['ticketing_id']}'  data-subscription-fees-id='{$row['subscription_fees_id']}'",
                                    "permission" => $_GET['is_actual'] == 1 ? ($_GET['IsVendor'] != "true" ? "DeleteSalesInvoiceActual" : ($_GET['is_noqty'] == 1 ? 'delete_act_purchase_invoice_noqty' : "delete_act_purchase_invoice")) : ($_GET['IsVendor'] != "true" ? "DeleteSalesInvoice" : ($_GET['is_noqty'] == 1 ? 'delete_purchase_invoice_noqty' : "delete_purchase_invoice")),
                                    "icon" => "fa-trash"];
                                if (empty($row['invoice_app_id']) && empty($row['ticketing_id']) && empty($row['subscription_fees_id'])) {
                                    $option_arr[] = ["title" => CommonLanguage::getMessage($_GET['is_actual'] == 1 ? "to_official" : "to_actual"),
                                        "class" => "change_actual",
                                        "permission" => $_GET['IsVendor'] === "true" ? ($_GET['is_actual'] == 1 ? ($_GET['is_noqty'] == 1 ? 'pur_to_official_noqty' : 'pur_to_official') : ($_GET['is_noqty'] == 1 ? 'pur_to_actual_noqty' : 'pur_to_actual')) : ($_GET['is_actual'] == 1 ? "inv_to_official" : "inv_to_actual"),
                                        "icon" => "fa-retweet"];
                                }
                            }
                            if ($_GET['IsVendor'] == 'true') {
                                $option_arr[] = ["title" => CommonLanguage::getMessage("adjust_prices"),
                                    "class" => "adjust_prices openFrame",
                                    "attr" => "data-src='Inventory/PricingList?is_pop=1&id=" . $row['ID_Auto'] . "'",
                                    "permission" => $_GET['is_actual'] == 1 ? ($_GET['is_noqty'] == 1 ? "act_adjust_prod_prices_noqty" : "act_adjust_prod_prices") : ($_GET['is_noqty'] == 1 ? "adjust_prod_prices_noqty" : "adjust_prod_prices"),
                                    "icon" => "fa-usd"];
                            }
                            if ($_GET['IsVendor'] != 'true') {
                                $option_arr[] = ["title" => CommonLanguage::getMessage("invoice_profit"),
                                    "class" => "invoice_profit openFrame",
                                    "attr" => "data-src='Inventory/ItemProfit?is_pop=1&Invoice_ID_Auto=" . $row['ID_Auto'] . "'",
                                    "permission" => $_GET['is_actual'] == 1 ? "act_invoice_profit" : "invoice_profit",
                                    "icon" => "fa-usd"];
                                $option_arr[] = ["title" => CommonLanguage::getMessage("transfer"),
                                    "class" => "transfer_inv openFrame",
                                     "href" => "Stock/RequestOrder/transfer/invoice/" . $row['ID_Auto'],
                                    "permission" => $_GET['is_actual'] == 1 ? "act_inv_transfer_invoice" : "inv_transfer_invoice",
                                    "icon" => "fa-exchange"];
                            }
                            if ($_GET['IsVendor'] === 'true' && $_GET['is_noqty']) {
                                $option_arr[] = ["title" => CommonLanguage::getMessage("delivery_note"),
                                    "class" => "delivery_note go_delivery",
                                    "attr" => "link='Inventory/DeliveryNote/vendor/pur/" . $row['ID_Auto'] . "'",
                                    "permission" => $_GET['is_actual'] == 1 ? "act_pur_noqty_to_delivery" : "pur_noqty_to_delivery",
                                    "icon" => "fa-truck"];
                            }
                        }
                        //                    }
                        $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $row['ID_Auto'],
                                    "ActionOption" => $option_arr]);
                        return $html;
                    } else {
                        return CommonLanguage::getMessage('void');
                    }
                }), 'ID_Auto', 'Person_ID', 'sales_purchase_id', 'table_id', 'is_branch_transfer', 'invoice_app_id',
            'exchange_id', 'local_net_total', 'Currency_Symbol', 'is_main_transfer', 'subscription_fees_id',
            'shipping_status_id', 'reason_id', 'return_total', 'return_paid_amount', 'return_ids', 'ticketing_id');
        $table_view = $IsVendor ? 'purchase_invoice_list' : 'sales_invoice_list';
        if (!$IsVendor && $_GET['is_pending'] == 0)
            $cond .= ' and is_committed = 1';
        $key = '(@cnt := @cnt + 1)';
        $table = $table_view . '  CROSS JOIN (SELECT @cnt := 0) AS dummy';
        //                $key = 'ID';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    //ActualNewInvoice.php
    public function ActualNewInvoiceRequest() {
        if (isset($_POST["Supplier_ID"]) && isset($_POST["Purchase_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $purchase_insert = $this->_registry->purchase->setData($_POST)->createActualInvoice();
            die(json_encode(is_numeric($purchase_insert) ? ['OK', $purchase_insert] : $purchase_insert[0] ));
        }
        if (isset($_POST["Customer_ID"]) && isset($_POST["Invoice_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $insert = $this->_registry->invoice->setData($_POST)->createActualInvoice();
            die(json_encode(is_numeric($insert) ? ['OK', $insert] : $insert[0] ));
        }
    }

    public function ActualSalesInvoice() {
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            $invoiceType = $_GET['invoiceType'];
            $all_uom = $this->_registry->material->getMaterialUOM();
            if ($invoiceType == 0) {
                $purchaseTotal = $this->_registry->purchase->getPurchaseAct($id);
                $Purchase_Details = $this->_registry->purchase->getPurchaseActDetails($id);
            } else {
                $purchaseTotal = $this->_registry->invoice->viewInvoiceAct($id);
                $Purchase_Details = $this->_registry->invoice->getInvoicesActDetails($id);
            }
            die(json_encode([$purchaseTotal, $Purchase_Details, $all_uom]));
        }
        if (isset($_POST["Supplier_ID"]) && isset($_POST["Purchase_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $purchases = $this->_registry->purchase->setData($_POST)->createActualInvoice();
            die(empty($purchases) ? "OK" : $purchases[0]);
        }
        if (isset($_POST["Customer_ID"]) && isset($_POST["Invoice_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->invoice->setData($_POST)->createActualInvoice();
            ob_clean();
            die(empty($result) ? "OK" : $result[0]);
        }
    }

    public function CustomerListRequest() {
        $compare_balance = $_GET['compare_balance'];
    
        $cond = ' 1=1 ';
        $_GET['symbol'] = smc_session()['local_currency_symbol'];
        $customer_ids_array = array();
        if (!empty($_GET['salesman_id'])) {
            $query_customer_ids = $this->db->query('select customer_id from tbl_salesman_customers where  employee_id = "' . $_GET['salesman_id'] . '"');
            while ($row = $this->db->assoc($query_customer_ids)) {
                $customer_ids_array[] = $row['customer_id'];
            }
            if (!empty($customer_ids_array))
                $cond .= ' and ID in (' . implode(',', $customer_ids_array) . ') ';
            else
                $cond .= ' and 1 = 2';
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        if (is_numeric($_GET['status_id']))
            $cond .= ' and Status_ID ="' . $_GET['status_id'] . '"';
        if (!empty($_GET['customer_address']) && empty($_GET['IsVendor']))
            $cond .= ' and Address LIKE "' . $_GET['customer_address'] . '"';

        $Employee_ID  =  smc_session()['user_details']['Employee_ID'];
        if (smc_session()['user_details']['limit_customer_invoice'] == 1) {
            $cond .= ' and employee_id ="'. $Employee_ID.'"';
        }
  
        if ($compare_balance == '>') {
            $cond .= ' and balance >"' . $_GET['search_balance'] . '"';
        }
        else if ($compare_balance == '<') {
            $cond .='  and balance <"' . $_GET['search_balance'] . '"';
        }
        else if ($compare_balance == '=') {
            $cond .= ' and balance = "' . $_GET['search_balance'] . '"';
        }

 
        $columns = array('Account_Code', 'Name', 'branch_name', 'Company',
            array('db' => 'ID', 'dt' => 4,
                'formatter' => function($d) {
                    $total = Forms::DecimalNumber(isset($_GET['IsVendor']) ? $this->_registry->vendor->viewSupplierSumPurchases($d) : $this->_registry->customer->viewCustomerSumSales($d));
                    $symbol = CurrencyFactory::getDefaultCurrencySymbol();
                    return $total . ' ' . (isset($_GET['IsVendor']) ? smc_session()['local_currency_symbol'] : $symbol);
                }),
            array('db' => 'balance', 'dt' => 5,
                'formatter' => function($d, &$row) {
                    $total = isset($_GET['IsVendor']) ? $this->_registry->vendor->returnBalanceByAccount($row['ID']) : (smc_session()['default_setting']['activate_customer_list_balances'] == 1 ? $d : $this->_registry->customer->return_customer_all_balances($row['ID'])[$this->controller_permission->hasPermission('show_actual_balance') ? 'balance' : 'off_balance']);
                    $row['balance'] = $total;
                    $symbol = (smc_session()['default_setting']['activate_customer_list_balances'] == 1 && !isset($_GET['IsVendor'])) ? (smc_session()['default_setting']['customer_balance_in_second_currency'] == 1 ? smc_session()['second_currency']['symbol'] : smc_session()['local_currency_symbol']) : CurrencyFactory::getDefaultCurrencySymbol();
                    return Forms::DecimalNumber($total) . ' ' . (isset($_GET['IsVendor']) ? smc_session()['local_currency_symbol'] : $symbol);
                }),
            array('db' => 'Customer_Mobile', 'dt' => 6),
            array('db' => 'Address', 'dt' => 7),
            array('db' => 'Status_ID', 'dt' => 8, 'formatter' => function( $d, $row, $excel ) {
                    return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
                }),
            array(
                'db' => 'ID',
                'dt' => 9,
                'formatter' => function( $d, $row ) {
                    $actions = [["title" => CommonLanguage::getMessage("invoices"),
                    "class" => "Invoice",
                    "icon" => "fa-list",
                    "permission" => (!empty($_GET['IsVendor']) ? 'VendorList' : 'CustomerList'),
                    "href" => "Inventory/VendorList/" . (isset($_GET['IsVendor']) ? 'vendor/' : '') . "{$d}"
                        ],
                        ["title" => CommonLanguage::getMessage("view"),
                            "class" => "View",
                            "icon" => "fa-eye",
                            "permission" => (!empty($_GET['IsVendor']) ? 'ViewVendor' : 'viewCustomer'),
                            "href" => "Inventory/" . (isset($_GET['IsVendor']) ? 'viewVendorDetails' : 'viewCustomerDetails') . "/{$d}"
                        ],
                        ["title" => CommonLanguage::getMessage($row[7] == 1 ? 'disable' : 'enable'),
                            "class" => "disable_enable_item",
                            "icon" => "fa-" . ($row[7] == 1 ? 'lock' : 'unlock'),
                            "data-target" => "#enable-disable-modal",
                            "attr" => "data-id={$row[7]}",
                            "permission" => isset($_GET['IsVendor']) ? "disable_enable_supplier" : "disable_enable_customer"
                        ],
                        ["title" => CommonLanguage::getMessage('view_general_ledger'),
                            "class" => "openFrame",
                            "icon" => "fa-eye",
                            "attr" => "data-src='ACC/ledger?is_pop=1/" . $row[0] . "'",
                            "permission" => "ledger"
                        ],
                        ["title" => CommonLanguage::getMessage('actual_general_ledger'),
                            "class" => "openFrame",
                            "icon" => "fa-eye",
                            "attr" => "data-src='ACC/ledger/act?is_pop=1/" . $row[0] . "'",
                            "permission" => "ActualLedger"
                        ],
                    ];
                    if (!isset($_GET['IsVendor'])) {
                        $actions [] = ["title" => CommonLanguage::getMessage("change_password"),
                            "data-target" => "#change-customer-password-modal",
                            "class" => "change_customer_password",
                            "icon" => "fa-key"
                        ];
                        $actions [] = ["title" => CommonLanguage::getMessage("print_id"),
                            "attr" => "data-id={$d} data-code={$d}",
                            "permission" => "print_customer_id",
                            "class" => "print_qrcode",
                            "icon" => "fa-print"
                        ];
                        $actions [] = ["title" => CommonLanguage::getMessage("print_code"),
                            "attr" => "data-id={$d} data-code={$row['Customer_Code']}",
                            "permission" => "print_customer_code",
                            "class" => "print_qrcode",
                            "icon" => "fa-print"
                        ];
                    }
                    if (smc_session()['default_setting']['sync_type'] != 2) {
                        $actions [] = ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "openFrame",
                            "icon" => "fa-pencil",
                            "attr" => "data-src='Inventory/" . (isset($_GET['IsVendor']) ? "viewVendorDetails" : "viewCustomerDetails") . "/{$d}?is_pop=1&modal=1'",
                            "permission" => isset($_GET['IsVendor']) ? "edit_vendor" : "edit_customer"
                        ];
                        if ($row['ID'] > 0) {
                            $actions [] = ["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash"
                            ];
                        }
                    }
                    $html = Forms::action_snippet(["color" => "primary",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => $actions]);
                    return $html;
                }
            )
        );

        if (!isset($_GET['IsVendor']))
            $columns[] = 'Customer_Code';
        $key = 'ID';
        if (isset($_GET['IsVendor']))
            $table = 'supplier_list';
        else {
            if (smc_session()['default_setting']['activate_customer_list_balances'] == 1) {
                $balance = smc_session()['default_setting']['customer_balance_in_second_currency'] == 1 ? '(t.Transaction_Amount*t.second_currency_rate)' : '`t`.`local_amount`';
                $table = "(select `c`.`Customer_Code` AS `Customer_Code`,`c`.`Customer_ID` AS `ID`,`c`.`branch_id` AS `branch_id`,
                    `c`.`Customer_Name` AS `Name`,`c`.`Customer_Company` AS `Company`,
                    `c`.`Customer_Mobile` AS `Customer_Mobile`,`c`.`Customer_Address` AS `Address`,
                    `ca`.`Account_Code` AS `Account_Code`,`c`.`Status_ID` AS `Status_ID`,
                    `org`.`branch_name` AS `branch_name`,
                    sum((" . $balance . " * if((`t`.`Transaction_Type` = 'Debit'),1,-(1)))) AS `balance`,
                    `t`.`current_year_id` AS `current_year_id` from `tbl_customers` `c` 
                    join `tbl_chart_of_accounts` `ca` on `ca`.`main_id` = `c`.`Customer_ID`
                    and (`ca`.`main_type` = 'cust') and (`ca`.`sub_type` = 'main')
                    left join `tbl_common_currency` `cu` on `c`.`Currency_ID` = `cu`.`Currency_ID`
                    left join `tbl_accounting_transactions` `t` on `t`.`Account_ID` = `ca`.`Account_ID`
                    left join `tbl_organization_branches` `org` on `c`.`branch_id` = `org`.`branch_id`
                    and current_year_id = '" . $this->year_id . "'
                    group by `ca`.`Account_ID`) as dummy";
            } else {
                $table = 'customer_list';
            }
        }

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function deleteCustomerAjax() {
        if (isset($_GET["GetCustomerID"])) { // to update Status of delete 
            $logged_id = Session::getUserID();
            $Customer_ID = $_GET["GetCustomerID"];
            $delete_customer = $this->_registry->customer->deleteCustomer($Customer_ID);
            die(empty($delete_customer) ? "OK" : ($delete_customer[0] == "check_customer" ? CommonLanguage::getMessage("check_customer") : $delete_customer[0]));
        }
    }

    public function getcities() {
        if (!isset($_GET["countryId"]))
            die("error");
        $C = new Countries;
        die(json_encode($C->getCities($_GET["countryId"])));
    }

    public function DeliveryNoteRequest() {
        if (isset($_POST["Products"])) {
            $insert = $this->_registry->delivery->setData($_POST)->add_delivery_note();
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0]] : $insert[0] ));
        }
    }

    public function EditDeliveryNoteRequest() {
        if (isset($_POST["Products"])) {
            $insert = $this->_registry->delivery->setData($_POST)->edit_delivery_note($_POST['Delivery_Report_ID']);
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0]] : $insert[0] ));
        }
    }

    public function EditCustomerRequest() {
        if (isset($_POST["Customer_Name"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->customer->setData($_POST)->updateCustomer();
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }

    public function EditOrderRequest() {
        if (isset($_POST['Customer_ID']) && isset($_POST['Sales_Order_ID'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $sales_id = $_POST['Sales_Order_ID'];
            $result = $this->_registry->LoadingOrder->setData($_POST)->updateSalesOrder($sales_id);
            if ($result)
                die("ok");
            die("error");
        }
    }

    public function SalesOrderListRequest() {
        if (isset($_GET['code_id'])) {
            $code = $_GET['code_id'];
            $SalesOrderDetail = $this->_registry->LoadingOrder->getSalesOrder($code);
            die(json_encode($SalesOrderDetail));
        }
        if (isset($_GET['Sale_Order_Date'])) {
            $currentdate = $_GET['Sale_Order_Date'];
            $Ret = $this->_registry->LoadingOrder->viewSalesOrder($currentdate);
            die(json_encode($Ret));
        }
        if (isset($_GET['GetID'])) {
            $id = $_GET['GetID'];
            $deleteOrder = $this->_registry->LoadingOrder->deleteSalesOrder($id);
            die(json_encode($deleteOrder));
        }
        if (isset($_GET['SalesID'])) {
            $SalesInfo = $this->_registry->LoadingOrder->getSalesOrderProduct($_GET['SalesID']);
            die(json_encode($SalesInfo));
        }
    }

    //    public function SalesOrderList() {
    //        $cond = '';
    //        if (isset($_GET['Sale_Order_Date'])) {
    //            $cond = ' Sales_Order_Date = "' . smc_escape($_GET['Sale_Order_Date']) . '"';
    //        }
    //        $columns = array(
    //            array('db' => 'Sales_Order_ID', 'dt' => 0),
    //            array('db' => 'Customer_Name', 'dt' => 1),
    //            //            array('db' => 'Sales_Status', 'dt' => 2,
    //            //                  'formatter' => function($d) {
    //            //                      $Statuses = [$this->_registry->expenses->getStatusName(25) . "#label-important", $this->_registry->expenses->getStatusName(26) . "#label-warning", $this->_registry->expenses->getStatusName(24) . "#label-master", $this->_registry->expenses->getStatusName(10) . "#label-info"];
    //            //                      return '<span class="label ' . explode("#", $Statuses[$d - 1])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d - 1])[0] . '</span>';
    //            //                  }),
    //            array('db' => 'Employee_Name', 'dt' => 2),
    //            array(
    //                'db' => 'Sales_Order_ID',
    //                'dt' => 3,
    //                'formatter' => function( $d, $row ) {
    //                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
    //                                "ActionOption" => [
    //                                    ["title" => CommonLanguage::getMessage("Edit"),
    //                                        "class" => "Edit",
    //                                        "icon" => "fa-pencil",
    //                                        "href" => "Inventory/purchaseOrder/sales/{$d}"
    //                                    ],
    //                                    ["title" => CommonLanguage::getMessage("view"),
    //                                        "class" => "View",
    //                                        "icon" => "fa-eye",
    //                                        "href" => "Inventory/ViewOrder/Sales/{$d}/{$row[4]}"
    //                                    ],
    //                                    ["title" => CommonLanguage::getMessage("go_invoice"),
    //                                        "class" => "go_invoice",
    //                                        "icon" => "fa-arrow-right",
    //                                        "href" => "Inventory/addpurchase/sales/order/{$d}"
    //                                    ]
    //                    ]]);
    //                    return $html;
    //                }
    //            ),
    //            array('db' => 'Customer_ID', 'dt' => 4)
    //        );
    //        $key = 'Sales_Order_ID';
    //        $table = 'sales_order_list';
    //        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
    //        echo json_encode($data);
    //    }
    //    public function requestProduct() {
    //        $columns = array(
    //            array('db' => 'Product_Code', 'dt' => 0),
    //            array('db' => 'Product_Name', 'dt' => 1),
    //            array('db' => 'Cat_Name', 'dt' => 2),
    //            array('db' => 'Product_Quantity', 'dt' => 3),
    //            array(
    //                'db' => 'Product_ID',
    //                'dt' => 4,
    //                'formatter' => function( $d ) {
    //                    $html = "<div class='btn-group Action'>";
    //                    $html .= "<a style='margin-left:5px' href='" . SITE_LINK . "Inventory/ViewProduct/{$d}'>";
    //                    $html .= "<button type='button' class='btn btn-default'><i class='fa fa-eye'> " . CommonLanguage::getMessage('view') . "</i></button>";
    //                    $html .= "</a>";"<a style='margin-left:5px' href='" . SITE_LINK . "Inventory/ViewProduct/{$d}'>";
    //                    $html .= "<button type='button' data-barcode='#Barcode' id='PrintBarcode' class='btn btn-default'><i class='fa fa-print'> " . CommonLanguage::getMessage('print') . " </i></button>";
    //                    $html .= "</div>";
    //                    return $html;
    //                }
    //            )
    //        );
    //        $key = 'Product_Code';
    //        $data = DataTable::complex($_GET, 'datasource_productlist', $key, $columns);
    //        echo json_encode($data);
    //    }

    public function EditProductRequest() {
        if (isset($_POST["Product_Reorder_Point"]) && isset($_POST["Product_ID"])) {
            $logged_id = Session::getUserID();
            $_POST['logged_id'] = $logged_id;
            $RET = $this->_registry->Product->setData($_POST)->updateProduct();
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }

    //    public function EditVendorRequest() {
    //        if (isset($_POST["Supplier_Name"])) {
    //            $logged_id = Session::getUserID();
    //            array_push($_POST, $logged_id);
    //            $RET = $this->_registry->vendor->setData($_POST)->updateSupplier();
    //            die(json_encode(empty($RET) ? "OK" : $RET));
    //        }
    //    }

    public function GeneralSettingRequest() {
        if (isset($_GET['GetIDToDelete'])) {
            $id = $_GET['GetIDToDelete'];
            $table = $_GET['tableDel'];
            $col = $_GET['columnDel'];
            $delete = $this->_registry->Product->deleteSettingEntry($table, $col, $id);
            die(empty($delete) ? "ok" : $delete[0]);
        }
        if (isset($_GET['colNewValue'])) {
            $table = $_GET['tableEdit'];
            $col = $_GET['columnEdit'];
            $newVal = $_GET['colNewValue'];
            $colName = $_GET['colNameEdit'];
            //            $option = $_GET['optiontype'];
            //            $currency_id = $_GET['currency_id'];
            if (isset($_GET['GetIDToEdit'])) {
                $id = $_GET['GetIDToEdit'];
                $submitEntry = $this->_registry->Product->editSettingEntry($table, $col, $id, $colName, $newVal);
                die(empty($submitEntry) ? 'OK' : 'error');
            } else {
                $submitEntry = $this->_registry->Product->addSettingEntry($table, $colName, $newVal);
                die(empty($submitEntry) ? 'OK' : 'error');
            }
        }
    }

    public function GeneralSettingList() {
        $firstSetting = $this->_registry->Product->getFirstSetting();
        $table = $firstSetting[0]['Table_Name'];
        $col = $firstSetting[0]['Column_ID'];
        $colName = $firstSetting[0]['Column_Name'];
        if (isset($_GET['table'])) {
            $table = $_GET['table'];
            $col = $_GET['column'];
            $colName = $_GET['colName'];
        }
        $columns = array(
            array('db' => $colName, 'dt' => 0),
            array(
                'db' => $col,
                'dt' => 1,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil"
                                    ]
                    ]]);
                    return ($_GET['name'] == 'UOM' && smc_session()['default_setting']['sync_type'] == 2) ? '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>' : $html;
                }
            )
        );
        $key = $col;
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function InvoiceDeliveryNoteList() {
        $cond = ' current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['freq'])) {
            $freq = $_GET['freq'];
            if ($freq == 1) {
                $date = $_GET['Date'];
                $cond .= ' AND Delivery_Report_Date = "' . $date . '" ';
            } else
            if ($freq == 2) {
                $year = $_GET['Date'][0];
                $month = $_GET['Date'][1];
                $cond .= ' AND YEAR(Delivery_Report_Date) = "' . $year . '" AND MONTH(Delivery_Report_Date) = "' . $month . '"';
            } else
            if ($freq == 3) {
                $year = $_GET['Date'][0];
                $cond .= ' AND YEAR(Delivery_Report_Date) = "' . $year . '" ';
            }
            $cond .= (isset($_GET['Is_Vendor'])) ? ' AND Is_Customer_Invoice = 0' : ' AND Is_Customer_Invoice = 1';
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        $columns = array(
            array('db' => 'Person_Name', 'dt' => 0),
            array('db' => 'Delivery_Report_Date', 'dt' => 1),
            array(
                'db' => 'Delivery_Report_ID',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "View",
                                "icon" => "fa-eye",
                                "permission" => !empty($_GET['Is_Vendor']) ? "ViewPurchaseDeliveryNote" : "DeliveryNoteList",
                                "href" => "Inventory/ViewDeliveryNote/" . ((isset($_GET['Is_Vendor'])) ? 'vendor/' : '') . "{$d}/{$row[4]}"
                                    ], ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil",
                                        "permission" => !empty($_GET['Is_Vendor']) ? "edit_supplier_delivery" : "edit_customer_delivery",
                                        "href" => "Inventory/DeliveryNote/" . ((isset($_GET['Is_Vendor'])) ? 'vendor/' : '') . "{$d}"
                                    ], ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => !empty($_GET['Is_Vendor']) ? "delete_purchase_delivery_not" : "delete_sales_delivery_note"
                                    ], ["title" => CommonLanguage::getMessage("go_invoice"),
                                        "class" => "go go_to_invoice",
                                        "icon" => "fa-arrow-right",
                                        "href" => "Inventory/addpurchase/note/" . (empty($_GET['Is_Vendor']) ? 'sales/' : '') . $d,
                                        "permission" => !empty($_GET['Is_Vendor']) ? "supp_delivery_note_toinv" : "cust_delivery_note_toinv"
                                    ]
                    ]]);
                    return $html;
                }
            ),
            array('db' => 'Is_Customer_Invoice', 'dt' => 3),
            array('db' => 'Person_ID', 'dt' => 4),
        );
        $key = 'Delivery_Report_ID';
        $table = 'delivery_notes';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function LoadOrderWithoutSalesORderRequest() {
        if (isset($_GET['Truck_ID'])) {
            $id = $_GET['Truck_ID'];
            $list_vehicles = $this->_registry->vehicle->getAvailableVehicles($id);
            die(json_encode($list_vehicles));
        }
        if (isset($_POST['Vehicle_ID'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $order = $this->_registry->LoadingOrder->setData($_POST)->addLoadingOrderWithoutSalesOrder();
            die($order ? "ok" : 'error');
        }
        $columns = array(
            array('db' => 'Cat_Name', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1),
            array('db' => 'Product_Quantity', 'dt' => 2, "formatter" => function($d, $row) {
                    $input = "</span><input  type='text' class='Quantity' data-id='{$row[3]}' />";
                    return $input;
                }),
            array('db' => 'Product_ID', 'dt' => 3),
        );
        $key = 'Product_ID';
        $data = DataTable::complex($_GET, 'datasource_productlist', $key, $columns);
        echo json_encode($data);
    }

    public function LoadingOrderListRequest() {
        $cond = '';
        if (isset($_GET['type']) && $_GET['type'] != 5) {
            $cond = ' Is_Load = "' . smc_escape($_GET['type']) . '"';
        } else if (isset($_GET['Load_Order_Date'])) {
            $cond = ' Loading_Order_Date = "' . smc_escape($_GET['Load_Order_Date']) . '" ';
        }
        $columns = array(
            array('db' => 'Loading_Order_ID', 'dt' => 0),
            array('db' => 'Vehicle_Registration_Number', 'dt' => 1),
            array('db' => 'Driver_Name', 'dt' => 2),
            array('db' => 'Loading_Order_Date', 'dt' => 3),
            array('db' => 'Is_Load', 'dt' => 4,
                'formatter' => function($d) {
                    $Statuses = [$this->_registry->expenses->getStatusName(18) . "#label-important", $this->_registry->expenses->getStatusName(17) . "#label-warning", $this->_registry->expenses->getStatusName(23) . "#label-info", $this->_registry->expenses->getStatusName(24) . "#label-master"];
                    return '<span class="label ' . explode("#", $Statuses[$d - 1])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d - 1])[0] . '</span>';
                }),
            array(
                'db' => 'Loading_Order_ID',
                'dt' => 5,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "View",
                                "icon" => "fa-eye",
                                "href" => "Inventory/ViewLoadingOrder/{$d}"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "Delete",
                                        "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("return"),
                                        "class" => "Return",
                                        "icon" => "fa-retweet",
                                        "href" => "Inventory/ReturnDamagedLoad/{$d}"
                                    ],
                                    ["title" => CommonLanguage::getMessage("payment"),
                                        "class" => "Payment",
                                        "icon" => "fa-usd",
                                        "href" => "Inventory/PaymentofLoadingOrder/{$d}"
                                    ]
                    ]]);
                    return $html;
                }
            )
        );
        $key = 'Loading_Order_ID';
        $table = 'loading_order_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function LoadingOrderListAjax() {
        if (isset($_GET['GetID'])) {
            $id = $_GET['GetID'];
            $deleteLoad = $this->_registry->LoadingOrder->deleteLoadingOrder($id);
            die(json_encode($deleteLoad));
        }
    }

    public function POSCatAjax() {
        //to add a new cat
        if (isset($_POST['Cat_Name']) && isset($_GET['cmd'])) {
            if ($_GET['cmd'] == 'add') {
                $RET = $this->_registry->Product->setData($_POST)->addCategory();
                die(json_encode(!is_array($RET) ? ['OK', $RET] : [$RET[0]] ));
            }
        }
        //to rename cat
        if (isset($_POST['Cat_Name']) && isset($_POST['CATID']) && isset($_GET['cmd'])) {
            if ($_GET['cmd'] == 'edit') {
                $RET = $this->_registry->Product->setData($_POST)->renamePOSCat();
                die(json_encode(empty($RET) ? 'OK' : 'error'));
            }
        }
        //to delete cat
        if (isset($_GET['id'])) {
            $RET = $this->_registry->Product->deletePOSCat($_GET['id']);
            die(json_encode(empty($RET) ? 'OK' : 'error'));
        }
    }

    public function getProdCatData(){
        $data['main'] = CommonFunctions::CommonView('tbl_product_cat', ['Cat_ID'], [$_GET['cat_id']])[0];
        $data['options'] = CommonFunctions::ViewByTableEntry('tbl_organization_branches', 'branch_id', 'branch_name', $data['main']['multi_branch_id1']);
        die(json_encode($data));
    }
    
    public function PaymentOfLoadingOrderAjax() {
        if (isset($_POST['Date'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $Result = $this->_registry->LoadingOrder->setData($_POST)->submitLoadPayment();
            die($Result ? "OK" : "error");
        }
        if (isset($_POST["Expense"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->LoadingOrder->addExpenseAccount($_POST["Expense"]);
            die(json_encode($RET));
        }
    }

    public function ViewLoadingOrderAjax() {
        if (isset($_POST['Loading_Order_ID'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $load_id = $_POST['Loading_Order_ID'];
            $Ret = $this->_registry->LoadingOrder->setData($_POST)->submitLoadOrder($load_id);
            die($Ret ? "OK" : "error");
        }
    }

    public function ReturnDamagedLoadAjax() {
        if (isset($_POST['Return'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->LoadingOrder->setData($_POST)->addReturnDamagedQuantity();
            die($RET ? "OK" : "error");
        }
    }

    public function PricingListAjax() {
        //        if (isset($_GET['Class'])) {
        //            $class = $_GET['Class'];
        //            $products = $this->_registry->Product->getItemsToAdjustPrice($class);
        //            die(json_encode($products));
        //        }
        if (isset($_POST['Products'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $Ret = $this->_registry->Product->setData($_POST)->AdjustItemPrices();
            die(empty($Ret) ? "ok" : "error");
        }
    }

    public function ReportProductAjax() {
        if (isset($_GET["ReportDate"]) && isset($_GET["Product_ID"])) {
            $Product_ID = smc_escape($_GET["Product_ID"]);
            $Year = smc_escape($_GET["ReportDate"][0]);
            $Month = smc_escape($_GET["ReportDate"][1]);
            $Day = smc_escape($_GET["ReportDate"][2]);
            /// Plot Sold Quantity BY Year and Month
            $ReturnSoldQuantityPerYearMonth = $this->_registry->Product->SoldQuantityPerDay($Product_ID, $Year, $Month);
            $ReturnSoldQuantityPerYear = $this->_registry->Product->SoldQuantityPerDay($Product_ID, $Year);
            $final_result = array_merge($ReturnSoldQuantityPerYearMonth, $ReturnSoldQuantityPerYear);
            $arr = array();
            for ($i = 0; $i < count($final_result) - 12; $i++) {
                if (!is_null($final_result[$i]))
                    array_push($arr, $final_result[$i]);
                else
                    array_push($arr, 0);
            }
            $arrYear = array();
            for ($i = count($final_result) - 12; $i < count($final_result); $i++) {
                if (!is_null($final_result[$i]))
                    array_push($arrYear, $final_result[$i]);
                else
                    array_push($arrYear, 0);
            }
            $SoldQuantityPermonth = $this->_registry->Product->viewSoldQuantityByDate($Product_ID, $Year, $Month);
            $exact_result = array_merge($arr, $arrYear, $SoldQuantityPermonth);
            die(json_encode($exact_result));
        }
        if (isset($_GET["Customer_ID"]) && isset($_GET["Product_ID"])) {
            $Product_ID = smc_escape($_GET["Product_ID"]);
            $Customer_ID = smc_escape($_GET["Customer_ID"]);
            // yousif_error_fix error come from $year than change it to $Year 
            $Year = smc_escape($_GET["ReportDate"][0]);
            $ReturnSoldQuantityPerCustomerYear = $this->_registry->Product->SoldQuantityPerCustomer($Product_ID, $Customer_ID, $Year);
            $Return_Details = $this->_registry->Product->viewProductByCustomer($Product_ID, $Customer_ID);
            $final_result = array_merge($ReturnSoldQuantityPerCustomerYear, $Return_Details);
            $arrCustomerPerYear = array();
            for ($i = 0; $i < count($final_result); $i++) {
                if (!is_null($final_result[$i]))
                    array_push($arrCustomerPerYear, $final_result[$i]);
                else
                    array_push($arrCustomerPerYear, 0);
            }
            die(json_encode($arrCustomerPerYear));
        }
    }

    public function ReturnCustomerAjax() {
        if (isset($_GET["GetInvoiceData"]) && isset($_GET["IsVendor"])) {
            $IsVendor = $_GET["IsVendor"];
            $Invoice_ID = $_GET["GetInvoiceData"];
            $is_actual = $_GET['is_actual'];
            $return_id = !empty($_GET['return_id']) ? $_GET['return_id'] : null;
//            if ($is_actual) {
//                $list = $IsVendor === 'true' ? $this->_registry->return->getReturnSupplierDataByID($_GET['auto_id']) : $this->_registry->return->getReturnCustomerDataByID($_GET['auto_id']);
//            } else {
            $list = $IsVendor ? $this->_registry->return->getReturnSupplierDataByID($_GET['auto_id'], $return_id) : $this->_registry->return->getReturnCustomerDataByID($_GET['auto_id'], $return_id);
            //                $list = $IsVendor === 'true' ? $this->_registry->return->viewPurchaseDetails($Invoice_ID) : $this->_registry->return->viewInvoiceDetails($Invoice_ID);
//            }
            die(json_encode($list));
        }
        //        else if (isset($_POST["Products"]) && isset($_POST["Invoice_Purchase_ID"])) {
        //            $logged_id = Session::getUserID();
        //            array_push($_POST, $logged_id);
        //            if ($_POST['is_actual'])
        //                $insert = $this->_registry->return->setData($_POST)->createActual();
        //            else
        //                $insert = $this->_registry->return->setData($_POST)->create();
        //            die(empty($insert) ? "OK" : $insert[0]);
        //        }
    }

    //public function ReturnCustomerAjax() {
    //
    //    if (isset($_GET["GetInvoiceData"]) && isset($_GET["IsVendor"])) {
    //        $IsVendor = $_GET["IsVendor"];
    //        $Invoice_ID = $_GET["GetInvoiceData"];
    //        $list = $IsVendor === 'true' ? $this->_registry->return->viewPurchaseDetails($Invoice_ID) : $this->_registry->return->viewInvoiceDetails($Invoice_ID);
    //        die(json_encode($list));
    //    } else if (isset($_POST["Products"]) && isset($_POST["Invoice_Purchase_ID"])) {
    //        $logged_id = Session::getUserID();
    //        array_push($_POST, $logged_id);
    //
    //
    //        $insert = $this->_registry->return->setData($_POST)->create();
    //        die(empty($insert) ? "OK" : $insert[0]);
    //    }
    //
    //   
    //}
    public function ReturnCustomerList() {
        $cond = '  current_year_id = "' . $this->year_id . '" ';
        //    die(print_r($_GET['Is_Vendor']));
        $year_id = $_GET['IsActual'] ? $this->year_id_actual : $this->year_id;
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        if (isset($_GET['freq'])) {
            $freq = $_GET['freq'];
            if ($freq == 1) {
                $date = smc_escape($_GET['Date']);
                $cond .= ' AND Date = "' . $date . '" ';
            } else
            if ($freq == 2) {
                $year = smc_escape($_GET['Date'][0]);
                $month = smc_escape($_GET['Date'][1]);
                $cond .= ' AND YEAR(Date) = "' . $year . '" AND MONTH(Date) = "' . $month . '"';
            } else
            if ($freq == 3) {
                $year = smc_escape($_GET['Date'][0]);
                $cond .= ' AND YEAR(Date) = "' . $year . '" ';
            }
        }


        $user_id =smc_session()['user_details']['User_ID'];
        if (smc_session()['user_details']['limit_customer_invoice'] == 1) {
            $cond .= ' and Logged_ID = '.$user_id.'';
        }
        
        if(isset($_GET['is_noqty']))
            $cond.=' and disable_qty="'.$_GET['is_noqty'].'" ';
        $columns = array(
            array('db' => 'return_nb', 'dt' => 0, "formatter" => function($d, $row) {

                    return '<input type="checkbox" data-id="' . $row[6] . '" data-nb="' . $d . '" class="ret_del_td pull-left multi_delete"/>' . $d;
                }),
            array('db' => 'ID', 'dt' => 1, "formatter" => function($d) {
                    return !empty($d) ? $d : 'no invoice';
                }),
            array('db' => 'Name', 'dt' => 2, "formatter" => function($d) {
                    return $d ? $d : 'Cash Customer';
                }),
            array('db' => 'Date', 'dt' => 3),
            array('db' => 'Total', 'dt' => 4, "formatter" => function($d) {
                return CommonFunctions::public_round_number($d);
            }),
            array('db' => 'Note', 'dt' => 5),
            array(
                'db' => 'Return_Invoice_ID',
                'dt' => 6,
                'formatter' => function( $d, $row) {
                    $actions = [
                        ["title" => CommonLanguage::getMessage("view"),
                            "class" => "View openFrame",
                            "icon" => "fa-eye",
                            "permission" => (smc_escape($_GET['Is_Vendor']) === "1" ? ($_GET['IsActual'] ? "ViewReturnDebitActual" : ($row['disable_qty'] ==1 ? "view_ret_supp_noqty": "ViewReturnDebit")) : ($_GET['IsActual'] ? "ViewReturnCreditActual" : ($row['disable_qty'] ==1 ? "view_ret_cust_noqty": "ViewReturnCredit")) ),
                            "attr" => "data-src='Inventory/ViewReturnDebit/" . (smc_escape($_GET['Is_Vendor']) === "1" ? 'vendor/' : '') . "{$d}?is_pop=1'"
                        ]
                    ];
                    if($row['disable_qty']==0){
                        $actions[]=["title" => CommonLanguage::getMessage("copy_to_inv"),
                            "class" => "copy copy_to_invoice_purchase",
                            "attr" => " link='Inventory/addpurchase/" . (smc_escape($_GET['Is_Vendor']) === "1" ? '' : 'sales/') . ($_GET['IsActual'] ? 'act/' : '') . "return/{$d}'  data-type='" . ($_GET['Is_Vendor'] === "1" ? 0 : 1) . "' ",
                            "permission" => ($_GET['IsActual'] == 1 ? ($_GET['Is_Vendor'] != "1" ? "act_copy_return_customer_to_invoice" : "act_copy_return_vendor_to_invoice") : ($_GET['Is_Vendor'] != "1" ? "copy_return_customer_to_invoice" : "copy_return_vendor_to_invoice")),
                            "icon" => "fa-copy"];
                    }
                    if (empty($row[8]) && empty($row[9]) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {
                        $actions[] = ["title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete_inv",
                            "attr" => "data-invoice-app-id={$row['invoice_app_id']}",
                            "permission" => ($_GET['IsActual'] == 1 ? ($_GET['Is_Vendor'] != "1" ? "act_delete_return_customer" : "act_delete_return_vendor") : ($_GET['Is_Vendor'] != "1" ? ($row['disable_qty'] ==1 ? "delete_ret_cust_noqty":"delete_return_customer") : ($row['disable_qty'] ==1 ? "delete_ret_supp_noqty":"delete_return_vendor"))),
                            "icon" => "fa-trash"];
                        if (empty($row['ID'])) {
                            $actions[] = ["title" => CommonLanguage::getMessage($_GET['IsActual'] == 1 ? "to_official" : "to_actual"),
                                "class" => "change_actual",
                                "permission" => ($_GET['Is_Vendor'] === "1" ? ( $_GET['IsActual'] == 1 ? 'act_return_vendor_to_official' : ($row['disable_qty'] ==1 ? "ret_supp_noqty_to_act":'return_vendor_to_actual')) : ($_GET['IsActual'] == 1 ? "act_return_customer_to_official" : ($row['disable_qty'] ==1 ? "ret_cust_noqty_to_act":"return_customer_to_actual"))),
                                "icon" => "fa-retweet"];
                        }
//                        if (!$row[1]) {
                        $actions[] = ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "Edit",
                            "icon" => "fa-eye",
                            "permission" => (smc_escape($_GET['Is_Vendor']) === "1" ? ($_GET['IsActual'] ? "edit_act_return_vendor" : ($row['disable_qty'] ==1 ? "edit_ret_supp_noqty":"edit_return_vendor")) : ($_GET['IsActual'] ? "edit_act_return_customer" : ($row['disable_qty'] ==1 ? "edit_ret_cust_noqty":"edit_return_customer")) ),
                            "href" => "Inventory/ReturnNoInvoice/" . (smc_escape($_GET['Is_Vendor']) === "1" ? '' : 'sales/') . ($_GET['IsActual'] ? 'act/' : '') . ($row['disable_qty'] ? 'noqty/' : ''). "{$d}"
                        ];
//                        }
                    }
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $actions]);
                    return $html;
                }
            ),
            array('db' => 'Person_ID', 'dt' => 7), 'exchange_id', 'sales_purchase_id', 'invoice_app_id', 'is_main_transfer','disable_qty'
        );
        //            $cond .=$_GET['Is_Vendor']==="true" ? ' AND Is_Customer_Invoice = 0' : ' AND Is_Customer_Invoice = 1';
        $cond .= ' AND Is_Actual = "' . $_GET['IsActual'] . '"';
        $key = 'Return_Invoice_ID';
        $table = $_GET['Is_Vendor'] ? 'vendor_return_list' : 'customer_return_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function SalesOrderIvoice() {
        if (isset($_POST["Customer_ID"]) && isset($_POST["Invoice_Date"])) {
            $logged_id = Session::getUserID();
            $_POST['Logged_ID'] = $logged_id;
            $ret = $this->_registry->invoice->setData($_POST)->insertSalesInvoice(null, 1);
            die($ret ? "OK" : "error");
        }
    }

    public function ServiceInvoiceList() {
        $year_id = $_GET['is_actual'] ? $this->year_id_actual : $this->year_id;
        $cond = '';
        if (isset($_GET['From_Date'])) {
            $cond = ' Invoice_Date >= "' . $_GET['From_Date'] . '" and Invoice_Date <= "' . $_GET['To_Date'] . '" and Is_Actual = "' . $_GET['is_actual'] . '"';
        }
        $cond .= ' and current_year_id = "' . $year_id . '"';
        $columns = array(
            array('db' => 'Invoice_ID', 'dt' => 0),
            array('db' => 'Customer_Name', 'dt' => 1),
            array('db' => 'Invoice_Date', 'dt' => 2),
            array('db' => 'Invoice_Due_Date', 'dt' => 3),
            array('db' => 'Total', 'dt' => 4),
            array(
                'db' => 'Invoice_ID_Auto',
                'dt' => 5,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => false, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "View",
                                "icon" => "fa-eye",
                                "href" => "Inventory/ViewServicesInvoice/{$d}"
                                    ]
                    ]]);
                    return $html;
                }
            )
        );
        $key = 'Invoice_ID_Auto';
        $table = 'service_invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function StockAjax() {
        if (isset($_POST['Method_ID'])) {
            $result = $this->_registry->Product->setData($_POST)->createPricingMethod();
            die(empty($result) ? "OK" : "error");
        }
        if (isset($_POST['ClosingStock'])) {
            $logged_id = Session::getUserID();
            $result = $this->_registry->Product->setData($_POST)->closeStock($logged_id);
            die(empty($result) ? "OK" : "error");
        }
    }

    public function InvoicesPerCustomerVendor() {
        $IsVendor = true;
        $cond = '';
        if (isset($_GET['id'])) {
            $IsVendor = ($_GET['Is_Vendor'] == 'true') ? true : false;
            $cond .= ' and Person_ID = "' . smc_escape($_GET['id']) . '"';
        }
        $columns = array(
            array('db' => 'ID', 'dt' => 0),
            array('db' => 'Name', 'dt' => 1),
            array('db' => 'Date', 'dt' => 2),
            array('db' => 'Due_Date', 'dt' => 3),
            array('db' => 'VAT', 'dt' => 4),
            array('db' => 'SubTotal', 'dt' => 5),
            array('db' => 'NetTotal', 'dt' => 6),
            array(
                'db' => 'ID',
                'dt' => 7,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $row[8],
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "View openFrame",
                                "icon" => "fa-eye",
                                "attr" => "data-src=Inventory/ViewInvoice/" . ($_GET['Is_Vendor'] == 'true' ? 'vendor/' : '') . "{$row[8]}/{$row[9]}"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "permission" => $_GET['Is_Vendor'] === 'true' ? ($row[10] == 1 ? "editPurchaseActual" : "editPurchase") : ($row[10] == 1 ? "editInvoiceActual" : "editInvoice"),
                                        "icon" => "fa-pencil",
                                        "href" => "Inventory/addpurchase/" . ($_GET['Is_Vendor'] === 'true' ? '' : 'sales/') . ($row[10] == 1 ? 'act/' : '') . "{$row[8]}"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete_inv",
                                        "permission" => $row[10] == 1 ? ($_GET['Is_Vendor'] != "true" ? "DeleteSalesInvoiceActual" : "delete_act_purchase_invoice") : ($_GET['Is_Vendor'] != "true" ? "DeleteSalesInvoice" : "delete_purchase_invoice"),
                                        "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage($row[10] == 1 ? "to_official" : "to_actual"),
                                        "class" => "change_actual",
                                        "permission" => $_GET['Is_Vendor'] != "true" ? ($row[10] == 1 ? 'pur_to_official' : 'pur_to_actual') : ($row[10] == 1 ? "inv_to_official" : "inv_to_actual"),
                                        "icon" => "fa-retweet"]
                    ]]);
                    return $html;
                }
            ),
            array('db' => 'ID_Auto', 'dt' => 8),
            array('db' => 'Person_ID', 'dt' => 9),
            array('db' => 'is_actual', 'dt' => 10)
        );
        $key = 'ID';
        $table = $IsVendor ? 'purchase_invoice_list' : 'sales_invoice_list';
        $cond .= $IsVendor ? '' : ($this->controller_permission->hasPermission('show_actual_invoices') ? '' : ' and is_actual = 0');
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function DeleteVendor() {
        if (isset($_GET["Supplier_ID"])) {
            $delete_vendor = $this->_registry->vendor->setData($_GET)->deleteSupplier();
            die(empty($delete_vendor) ? "OK" : ($delete_vendor[0] == "check_supplier" ? CommonLanguage::getMessage("check_supplier") : $delete_vendor[0]));
        }
    }

    public function addLoadingOrderAjax() {
        if (isset($_GET['code_id'])) {
            $code = $_GET['code_id'];
            $SalesOrderDetail = $this->_registry->LoadingOrder->viewSalesDetailsByID($code);
            die(json_encode($SalesOrderDetail));
        }
        if (isset($_GET['Truck_ID'])) {
            $id = $_GET['Truck_ID'];
            $list_vehicles = $this->_registry->vehicle->getAvailableVehicles($id);
            die(json_encode($list_vehicles));
        }
        if (isset($_GET['GetZone'])) {
            $zone_id = $_GET['GetZone'];
            $ViewInfo = $this->_registry->LoadingOrder->getSalesOrderInfo($zone_id);
            die(json_encode($ViewInfo));
        }
        if (isset($_POST['Vehicle_ID'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->LoadingOrder->setData($_POST)->assignSalesOrderToLoadOrder();
            die($result ? "OK" : "erorr");
        }
    }

    public function addCityAjax() {
        if (isset($_POST['Country_ID'])) {
            $result = $this->_registry->countries->setData($_POST)->addCities();
            die($result ? "ok" : "error");
        }
    }

    public function addPricingClassAjax() {
        if (isset($_POST["PricingClass"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->Product->setData($_POST)->addPricingClass();
            if (empty($RET)) {
                $class = $this->_registry->material->getLastOfType('tbl_pricing_class', 'Class_ID');
                die(json_encode(['OK', $class]));
            } else {
                // yousid_error_fix
                $class = $this->_registry->material->getLastOfType('tbl_pricing_class', 'Class_ID');
                die(json_encode(['error', $class]));
            }
        }
    }

    public function addServiceAjax() {
        if (isset($_POST["Customer_ID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->invoice->setData($_POST)->addServicesInvoice();
            die(json_encode(empty($result) ? "OK" : $result));
        }
        if (isset($_GET['id'])) {
            $details = $this->_registry->customer->ViewAllCustomerDetails($_GET['id']);
            die(json_encode($details));
        }
    }

    public function products_customers_list() {
        
        $cond = !empty($_GET['customers_id']) ? ' and Customer_ID ="' . $_GET['customers_id']  . '"' : '';
        $cond .= !empty($_GET['product_id']) ? ' and product_id ="' . $_GET['product_id']  . '"' : '';

        $columns = array();
         
         
        $columns[] = 'Customer_Name';

          
        $columns[] = 'Product_Name';

        $key = 'Customer_Name';
             $table = "(SELECT DISTINCT
             Customer_Name,
              Product_Name,
              customers.Customer_ID Customer_ID,
              products.Product_ID product_id
         FROM
             tbl_invoice_products_details AS invoice_products
         LEFT JOIN `tbl_invoices` `invoices` ON
             `invoices`.`Invoice_ID_Auto` = `invoice_products`.`Invoice_ID_Auto`
         LEFT JOIN `tbl_stock_products` `products` ON
             `products`.`Product_ID` = `invoice_products`.`Product_ID`
         LEFT JOIN `tbl_customers` `customers` ON
             `customers`.`Customer_ID` = `invoices`.`Customer_ID`) as product_list";
        
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function listProductRequest() {
       
        $cond = !empty($_GET['Status_ID']) ? ' and Status_ID ="' . ($_GET['Status_ID'] == 1 ? 1 : 0) . '"' : '';
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and multi_branch_id in (' . ($_GET['search_branch_id']) . ') OR multi_branch_id LIKE "' . ($_GET['search_branch_id']) . ',%" OR multi_branch_id LIKE "%,' . ($_GET['search_branch_id']) . ',%" OR multi_branch_id like "%,' . ($_GET['search_branch_id']) . '"  ' : '';
        }else{
            $cond .= ' and multi_branch_id in (' . (smc_session()['user_accounts']['branch_id']) . ') OR multi_branch_id LIKE "' . (smc_session()['user_accounts']['branch_id']) . ',%" OR multi_branch_id LIKE "%,' . (smc_session()['user_accounts']['branch_id']) . ',%" OR multi_branch_id like "%,' . (smc_session()['user_accounts']['branch_id']) . '"  ' ;
        }
        
        $columns = array();
        if (empty($_GET['show_zero_qty'])) {
            $cond .= ' and prod_quantity <> 0';
        }
        if ($this->controller_permission->hasPermission('print_bar_code') || $this->controller_permission->hasPermission('delete_multi_product')) {
            $columns[] = array('db' => 'Product_ID', 'formatter' => function($d, $row) {
                    return '<input type="checkbox" class="multi_barcode prdt_check_input_td" data-id="' . $d . '" />';
                });
        }
        if (smc_session()['default_setting']['show_product_image_list'] == 1) {
            $columns[] = array('db' => 'Product_ID', 'formatter' => function($d, $row) {
                    $img_prd = file_exists(dirBase . "uploads/products_photos/{$d}.jpg") ? dirBase . "uploads/products_photos/{$d}.jpg" : dirBase . "img/profiles/product.png";
                    $img_prd_pop = file_exists(dirBase . "uploads/products_photos/{$d}.jpg") ? SITE_LINK . "uploads/products_photos/{$d}.jpg" : SITE_LINK . "img/profiles/product.png";

                    return "<img class='image_popup' popup-src='" . $img_prd_pop . "' src='" . CommonFunctions::image_thumb($img_prd, 75) . "' style='max-width:50px;max-height:50px;cursor:pointer;'/>";
                });
        }
        if (!empty($_GET['category_id']))
            $cond .= ' and Category_ID IN (' . $_GET['category_id'] . ')';

        array_push($columns, 'Bar_Code', 'Product_Code');
        if (smc_session()['default_setting']['activate_search_product_second_code'] == 1) {
            array_push($columns, 'product_second_code');
        }
        $columns[] = 'Product_Name';
        if (smc_session()['default_setting']['show_price_product_list'] == 1) {
            array_push($columns, array('db' => 'Product_Price', 'formatter' => function($d) {
                    return CommonFunctions::formatNumber($d) . ' ' . smc_session()['pricing_class_currency_symbol'];
                }));
        }
        array_push($columns, 'Cat_Name', 'brand_name', array('db' => 'Product_View_Quantity', 'formatter' => function($d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['def_view_uom_name'];
            }), 'Product_PLU');
        $columns[] = array('db' => 'Status_ID', "formatter" => function($d, $row, $excel) {
                return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
            });
        $columns[] = array('db' => 'Product_ID', "formatter" => function($d, $row, $excel) {
                $options = [
                    ["title" => CommonLanguage::getMessage("view"),
                        "class" => "View",
                        "icon" => "fa-eye",
                        "permission" => "ViewProduct",
                        "href" => "Inventory/ViewProduct/{$d}"
                    ],
                    ["title" => CommonLanguage::getMessage($row['Status_ID'] == 1 ? 'disable' : 'enable'),
                        "class" => "disable_enable_item",
                        "icon" => "fa-" . ($row['Status_ID'] == 1 ? 'lock' : 'unlock'),
                        "data-target" => "#enable-disable-modal",
                        "attr" => "data-id={$row['Status_ID']}",
                        "permission" => "disable_enable_product"
                    ],
                    ["title" => CommonLanguage::getMessage('print_barcodes'),
                        "class" => "openFrame",
                        "icon" => "fa-print",
                        "attr" => "data-src='Inventory/printBarCode?pr={$d}&is_pop=1'",
                        "permission" => "print_bar_code"
                    ]
                ];
                if (smc_session()['default_setting']['sync_type'] != 2) {
                    $options[] = ["title" => CommonLanguage::getMessage("Edit"),
                        "class" => "openFrame",
                        "icon" => "fa-pencil",
                        "attr" => "data-src='Inventory/ViewProduct/{$d}?is_pop=1&modal=1'",
                        "permission" => "EditProduct"
                    ];
                    $options[] = ["title" => CommonLanguage::getMessage("copy"),
                        "class" => "copy",
                        "icon" => "fa-copy",
                        "permission" => "copy_product",
                        "data-target" => "#addProduct"
                    ];
                    $options[] = ["title" => CommonLanguage::getMessage("Delete"),
                        "class" => "delete_product",
                        "icon" => "fa-trash"
                    ];
                }
                $html = Forms::action_snippet(["color" => "primary",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => $options]);
                return $html;
            });
        $columns[] = 'def_view_uom_name';

        $key = 'Product_ID';
        $table = 'datasource_productlist';
        if (smc_session()['default_setting']['show_price_product_list'] == 1) {
            $table = "(select `p`.`Product_Code`,`p`.`Product_Name`,`p`.`branch_id`
            ,if(isnull(concat(`p`.`Product_Quantity`,' ',`uc`.`UOM_Name`)),`p`.`Product_Quantity`,concat(`p`.`Product_Quantity`,' ',`uc`.`UOM_Name`)) AS `Product_Quantity`,
            if((`p`.`default_view_uom_id` = 0),`uc`.`UOM_Name`,`dfvu`.`UOM_Name`) AS `def_view_uom_name`,
            if((`p`.`default_view_uom_id` = 0),`p`.`Product_Quantity`,(`p`.`Product_Quantity` / `p`.`default_view_rate`)) AS `Product_View_Quantity`,
            `p`.`Product_ID`,`c`.`Cat_Name`,`p`.`Product_PLU`,`br`.`brand_name`,`p`.`Status_ID`,
            `u`.`Bar_Code`,`p`.`Category_ID`,`p`.`Product_Quantity` AS `prod_quantity`,
            `p`.`product_second_code` AS `product_second_code` ,ifnull(pc.Product_Price,0) as Product_Price
            from `tbl_stock_products` `p` 
            join `tbl_product_cat` `c` on `c`.`Cat_ID` = `p`.`Category_ID`
            left join `tbl_common_currency` `y` on `y`.`Currency_ID` = `p`.`Currency_ID`
            join `tbl_stock_uom` `uc` on `uc`.`UOM_ID` = `p`.`UOM_ID`
            left join `tbl_brand_products` `br` on `br`.`brand_id` = `p`.`brand_id`
            left join `tbl_item_price_by_classes` `pc` on `pc`.`Product_ID` = `p`.`Product_ID`
            and pc.Class_ID = '" . smc_session()['default_setting']['pricing_class_id'] . "'
                and pc.UOM_ID = p.UOM_ID
            join `tbl_uom_conversions` `u` on (`u`.`Product_ID` = `p`.`Product_ID` and (`u`.`is_default` = 1))
            join `tbl_stock_uom` `dfvu` on `dfvu`.`UOM_ID` = `p`.`default_view_uom_id`) as product_list";
        }
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function product_recipe() {
        $cond = ' operation = "-" ';
        $_GET['currency_id'] = smc_session()['local_currency'];
        //        $_GET['class_id'] = 1;
        if (!empty($_GET['product_id'])) {
            $cond .= 'and main_product_id = "' . $_GET['product_id'] . '" ';
        }
        if (!empty($_GET['class_id'])) {
            $query = $this->db->query('select Currency_ID from tbl_pricing_class where Class_ID = "' . $_GET['class_id'] . '"');
            $_GET['currency_id'] = $this->db->assoc($query)['Currency_ID'];
        }
        $columns = array();
        $columns[] = 'main_product_name';
       
        $columns[] = array('recipe_qty', 'formatter' => function( $d, $row ) {
                return $d . ' ' . $row['main_uom'];
            });
             $columns[] = 'Product_Name';
        $columns[] = array('UOM_Name', 'formatter' => function( $d, $row ) {
                return $row['current_quantity'] . ' ' . $d;
            });
        $columns[] = 'sub_product_id';
        $columns[] = 'operation';
        //        if(!empty($_GET['class_id']))
        $columns[] = 'price';
        $columns[] = 'profit';
        $columns[] = 'quantity';
        $columns[] = 'current_quantity';
        $columns[] = 'main_product_id';
        $columns[] = 'main_uom_id';
        $columns[] = 'main_uom';

        //        $columns = array('main_product_name', array('db' => 'Product_Name', 'dt' => 1),
        //                         array('UOM_Name', 'dt' => 2, 'formatter' => function( $d, $row ) {
        //                             return $row['current_quantity'] . ' ' . $d;
        //                         }),
        //                         'sub_product_id', 'operation','price', 'quantity', 'current_quantity', 'main_product_id','main_uom_id'
        //                        );
        $key = 'link_id';
        $table = 'product_link';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, ['fetch_row_callback' => ['ft' => array($this, 'product_recipe_fetch_row')]]);
        echo json_encode($data);
    }

    public function product_recipe_fetch_row(&$data, &$row) {
        static $product_id = null;
        //        static $last_index= 0;
        static $product_cost = 0;
        static $product_price = 0;
        static $product_profit = 0;
        //        echo"<pre"; print_r($data);
        if ($product_id != $row['main_product_id']) {
            $product_id = $row['main_product_id'];
            $product_cost = Product::get_main_product_cost($row['main_product_id']);
            if (!empty($_GET['class_id']))
                $product_price = Product::get_product_price($row['main_product_id'], $_GET['class_id'], $row['main_uom_id']);
            $product_profit = $product_cost == 0 ? 0 : (($product_price - $product_cost) / $product_cost) * 100;
        }
        $current_cost = Product::get_main_product_cost($row['sub_product_id']) * $row['quantity'];
        //        $current_cost = CommonBusiness::viewLastProductCost($row['sub_product_id']) * $row['quantity'];
        $row['sub_product_id'] = CommonFunctions::formatNumber($current_cost) . ' ' . smc_session()['local_currency_symbol'];
        if (!empty($_GET['class_id'])) {
            $price = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($_GET['currency_id'], smc_session()['local_currency'], $product_price);
            $row['price'] = CommonFunctions::formatNumber($price) . ' ' . smc_session()['local_currency_symbol'];
            $row['profit'] = CommonFunctions::formatNumber($product_profit) . ' %';
        } else {
            $row['price'] = '-- --';
            $row['profit'] = '-- --';
        }
        $row['operation'] = CommonFunctions::formatNumber($product_cost) . ' ' . smc_session()['local_currency_symbol'];
    }

    public function addProductAjax() {
        if (isset($_POST["Product_Reorder_Point"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->Product->setData($_POST)->addProduct();
            $max_code = $this->_registry->Product->getMaxProductCode();
            die(json_encode(empty($RET) ? ["OK", $max_code] : $RET));
        }
    }

    public function addPurchaseAjax() {

        if (isset($_POST["Supplier_ID"]) && isset($_POST["Purchase_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
//            die('here');
            $insert = $this->_registry->purchase->setData($_POST)->createInvoicePurchase(true);
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
        }
        if (isset($_POST["Customer_ID"]) && isset($_POST["Invoice_Date"])) {
            $logged_id = Session::getUserID();
            $_POST['Logged_ID'] = $logged_id;
            $sales = $this->_registry->invoice->setData($_POST)->insertSalesInvoice();
            //        die(empty($sales) ? "OK" : $sales[0]);
            die(json_encode(is_numeric($sales[0]) ? ['OK', $sales[0], $sales[1]] : $sales ));
        }

        if (isset($_GET['id'])) {
            if (!empty($_GET['mode']) && $_GET['mode'] === 'true') {
                $details = $this->_registry->customer->ViewAllCustomerDetails($_GET['id']);
            } else {
                $details = $this->_registry->vendor->ViewAllDetails($_GET['id']);
            }
            die(json_encode($details));
        }
    }

    public function addSalesPurchaseAjax() {

        if (isset($_POST["is_return"]) && isset($_POST["is_return"])) {
            $logged_id = Session::getUserID();
            $_POST['Logged_ID'] = $logged_id;
            if ($_POST['is_return'] == 1) {
                $salesPurchase = $this->_registry->salesPurchase->setData($_POST)->insertSalesPurchaseReturn();
            } else {
                $salesPurchase = $this->_registry->salesPurchase->setData($_POST)->insertSalesPurchase();
            }//        die(empty($sales) ? "OK" : $sales[0]);
            die(json_encode(is_numeric($salesPurchase[0]) ? ['OK', $salesPurchase[0], $salesPurchase[1]] : $salesPurchase[0] ));
        }
    }

    public function addCustomerAjax() {
        if (isset($_POST["Customer_Name"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->customer->setData($_POST)->createCustomer();
            die(json_encode(empty($RET) ? "OK" : $RET ));
        }
    }

    public function mergeCategoriesItemsAjax() {
        if (isset($_GET['ProdType'])) {
            $data = $this->_registry->Product->getItemsCategoryByType($_GET['ProdType']);
            die(json_encode($data));
        }
        if (isset($_GET['Type_ID'])) {
            $data = $this->_registry->Product->setData($_GET)->mergeCategories();
            die(empty($data) ? 'OK' : 'error');
        }
        if (isset($_GET['Product_ID'])) {
            $logged_id = Session::getUserID();
            array_push($_GET, $logged_id);
            $data = $this->_registry->Product->setData($_GET)->mergeItems();
            die($data ? 'OK' : 'error');
        }
        if (isset($_GET['Cat_Type'])) {
            $data = $this->_registry->Product->setData($_GET)->addCategoryInMerge();
            die(json_encode($data));
        }
        if (isset($_GET["Material_Category_ID"])) {
            die(json_encode($this->_registry->material->getType($_GET["Material_Category_ID"])));
        }
    }

    public function reorderStockAjax() {
        if (isset($_GET["Product_ID"])) {
            $Vendors = $this->_registry->Product->viewListVendorPurchaseByProduct($_GET["Product_ID"]);
            die(json_encode($Vendors));
        }
    }

    public function reorderStockRequest() {
        $columns = array(
            array('db' => 'Product_Code', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1,
                "formatter" => function($d, $row) {
                    $html = "<span class='Arrow semi-bold' data-id='{$row[5]}'>{$d}</span>";
                    return $html;
                }),
            array('db' => 'Product_Quantity', 'dt' => 2),
            array('db' => 'Product_Price', 'dt' => 3),
            array('db' => 'Product_Reorder_Point', 'dt' => 4),
            array('db' => 'Product_ID', 'dt' => 5)
        );
        $key = 'Product_ID';
        $table = 'reorder_product_stock';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' Product_Reorder_Point IS NOT NULL');
        echo json_encode($data);
    }

    //    public function addSupplierAjax() {
    //        if (isset($_POST["Supplier_Name"])) {
    //            $logged_id = Session::getUserID();
    //            array_push($_POST, $logged_id);
    //            $RET = $this->_registry->vendor->setData($_POST)->createSupplier();
    //            //            die(print_r($RET));
    //            die(json_encode(empty($RET) ? 'OK' : $RET));
    //        }
    //    }
    public function submitVendor() {
        $submit = $_POST['Supplier_ID'] == '' ? $this->_registry->vendor->setData($_POST)->createSupplier() : $this->_registry->vendor->setData($_POST)->updateSupplier();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getSupplierDetails() {
        $data['main'] = $this->_registry->vendor->ViewAllDetails($_GET['Supplier_ID'])[0];
        $data['contacts'] = CommonFunctions::CommonView('tbl_customer_supplier_contacts', ['main_id', 'type_id'], [$_GET['Supplier_ID'], '2']);
        die(json_encode($data));
    }

    public function purchaseOrderAjax() {
        if (isset($_POST['Products'])) {
            //            $logged_id = Session::getUserID();
            //            array_push($_POST, $logged_id);
            //            if ($_POST['IsSales'] == "true") {
            //                $RET = $this->_registry->invoice->setData($_POST)->addSalesOrder();
            //            } else {
            $sales = $this->_registry->purchase->setData($_POST)->addPurchaseOrder();
            //            }
            die(json_encode(is_numeric($sales[0]) ? ['OK', $sales[0], $sales[1]] : $sales ));
            //            die(empty($RET) ? json_encode("OK") : json_encode($RET));
        }
        //        if (isset($_GET['id'])) {
        //            if ($_GET['mode'] === 'true') {
        //                $details = $this->_registry->customer->ViewAllCustomerDetails($_GET['id']);
        //            } else {
        //                $details = $this->_registry->vendor->ViewAllDetails($_GET['id']);
        //            }
        //            die(json_encode($details));
        //        }
    }

    public function quotationRequest() {
        $cond = ' is_sales = "' . $_GET['IsSales'] . '" and is_quotation = "' . $_GET['is_quotation'] . '"';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and Order_Date between "' . $_GET['from_date'] . '" AND "' . $_GET['to_date'] . '"';
        }
        if (!empty($_GET['from_delivery_date']) && !empty($_GET['to_delivery_date'])) {
            $cond .= ' and if(isnull(delivery_date),Order_Date,Date(delivery_date)) between "' . $_GET['from_delivery_date'] . '" AND "' . $_GET['to_delivery_date'] . '"';
        }

        
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        
        $cond .= ' and is_actual = "' . $_GET['is_actual'] . '" and current_year_id = "' . $this->year_id . '"';
        if (!empty($_GET['status_id']) && $_GET['status_id'] != 0) {
            $cond .= ' and is_converted = "' . ($_GET['status_id'] == 1 ? '0' : '1') . '"';
        }

        $user_id =smc_session()['user_details']['User_ID'];
        if (smc_session()['user_details']['limit_customer_invoice'] == 1) {
            $cond .= ' and Logged_ID = '.$user_id.'';
        }

        $columns = array('sale_nb', 'Person_Name', 'Order_Date','date_created','order_description',
        );
        if (!$_GET['is_quotation']) {
            $columns [] = array('delivery_date');
        }
        if (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && !$_GET['is_quotation'] && $_GET['IsSales']) {
            $columns [] = array('db' => 'postponed_status_id',
                "formatter" => function($d) {
                    $label_name = CommonLanguage::getMessage($d == 1 ? 'Request' : ($d == 2 ? 'production_line' : ($d == 3 ? 'production_done' : ($d == 4 ? 'delivered' : 'on_request'))));
                    $label_color = $d == 1 ? 'important' : ($d == 2 ? 'master' : ($d == 3 ? 'warning' : 'info'));
                    return empty($d) ? '--- ---' : '<span class="label label-' . $label_color . '" data-status="' . $d . '">' . $label_name . '</span>';
                });
            $columns [] = array('db' => 'postponed_date_time');
        }
        $columns[] = array('db' => 'Order_ID',
            'formatter' => function( $d, $row) {
                $option_arr = [
                    ["title" => CommonLanguage::getMessage("view"),
                        "class" => "View openFrame",
                        "icon" => "fa-eye",
                        "attr" => "data-src='Inventory/ViewQuotationOrder/" . ($_GET['is_quotation'] == 1 ? 'quotation' : 'order') . ($_GET['is_actual'] == 1 ? '/act' : '') . "/{$d}?is_pop=1'",
                        "permission" => $_GET['is_quotation'] == 1 ? ($_GET['IsSales'] == 1 ? 'view_sales_quotation_details' : 'view_purchase_quotation_details') : ($_GET['is_actual'] ? ($_GET['IsSales'] == 1 ? 'actual_sales_order_details' : 'actual_purchase_order_details') : ($_GET['IsSales'] == 1 ? 'view_sales_order_details' : 'view_purchase_order_details'))
                    ],
                    ["title" => CommonLanguage::getMessage("Edit"),
                        "class" => "Edit",
                        "icon" => "fa-pencil",
                        "href" => "Inventory/quotationOrder/" . ($_GET['is_quotation'] == 1 ? 'quotation/' : 'order/') . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d,
                        "permission" => $_GET['is_quotation'] == 1 ? ($_GET['IsSales'] == 1 ? 'edit_sales_quotation' : 'edit_purchase_quotation') : ( $_GET['is_actual'] == 1 ? ($_GET['IsSales'] == 1 ? 'edit_actual_sales_order' : 'edit_actual_purchase_order') : ($_GET['IsSales'] == 1 ? 'EditSalesOrder' : 'edit_purchase_order'))
                    ],
                    ["title" => CommonLanguage::getMessage("delete"),
                        "class" => "delete",
                        "icon" => "fa-trash",
                        "attr" => "data-sale-app-id={$row['sale_app_id']}",
                        "permission" => $_GET['is_quotation'] == 1 ? ($_GET['IsSales'] == 1 ? 'delete_sales_quotation' : 'delete_purchase_quotation') : ($_GET['is_actual'] == 1 ? ($_GET['IsSales'] == 1 ? 'delete_actual_sales_order' : 'delete_actual_purchase_order') : ($_GET['IsSales'] == 1 ? 'delete_sales_order' : 'delete_purchase_order'))
                    ],
                    ["title" => CommonLanguage::getMessage("go_invoice"),
                        "class" => "go go_to_invoice",
                        "icon" => "fa-arrow-right",
                        "attr" => "link='Inventory/addpurchase/order/" . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d . "'  data-type='" . ($_GET['IsSales'] == 1 ? 1 : 0) . "' ",
                        "permission" => $_GET['is_quotation'] == 1 ? ($_GET['IsSales'] == 1 ? 'sales_quotation_go_invoice' : 'purchase_quotation_go_invoice') : ($_GET['IsSales'] == 1 ? 'sales_order_go_invoice' : 'purchase_order_go_invoice')
                    ]
                ];
                if ($_GET['IsSales'] !== 1) {

                    $option_arr[] = ["title" => CommonLanguage::getMessage("go_inv_noqty"),
                        "class" => "go go_noqty",
                        "icon" => "fa-arrow-right",
                        "attr" => "link='Inventory/addpurchase/order/noqty/" . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d . "'",
                        "permission" => $_GET['is_quotation'] == 1 ? 'purchase_quotation_go_invoice_noqty' : 'purchase_order_go_invoice_noqty'
                    ];
                }
                if ($_GET['is_quotation'] == 1) {
                    $option_arr[] = ["title" => CommonLanguage::getMessage("go_order"),
                        "class" => "go go_order",
                        "icon" => "fa-arrow-right",
                        "attr" => "link='Inventory/quotationOrder/order/qto/" . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d . "'",
                        "permission" => ($_GET['IsSales'] == 1 ? 'sales_quotation_go_order' : 'purchase_quotation_go_order')
                    ];
                    if ($_GET['IsSales'] == 1) {
                        $option_arr[] = ["title" => CommonLanguage::getMessage("revisions"),
                            "class" => "revision",
                            "icon" => "fa-eye",
                            //                                                "href" => "Inventory/quotationOrder/order/qto/" . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d,
                            "permission" => ('view_sales_quotation_revesion')
                        ];
                    }
                }
                if ($_GET['is_quotation'] == 0) {

                    $option_arr[] = ["title" => CommonLanguage::getMessage("go_delivery"),
                        "class" => "go_delivery",
                        "icon" => "fa-arrow-right",
                        "attr" => "link='Inventory/DeliveryNote/order/" . ($_GET['IsSales'] == 1 ? '' : 'vendor/') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d . "'",
                        "permission" => ($_GET['IsSales'] == 1 ? 'sales_order_go_delivery' : 'purchase_order_go_delivery')
                    ];
                    $option_arr[] = ["title" => CommonLanguage::getMessage("go_delivered_invoice"),
                        "class" => "go_delivered_invoice",
                        "icon" => "fa-arrow-right",
                        "href" => "Inventory/addpurchase/delivery/" . ($_GET['IsSales'] == 1 ? 'sales/' : '') . ($_GET['is_actual'] == 1 ? 'act/' : '') . $d,
                        "permission" => ($_GET['IsSales'] == 1 ? 'sales_order_delivered_to_invoice' : 'purchase_order_delivered_to_invoice')
                    ];
                }
                if ($_GET['is_quotation'] == 0 && $_GET['IsSales'] == 1) {
                    $option_arr[] = ["title" => CommonLanguage::getMessage("purchase_orders"),
                        "class" => "go_purchase openFrame",
                        "icon" => "fa-arrow-right",
                        //                                "href" => "Inventory/sales_to_purchase_order/" .  ($_GET['is_actual'] == 1 ? 'act/' : '') . $d,
                        "attr" => "data-src='Inventory/sales_to_purchase_order/" . ($_GET['is_actual'] == 1 ? 'act/' : '') . "{$d}}?is_pop=1'",
                        "permission" => 'sales_order_to_multi_purchase'
                    ];
                }
                $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                            "ActionOption" => $option_arr]);

                return $html;
            });
        $columns [] = array('db' => 'Supplier_ID');
        $columns [] = array('db' => 'sale_app_id');
 
        $key = 'Order_ID';
        $table = 'purchase_order_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function deleteQuotationOrder() {
        $delete_quotation_order = $this->_registry->purchase->setData($_GET)->deleteQuotationOrder();
        die(empty($delete_quotation_order) ? "ok" : $delete_quotation_order[0]);
    }

    public function deleteDeliveryNote() {
        $delete_delivery_note = $this->_registry->delivery->setData($_GET)->deleteDeliveryNote();
        die(empty($delete_delivery_note) ? "ok" : $delete_delivery_note[0]);
    }

    public function deleteProduct() {
        $delete_product = $this->_registry->Product->setData($_GET)->deleteProduct();
        die(empty($delete_product) ? "ok" : ($delete_product[0] == 'unable_delete_product' ? CommonLanguage::getMessage('unable_delete_product') : "error"));
    }

    public function PurchaseDeliveryNoteAjax() {
        //            die(print_r($_GET));
        if (isset($_GET['GetData'])) {
            $data = $this->_registry->purchase->getPurchaseOrderDetails(smc_escape($_GET['GetData']));
            //            $data = $_GET['IsVendor'] === 'true' ? $this->_registry->purchase->getPurchaseOrderDetails(smc_escape($_GET['GetData'])) : $this->_registry->invoice->getSalesOrderDetails(smc_escape($_GET['GetData']));
            die(json_encode($data));
        }
        if (isset($_GET['getTerms'])) {
            $data = $_GET['IsVendor'] === 'true' ? $this->_registry->delivery->getPurchaseOrderTerms(smc_escape($_GET['getTerms'])) : $this->_registry->delivery->getPurchaseOrderTerms(smc_escape($_GET['getTerms']), 1);
            die(json_encode($data));
        }
        if (isset($_POST['term'])) {
            $RET = $this->_registry->delivery->setData($_POST)->confirmTermConditions();
            die(json_encode(empty($RET) ? 'OK' : $RET));
        }
        //                                                                                                        if (isset($_POST['order_confirm'])) {
        //                                                                                                            $RET = $_POST['IsVendor'] === 'true' ? $this->_registry->delivery->setData($_POST)->confirmPurchaseOrder() : $this->_registry->delivery->setData($_POST)->confirmSalesOrder();
        //                                                                                                            die(json_encode(empty($RET) ? 'OK' : $RET));
        //                                                                                                        }
    }

    public function purchaseOrderListAjax() {
        if (isset($_GET['OrderID'])) {
            $data = $this->_registry->purchase->getPurchaseOrderDetails(smc_escape($_GET['OrderID']));
            die(json_encode($data));
        }
    }

    public function ItemMovementAjax() {
        $type = smc_escape($_GET['type']);
        $item_id = smc_escape($_GET['Material_Code']);
        $freq = smc_escape($_GET['freq']);
        $date = $_GET['Report_Date'];
        $year_id = ($_GET['actual'] == 1) ? $this->year_id_actual : $this->year_id;
        $cond = ' Product_ID = "' . $item_id . '" and current_year_id = "' . $year_id . '"';
        if ($_GET['actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        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]) . '"';
        }
        $group = ' GROUP BY Person_ID ';
        $columns = array(
            array('db' => 'Name', 'dt' => 0),
            array('db' => 'SUM(Quantity)', 'dt' => 1),
            array('db' => 'Discount', 'dt' => 2),
            array('db' => 'SUM(Product_Total_Price)', 'dt' => 3, "formatter" => function($d, $row) {
                    return $row[4] . ' ' . CommonFunctions::public_round_number($d);
                }),
            array('db' => 'Currency_Symbol', 'dt' => 4)
        );
        $key = 'Person_ID';
        $table = ($type == 1 ? 'product_mov_invoice' : 'product_mov_purchase');
        $cond .= $type == 1 ? ' and is_committed = 1' : '';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }

    public function UnmovedItemsAjax() {
        $type = smc_escape($_GET['type']);
        $threshold = smc_escape($_GET['Threshold']);
        $fromdate = $_GET['FromDate'];
        $todate = $_GET['ToDate'];
        $year_id = ($_GET['actual'] == 1) ? $this->year_id_actual : $this->year_id;
        
        $cond = ' current_year_id = "' . $year_id . '"';
        if (isset($_GET['FromDate']) && isset($_GET['ToDate'])) {
            $cond .= ' AND Date <= "' . $todate . '" AND Date >= "' . $fromdate . '"';
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        if ($_GET['actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        $group = ' GROUP BY Product_ID HAVING SUM(Quantity) <= "' . $threshold . '"';
        $columns = array(
            array('db' => 'Code', 'dt' => 0),
            array('db' => 'Item_Name', 'dt' => 1),
            array('db' => 'SUM(Quantity)', 'dt' => 2));
        $key = 'Entery_ID';
        $table = ($type == 0 ? 'product_movement_invoice' : 'product_mov_purchase');
        $cond .= $type == 0 ? ' and is_committed = 1' : '';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }

    public function DueDateInvoiceListRequest() {
        $cond = '';
        if (isset($_GET['FromDate']) && isset($_GET['ToDate'])) {
            $cond .= ' and Due_Date between "' . $_GET['FromDate'] . '" AND  "' . $_GET['ToDate'] . '"';
        }
        if (empty($_GET['IsVendor']) && !empty($_GET['customer_group_id']))
            $cond .= ' and customer_group_id ="' . $_GET['customer_group_id'] . '"';
        if (!empty($_GET['person_id']))
            $cond .= ' and Person_ID ="' . $_GET['person_id'] . '" ';
        if (empty($_GET['IsVendor']) && !empty($_GET['salesman_id']))
            $cond .= ' and Sales_ID ="' . $_GET['salesman_id'] . '" ';
        $_GET['cond'] = $cond;
        $columns = array('Inv_Pur_ID', 'Name');
        if (!empty($_GET['IsVendor']) && !empty(smc_session()['default_setting']['activate_shipment_fields'])) {
            $columns[] = 'ship_bill_nb';
            $columns[] = 'ship_date';
        }
        $columns[] = 'Date';
        $columns[] = 'Due_Date';
        $columns[] = array('db' => 'Due_Date', 'formatter' => function($d, $row) {
                $date_diff = (CommonFunctions::calc_date_diff($d, date('Y-m-d')) );
                return $date_diff;
            });
        $columns[] = array('db' => 'Total', 'formatter' => function( $d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            });
        if (!empty($_GET['IsVendor']) && !empty(smc_session()['default_setting']['activate_shipment_fields'])) {
            $columns[] = 'shipping';
            $columns[] = 'extra_cost';
            $columns[] = 'net_total';
        }
        $columns[] = array('db' => 'Paid_Amount', 'formatter' => function( $d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            });
        $columns[] = array('db' => 'net_return', 'formatter' => function( $d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            });
        $columns[] = array('db' => 'remaining_amount', 'formatter' => function( $d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            });
        $columns[] = array('db' => 'remaining_amount', 'formatter' => function( $d, $row) {
                return '<b>' . CommonFunctions::formatNumber($_GET['customer_balances'][$row['Person_ID']][$_GET['currency_id'] == 1 ? 'local_amount' : 'second_amount']) . '</b>';
            });
        $columns[] = array(
            'db' => 'Inv_Pur_ID_Auto',
            'formatter' => function( $d, $row) {
                $html = Forms::action_snippet(["color" => "primary", "isDropDown" => false,
                            "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                            "class" => "View openFrame",
                            "icon" => "fa-eye",
                            "attr" => "data-src='Inventory/ViewInvoice/" . ($_GET['IsVendor'] == 1 ? 'vendor/' : '') . "{$d}/{$row['Person_ID']}?is_pop=1'"
                ]]]);
                return $html;
            });
        $columns[] = 'Person_ID';
        $columns[] = 'Currency_Symbol';

        $key = 'Inv_Pur_ID_Auto';
        if ($_GET['IsVendor'] == 0)
            $cond .= ' and is_committed = 1';
        $table = $_GET['IsVendor'] == 1 ? 'due_date_purchase' : 'due_date_invoices';
        $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'inv_due_ftch_row']]
            , 'fetch_all_callback' => ['ft' => [$this, 'inv_due_ftch_all']],
            'order' => ' Person_ID,Due_Date '];
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond, null, null, $row_cb);
        echo json_encode($data);
    }

    public function inv_due_ftch_row(&$data, &$row) {

        $_GET['tmp__all_ids'][$row['Person_ID']] = false;
    }

    public function inv_due_ftch_all(&$data) {
        if (empty($_GET['tmp__all_ids']))
            return true;
        $query = $this->db->query('SELECT sum(remaining_amount*current_rate) as local_amount,
            sum(remaining_amount*second_currency_rate) as second_amount,Person_ID
            from ' . ( $_GET['IsVendor'] == 1 ? 'due_date_purchase' : 'due_date_invoices') . '
            where Person_ID in (' . implode(',', array_keys($_GET['tmp__all_ids'])) . ')  ' . $_GET['cond'] . '
            group by Person_ID');
        while ($row = $this->db->assoc($query)) {
            $_GET['customer_balances'][$row['Person_ID']] = $row;
        }

        //        echo"<pre>";die(print_r($_POST['prod_val']));
    }

    public function CustomerLimitBalanceRequest() {
        $cond = ' 1=1 ';
        if (isset($_GET['search_branch_id']) && $_GET['search_branch_id'] == 1)
            $cond .= ' and  branch_id  = "'.$_GET['search_branch_id'].'"  ';

        if (isset($_GET['hide_zero_limit']) && $_GET['hide_zero_limit'] == 1)
            $cond .= ' and Limit_Balance  <> 0 ';

        if (isset($_GET['hide_zero_balance']) && $_GET['hide_zero_balance'] == 1)
            $cond .= ' and Balance   <>  0 ';

        if (isset($_GET['show_stop_only']) && $_GET['show_stop_only'])
            $cond .= ' and stop_invoice  =1  ';
        $columns = array(
            array('db' => 'Account_Code', 'dt' => 0),
            array('db' => 'Customer_Name', 'dt' => 1),
            array('db' => 'Company', 'dt' => 2),
            array('db' => 'Limit_Balance', 'dt' => 3,
                "formatter" => function($d, $row) {
                    return $row[7] . ' ' . CommonFunctions::formatNumber($d);
                }),
            array('db' => 'Balance', 'dt' => 4,
                "formatter" => function($d, $row) {
                    $currency = new Currency;
                    $value = $currency->returnBalanceByCurrExchange($d, $row[6]);
                    return $row[7] . ' ' . CommonFunctions::formatNumber($value);
                }),
            array('db' => 'Balance', 'dt' => 5,
                "formatter" => function($d, $row) {
                    $currency = new Currency;
                    $value = $currency->returnBalanceByCurrExchange($d, $row[6]);
                    return '<span class="label ' . StatusCodes::getStatusColor(($value > $row[3]) ? 1 : 2) . '" >' . StatusCodes::getStatus(($value > $row[3]) ? 30 : 31) . '</span>';
                }),
            array('db' => 'Limit_Currency_ID', 'dt' => 6),
            array('db' => 'Currency_Symbol', 'dt' => 7)
        );
        $key = 'Account_Code';
        $table = 'customer_limit_balance';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function uomConversionRequest() {
        $cond = '';
        if ($_GET['id'] != '') {
            $cond .= ' Product_ID = "' . smc_escape($_GET['id']) . '"';
        }
        $columns = array(
            array('db' => 'Product_Name', 'dt' => 0),
            array('db' => 'from_name', 'dt' => 1),
            array('db' => 'to_name', 'dt' => 2),
            array('db' => 'conversion_amount', 'dt' => 3),
            array('db' => 'Bar_Code', 'dt' => 4),
            array('db' => 'additional_barcodes', 'dt' => 5)
        );
        $key = 'uom_conversion_id';
        $table = 'uom_conversions';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function addconversionAjax() {
        if (isset($_POST['Con'])) {
            $RET = $this->_registry->Product->setData($_POST)->addUOMConversions();
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
        if (isset($_POST['conversions'])) {
            $RET = $this->_registry->Product->setData($_POST)->editUOMConversions();
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }

    public function getconversionToEdit() {
        $RET = $this->_registry->Product->getConversionsByProduct($_GET['IDToEdit']);
        die(json_encode($RET));
    }

    public function ItemCostChangeAjax() {
        if (isset($_GET['FromDate'])) {
            $fromDate = implode("-", $_GET['FromDate']);
            $toDate = implode("-", $_GET['ToDate']);
            $item_ID = $_GET['Item_ID'];
            $productList = $this->_registry->Product->IfCostChanged($fromDate, $toDate, $item_ID);
            die(json_encode($productList));
        }
        if (isset($_GET['month'])) {
            $month = $_GET['month'];
            $item = $_GET['Month_Item_ID'];
            $CostList = $this->_registry->Product->MonthlyCostChange($month, $item);
            die(json_encode($CostList));
        }
    }

    //    public function ReturnProductUOMCon() {
    //        $data = $this->_registry->material->getUOMByProductID($_GET['pid'], $_GET['uid']);
    //        die(json_encode($data));
    //    }

    public function ReturnProductUOMPriceCon() {
        //        echo"<pre>";
        //        die(print_r(smc_session()));
        $customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : NULL;
        $currency_id = isset($_GET['currency_id']) ? $_GET['currency_id'] : smc_session()['local_currency'];
        $class_id = isset($_GET['class_id']) ? $_GET['class_id'] : smc_session()['pricing_class_id'];
        $depot_id = isset($_GET['depot_id']) ? $_GET['depot_id'] : smc_session()['default_depot_id'];
        $supp_class = isset($_GET['supp_class']) ? $_GET['supp_class'] : '';
        $data = $this->_registry->Product->getUOMByProductID($_GET['pid'], $_GET['uid'], $depot_id, $currency_id, $class_id, $customer_id, $supp_class);
        die(json_encode($data));
    }

    public function ReturnQtyPerDepot() {
        if (empty($_GET['items']))
            $_GET['items'] = array();
        $data = $this->_registry->Product->ReturnQtyPerDepot($_GET['items'], $_GET['depot_id']);
        die(json_encode($data));
    }

    public function getCurrentProductCost() {
        $data = CommonBusiness::viewCurrentProductCost($_GET['product_id']);
        die(json_encode($data));
    }

    public function ReturnPriceByClass() {
        $customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : NULL;
        $data = $this->_registry->Product->ReturnPriceByClass($_GET['items'], $_GET['class_id'], $customer_id);
        die(json_encode($data));
    }

    public function invoiceReportPerTime() {
        $cond = '';
        if (isset($_GET['freq'])) {
            $freq = $_GET['freq'];
            if ($freq == 1) {
                $date = $_GET['Date'];
                $cond = ' Invoice_Date = "' . $date . '" ';
            } else if ($freq == 2) {
                $year = $_GET['Date'][0];
                $month = $_GET['Date'][1];
                $cond = ' YEAR(Invoice_Date) = "' . $year . '" AND MONTH(Invoice_Date) = "' . $month . '"';
            } else if ($freq == 3) {
                $year = $_GET['Date'][0];
                $cond = ' YEAR(Invoice_Date) = "' . $year . '" ';
            }
        }
        $cond .= ' AND current_year_id = "' . $this->year_id . '" and is_committed = 1';
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' and Customer_ID = "' . $_GET['customer_id'] . '" ';
            if (!empty($_GET['customer_branch_id']))
                $cond .= ' and customer_branch_id = "' . $_GET['customer_branch_id'] . '" ';
        }
        $columns = array(
            array('db' => 'ID', 'dt' => 0),
            array('db' => 'Customer_Name', 'dt' => 1, 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }),
            array('db' => 'date_created', 'dt' => 2),
            array('db' => 'Invoice_Net_Total', 'dt' => 3, "formatter" => function($d, $row) {
                    return $row[4] . ' ' . Forms::DecimalNumber($d);
                }),
            array('db' => 'Currency_Symbol', 'dt' => 4)
        );
        $key = 'Invoice_ID';
        $table = '(select *,concat(invoice_prefix,Invoice_ID) as ID from invoice_list_main) as inv_table';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function TotalItemsPerDateAjax() {
        $cond = ' current_year_id="' . $this->year_id . '"';
        if (!empty($_GET['From_Date'])) {
            $cond .= ' AND date_created between "' . $_GET['From_Date'] . '" AND  "' . $_GET['To_Date'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' AND branch_id = "' . $_GET['branch_id'] . '" ';
        }
        if (!empty($_GET['sales_man_id'])) {
            $cond .= ' AND Sales_ID = "' . $_GET['sales_man_id'] . '" ';
        }
        if (!empty($_GET['barcode'])) {
            $cond .= ' AND Product_PLU = "' . $_GET['barcode'] . '" ';
        }
        if (isset($_GET['From_Date_invoice'])) {
            $cond .= ' AND Date between "' . $_GET['From_Date_invoice'] . '" AND  "' . $_GET['To_Date_invoice'] . '"';
        }
        if (isset($_GET['users']) && !empty($_GET['users'])) {
            $cond .= ' AND Logged_ID in (' . $_GET['users'] . ')';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' AND Customer_ID = "' . $_GET['customer_id'] . '" ';
            if (!empty($_GET['customer_branch_id'])) {
                $cond .= ' and customer_branch_id = "' . $_GET['customer_branch_id'] . '"';
            }
        }

        if (!empty($_GET['category_id'])) {
            $cond .= ' AND Category_ID = "' . $_GET['category_id'] . '" ';
        }
        if (!empty($_GET['customer_group_id'])) {
            $cust_ids = array();
            $query = $this->db->prepare_Stmt('select Customer_ID from tbl_customers 
                where customer_group_id = ?', [$_GET['customer_group_id']]);
            while ($row = $this->db->assoc($query))
                $cust_ids[] = $row['Customer_ID'];
            if (!empty($cust_ids))
                $cond .= ' AND Customer_ID in (' . implode(',', $cust_ids) . ') ';
            else
                $cond .= ' and 1=2 ';
        }

        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        $group = ' GROUP BY Product_ID,Currency_ID ';
        $columns = array('Item_Name', 'Code','Product_PLU',
            array('db' => 'SUM(def_view_qty)', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['UOM_Name'];
                }),
            array('db' => ( 'SUM(Product_Total_Price)'), "formatter" => function($d, $row, $is_excel) {
                    return ($is_excel ? '' : $row['Currency_Symbol'] . ' ') . CommonFunctions::formatNumber($d);
                }),
            array('db' => ('SUM(vat_amount)'), "formatter" => function($d, $row, $is_excel) {
                    return ($is_excel ? '' : $row['Currency_Symbol'] . ' ') . CommonFunctions::formatNumber($d) ;
                }),
        );
        if (smc_session()['default_setting']['activate_second_vat'] == 1) {
            $columns[] = array('db' => 'SUM(vat2_amount)', "formatter" => function($d, $row, $is_excel) {
                    return ($is_excel ? '' : $row['Currency_Symbol'] . ' ') . CommonFunctions::formatNumber($d);
                });
        }
        $columns[] = array('db' => 'SUM(Product_Total_Price+vat_amount+vat2_amount)', "formatter" => function($d, $row, $is_excel) {
                return ($is_excel ? '' : $row['Currency_Symbol'] . ' ') . CommonFunctions::formatNumber($d);
            });

        if ($this->controller_permission->hasPermission('effect_qty_link_product') == 1) {
            $columns[] = array('db' => 'SUM(qty_link)', "formatter" => function ($d, $row, $is_excel) {
                return  $d;
            });
        }

        $columns[] = 'UOM_Name';
        $columns[] = 'Currency_Symbol';
        //sales_return_mov
        $key = 'Product_ID';
        $table = $_GET['with_return'] == 0 ? 'product_movement_invoice' : '(select Product_Name,Product_PLU,u.*,um.UOM_Name,i.Sales_ID ,
            p.Product_Name as Item_Name,p.Product_Code as Code,c.Currency_Symbol,p.Category_ID,(Quantity/if(p.default_view_uom_id=0,1,p.default_view_rate)) as def_view_qty from
            (select i.Customer_ID as Customer_ID,`d`.`Product_ID`,`d`.`Product_Quantity` AS `Quantity`,`d`.`Product_Total_Price`AS `Product_Total_Price`,
            `i`.`date_created` ,i.Invoice_Date as Date,`i`.`Invoice_Currency` AS `Currency_ID`,i.current_year_id,i.Logged_ID ,
            i.created_logged_id,i.is_actual,i.branch_id,i.customer_branch_id ,d.vat_amount,d.vat2_amount,d.qty_link
            from `tbl_invoice_products_details` `d` join `tbl_invoices` `i` on `i`.`Invoice_ID_Auto` = `d`.`Invoice_ID_Auto` 
            where i.is_committed = 1
            union all
            select i.Person_ID as Customer_ID,d.Product_ID,(d.Return_Product_Quantity *(-1)) as Quantity, 0 as qty_link,i.Sales_ID ,
            (d.Return_Product_Total  * -1) as Product_Total_Price,i.date_created ,i.Return_Invoice_Date as Date,i.Currency_ID,i.current_year_id,
            i.Logged_ID,i.created_logged_id,i.Is_Actual as is_actual,i.branch_id,i.customer_branch_id ,(d.vat_amount  * -1) as vat_amount,(d.vat2_amount  * -1) as vat2_amount
            from tbl_accounting_return_items d join tbl_accounting_return_invoices i 
            on d.Return_Invoice_ID = i.Return_Invoice_ID) u join tbl_stock_products p on u.Product_ID = p.Product_ID 
            join tbl_common_currency c on c.Currency_ID = u.Currency_ID left join tbl_stock_uom um 
            on um.UOM_ID = if(p.default_view_uom_id=0,p.UOM_ID,p.default_view_uom_id) ) as movement';
        $cond .= $_GET['with_return'] == 0 ? ' and is_committed = 1' : '';
        //                       die($cond);
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }


    public function DetailedInvoiceProductReportAjax() {
        $freq = smc_escape($_GET['freq']);
        $date = $_GET['Date'];
        $cond = ' current_year_id="' . $this->year_id . '" and is_committed = 1';
        if ($freq == 1) {
            $cond .= '  AND Date = "' . smc_escape($date) . '"';
        } else if ($freq == 2) {
            $cond .= '  AND MONTH(Date) = "' . smc_escape($date[1]) . '" AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        } else if ($freq == 3) {
            $cond .= '  AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        }
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and modify_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }


        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' and Customer_ID = "' . $_GET['customer_id'] . '" ';
            if (!empty($_GET['customer_branch_id']))
                $cond .= ' and customer_branch_id = "' . $_GET['customer_branch_id'] . '"';

        }
        if (!empty($_GET['product_id'])) {
            $cond .= ' and Product_ID = "' . $_GET['product_id'] . '" ';
        }
        if (!empty($_GET['created_by_id'])) {
            $cond .= ' and created_logged_id = "' . $_GET['created_by_id'] . '" ';
        }
        if (!empty($_GET['sales_man_id'])) {
            $cond .= ' and Sales_ID = "' . $_GET['sales_man_id'] . '" ';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_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 (!empty($_GET['customer_group_id'])) {
            $cust_ids = array();
            $query = $this->db->prepare_Stmt('select Customer_ID from tbl_customers 
                where customer_group_id = ?', [$_GET['customer_group_id']]);
            while ($row = $this->db->assoc($query))
                $cust_ids[] = $row['Customer_ID'];
            if (!empty($cust_ids))
                $cond .= ' AND Customer_ID in (' . implode(',', $cust_ids) . ') ';
            else
                $cond .= ' and 1=2 ';
        }
        if($this->controller_permission->hasPermission('effect_qty_link_product') == 1){
            $columns = array(array('db' => 'invoice_nb', 'formatter' => function($d, $row) {
                        $html = '';
                        if (($row['is_actual'] == 1 && $this->controller_permission->hasPermission('editInvoiceActual')) || ($row['is_actual'] == 0 && $this->controller_permission->hasPermission('editInvoice')))
                            $html .= '<span class="openFrame cursor" data-src="Inventory/addpurchase/sales/' . ($row['is_actual'] == 1 ? 'act/' : '') . $row['Invoice_ID_Auto'] . '?is_pop=1"><i class="fa fa-pencil"></i></span>&nbsp;';
                        $html .= '<span class="openFrame" style="cursor:pointer;" data-src="Inventory/ViewInvoice/' . $row['Invoice_ID_Auto'] . '/' . $row['Customer_ID'] . '?is_pop=1">' . $d . '</span>';
                        return $html;
                    }),
                array('db' => 'Name', 'formatter' => function($d) {
                        return $d ? $d : '-- --';
                    }), 'Item_Name', 'product_description', 'date_created','modify_date','qty_link',
                array('db' => 'customer_branch_id', "formatter" => function($d, $row) {
                    $query = $this->db->query('select * from tbl_customer_branches where customer_branch_id = "'.$d.'"');
                    $row = $this->db->assoc($query);        
                    return   $row['customer_branch_name'];
                }),
                array('db' => 'Item_Quantity_Current', "formatter" => function($d, $row) {
                        return Forms::DecimalNumber($d) . ' ' . $row['details_prod_uom'];
                    }), 'Depot_Name',
                array('db' => 'Product_Net_Price', "formatter" => function($d, $row) {
                        return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                    }),
                array('db' => 'Discount_Amount', "formatter" => function($d, $row) {
                        return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                    }),
                array('db' => 'Product_Total_Price', "formatter" => function($d, $row) {
                        return $row['Currency_Symbol'] . ' ' . Forms::DecimalNumber($d);
                    }), 'UOM_Name', 'Currency_Symbol', 'Customer_ID', 'Invoice_ID_Auto', 'details_prod_uom', 'is_actual'
            );
        } else {
            $columns = array(
                array('db' => 'invoice_nb', 'formatter' => function ($d, $row) {
                    $html = '';
                    if (($row['is_actual'] == 1 && $this->controller_permission->hasPermission('editInvoiceActual')) || ($row['is_actual'] == 0 && $this->controller_permission->hasPermission('editInvoice')))
                    $html .= '<span class="openFrame cursor" data-src="Inventory/addpurchase/sales/' . ($row['is_actual'] == 1 ? 'act/' : '') . $row['Invoice_ID_Auto'] . '?is_pop=1"><i class="fa fa-pencil"></i></span>&nbsp;';
                    $html .= '<span class="openFrame" style="cursor:pointer;" data-src="Inventory/ViewInvoice/' . $row['Invoice_ID_Auto'] . '/' . $row['Customer_ID'] . '?is_pop=1">' . $d . '</span>';
                    return $html;
                }),
                array('db' => 'Name', 'formatter' => function ($d) {
                    return $d ? $d : '-- --';
                }), 'Item_Name', 'product_description', 'date_created',
                array('db' => 'Item_Quantity_Current', "formatter" => function ($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row['details_prod_uom'];
                }), 'Depot_Name',
                array('db' => 'Product_Net_Price', "formatter" => function ($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }),
                array('db' => 'Discount_Amount', "formatter" => function ($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }),
                array('db' => 'Product_Total_Price', "formatter" => function ($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . Forms::DecimalNumber($d);
                }), 'UOM_Name', 'Currency_Symbol', 'Customer_ID', 'Invoice_ID_Auto', 'details_prod_uom', 'is_actual'
            );
        }


        $key = 'Entery_ID';
        $table = 'product_mov_invoice';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY date_created asc');
        echo json_encode($data);
    }

    public function invoiceDetailsVehicleDriver() {
        $freq = smc_escape($_GET['freq']);
        $date = $_GET['Date'];
        $cond = ' current_year_id="' . $this->year_id . '" and is_committed = 1';
        if ($freq == 1) {
            $cond .= '  AND Date = "' . smc_escape($date) . '"';
        } else if ($freq == 2) {
            $cond .= '  AND MONTH(Date) = "' . smc_escape($date[1]) . '" AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        } else if ($freq == 3) {
            $cond .= '  AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (!empty($_GET['employee_id'])) {
            $cond .= ' and employee_id = "' . $_GET['employee_id'] . '" ';
        } if (!empty($_GET['vehicle_id'])) {
            $cond .= ' and vehicle_id = "' . $_GET['vehicle_id'] . '" ';
        }
        $columns = array('invoice_nb',
            array('db' => 'Name', 'dt' => 1, 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }), 'Item_Name',
            array('db' => 'vehicle_name', 'dt' => 3, 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }),
            array('db' => 'employee_name', 'dt' => 4, 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }), 'product_description', 'date_created',
            array('db' => 'Quantity', 'dt' => 7, "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row[10];
                }),
            array('db' => 'commission', 'dt' => 8, "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row[11];
                }),
            array('db' => 'Product_Total_Price', 'dt' => 9, "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row[11];
                }), 'UOM_Name', 'Currency_Symbol'
        );
        $key = 'Entery_ID';
        $table = 'product_mov_invoice';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY date_created asc');
        echo json_encode($data);
    }

    public function DetailedReturnProductReportAjax() {
        $freq = smc_escape($_GET['freq']);
        $return_type = $_GET['return_type'];
        $date = $_GET['Date'];
        $cond = ' current_year_id="' . $this->year_id . '" and Is_Customer_Invoice = "' . $return_type . '"';
        if ($freq == 1) {
            $cond .= '  AND Date = "' . smc_escape($date) . '"';
        } else if ($freq == 2) {
            $cond .= '  AND MONTH(Date) = "' . smc_escape($date[1]) . '" AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        } else if ($freq == 3) {
            $cond .= '  AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (!empty($_GET['category_id']))
            $cond .= ' and Category_ID = "' . $_GET['category_id'] . '" ';
        if (!empty($_GET['brand_id']))
            $cond .= ' and brand_id = "' . $_GET['brand_id'] . '" ';
        $columns = array(
            array('db' => 'Name', 'dt' => 0, 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }),
            array('db' => 'Item_Name', 'dt' => 1),
            array('db' => 'Date', 'dt' => 2),
            array('db' => 'Quantity', 'dt' => 3, "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row[5];
                }),
            array('db' => 'Product_Total_Price', 'dt' => 4, "formatter" => function($d, $row) {
                    return $row[6] . ' ' . Forms::DecimalNumber($d);
                }),
            array('db' => 'UOM_Name', 'dt' => 5),
            array('db' => 'Currency_Symbol', 'dt' => 6)
        );
        $key = 'Return_Item_ID';
        $table = 'product_mov_return';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY date_created asc');
        echo json_encode($data);
    }

    public function ItemProfitReportAjax() {
        //        $freq = smc_escape($_GET['freq']);
        //        $date = $_GET['Date'];
        $cond = ' 1=1  and is_committed = 1';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= '  and Date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '" ';
        }

        if (!empty($_GET['Invoice_ID_Auto']) && empty($_GET['with_return']))
            $cond .= ' and Invoice_ID_Auto = "' . $_GET['Invoice_ID_Auto'] . '" ';

        if (!empty($_GET['search_branch_id']))
            $cond .= ' and  branch_id = ' . $_GET['search_branch_id'] . ' ';


        if (!empty($_GET['zero_price']))
            $cond .= ' and Product_Total_Price = 0';
        if (!empty($_GET['brand_id']))
            $cond .= ' and brand_id = "' . $_GET['brand_id'] . '"';
        if (!empty($_GET['cat_id']))
            $cond .= ' and Category_ID in (' . $_GET['cat_id'] . ')';
        if (!empty($_GET['product_id']))
            $cond .= ' and Product_ID = "' . $_GET['product_id'] . '"';
        if (isset($_GET['person_id']) && $_GET['person_id'] != '')
            $cond .= ' and Customer_ID = "' . $_GET['person_id'] . '"';
        if (empty($_GET['is_actual']))
            $cond .= ' and is_actual = 0';

        $columns = array('Code', 'Item_Name', 'date_created',
            array('db' => ($_GET['is_group'] == 1 ? 'sum(def_view_qty)' : 'Item_Quantity_Current'), "formatter" => function($d, &$row) {
                    $row['total_qty'] = $d;
                    return Forms::DecimalNumber($d);
                }),
            array('db' => 'UOM_Name', "formatter" => function($d, &$row) {
                    return ($_GET['is_group'] == 1 ? $d : $row['current_uom_name']);
                }),
            array('db' => ($_GET['is_group'] == 1 ? 'sum(Product_Cost*current_rate*Quantity)' : '(Product_Cost*Quantity)'), "formatter" => function($d, &$row) {
                    $cost = 0;
                    if ($_GET['cost_type'] == 1) {
                        $cost_loc = (CommonBusiness::viewCostByAverage([$row['Product_ID']], true)[$row['Product_ID']]) * $row['total_qty']*($row['Quantity']/$row['Item_Quantity_Current']);
                        $cost = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $row['Currency_ID'], $cost_loc);
                    } else if ($_GET['cost_type'] == 2) {
                        $cost_loc = (CommonBusiness::viewLastProductCost($row['Product_ID'])) * $row['total_qty']*($row['Quantity']/$row['Item_Quantity_Current']);
                        $cost = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $row['Currency_ID'], $cost_loc);
                    } else {
                        $cost = $d;
                    }
                    $row['Product_Cost'] = $cost;
                    //                return $row['Quantity'];
                    //                $row['Product_Cost']=$cost;return $row['Product_Cost'];
                    return ($_GET['is_group'] == 1 ? smc_session()['local_currency_symbol'] : $row['Currency_Symbol']) . ' ' . Forms::DecimalNumber($cost);
                }),
            array('db' => ($_GET['is_group'] == 1 ? 'sum((Product_Total_Price+total_tax)*current_rate)' : '(Product_Total_Price+total_tax)'), "formatter" => function($d, &$row) {
                    $row['total_price'] = $d;
                    return ($_GET['is_group'] == 1 ? smc_session()['local_currency_symbol'] : $row['Currency_Symbol']) . ' ' . Forms::DecimalNumber($d);
                }),
            array('db' => ($_GET['is_group'] == 1 ? 'sum(profit*current_rate)' : 'profit'), "formatter" => function($d, &$row) {
                    if ($_GET['cost_type'] == 0) {
                        $row['total_profit'] = $d;
                        return ($_GET['is_group'] == 1 ? smc_session()['local_currency_symbol'] : $row['Currency_Symbol']) . ' ' . Forms::DecimalNumber($d);
                    } else {
                        $profit = ($row['total_price'] - $row['Product_Cost']);
                        $row['total_profit'] = $profit;
                        return Forms::DecimalNumber($profit) . ' ' . $row['Currency_Symbol'];
                    }
                }),
            array('db' => 'profit', "formatter" => function($d, $row) {
                    $percent = ($row['Product_Cost'] == 0 ? 0 : (($row['total_profit'] / $row['Product_Cost']) * 100 * (empty($row['is_return']) ? 1 : -1)));
                    return '% ' . Forms::DecimalNumber($percent);
                }), 'Currency_Symbol', 'total_tax', 'Product_ID', 'Quantity', 'current_uom_name', 'Currency_ID', 'is_return','Item_Quantity_Current'
        );
        $group = !empty($_GET['is_group']) ? 'group by Product_ID' : '';
        $key = 'Entery_ID';
        $table = empty($_GET['with_return']) ? 'product_movement_invoice' : '(select Product_Name,u.*,um.UOM_Name,uc.UOM_Name as current_uom_name,
            p.Product_Name as Item_Name,p.Product_Code as Code,c.Currency_Symbol,p.Category_ID,(Quantity/if(p.default_view_uom_id=0,1,p.default_view_rate)) as def_view_qty from
            (select i.Customer_ID as Customer_ID,`d`.`Product_ID`,`d`.`Product_Quantity` AS `Quantity`,`d`.`Product_Total_Price`AS `Product_Total_Price`,
            `i`.`date_created` ,i.Invoice_Date as Date,`i`.`Invoice_Currency` AS `Currency_ID`,i.current_year_id,i.Logged_ID ,
            i.created_logged_id,i.is_actual,i.branch_id as branch_id,i.customer_branch_id ,d.vat_amount,d.vat2_amount,
            d.Item_Quantity_Current,`d`.`unit_cost` AS `Product_Cost`,d.total_tax,d.UOM_ID as current_uom_id,i.is_committed,d.Entery_ID,
            (`d`.`Product_Total_Price` - (`d`.`Product_Quantity` * `d`.`unit_cost`)) AS `profit`,0 as is_return,
            (((`d`.`Product_Total_Price` - (`d`.`Product_Quantity` * `d`.`unit_cost`)) / `d`.`Product_Total_Price`) * 100) AS `profit_percent`
            from `tbl_invoice_products_details` `d` 
            join `tbl_invoices` `i` on `i`.`Invoice_ID_Auto` = `d`.`Invoice_ID_Auto` 
            join `tbl_stock_uom` `uc` on((`uc`.`UOM_ID` = `d`.`UOM_ID`))
            where i.is_committed = 1
            union all
            select i.Person_ID as Customer_ID,d.Product_ID,(d.Return_Product_Quantity *(-1)) as Quantity,
            (d.Return_Product_Total  * -1) as Product_Total_Price,i.date_created ,i.Return_Invoice_Date as Date,i.Currency_ID,i.current_year_id,
            i.Logged_ID,i.created_logged_id,i.Is_Actual as is_actual,i.branch_id as branch_id,i.customer_branch_id ,(d.vat_amount  * -1) as vat_amount,(d.vat2_amount  * -1) as vat2_amount,
            d.Item_Quantity_Current,`d`.`unit_cost` AS `Product_Cost`,0 as total_tax,d.UOM_ID as current_uom_id,1 as is_committed,d.Return_Item_ID as Entery_ID,
            ((`d`.`Return_Product_Total` - (`d`.`Return_Product_Quantity` * `d`.`unit_cost`))*-1) AS `profit`,1 as is_return,
            ((((`d`.`Return_Product_Total` - (`d`.`Return_Product_Quantity` * `d`.`unit_cost`)) / `d`.`Return_Product_Total`) * 100)*-1) AS `profit_percent`
            from tbl_accounting_return_items d join tbl_accounting_return_invoices i 
            on d.Return_Invoice_ID = i.Return_Invoice_ID) u join tbl_stock_products p on u.Product_ID = p.Product_ID 
            join tbl_common_currency c on c.Currency_ID = u.Currency_ID left join tbl_stock_uom um 
            on um.UOM_ID = if(p.default_view_uom_id=0,p.UOM_ID,p.default_view_uom_id)
            join `tbl_stock_uom` `uc` on((`uc`.`UOM_ID` = `u`.`current_uom_id`))
            ) as movement';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group, 'ORDER BY date_created asc');
        echo json_encode($data);
    }

    public function itemProfitReportRequest() {
        $profit = $this->_registry->invoice->setData($_GET)->getTotalItemProfit();
        die(json_encode($profit));
    }

    public function PrintBarCode() {

        //                                                                                                                $barcode_data=$_GET;
        //                                                                                                                
        //                                                                                                                $barcodeobj = new TCPDFBarcode($_GET['Code'], 'C128');
        //                                                                                                                $barcode_data['barcode_html']= $barcodeobj->getBarcodeHTML(1, 15, '#000');
        //                                                                                                                $html=Forms::build_print_template('barcode', $barcode_data);
        //                                                                                                                Forms::print_html_template($html, 'barcode',array("repeat"=>$_GET['repeat']));
        //                                                                                                                die();
        $print = $this->_registry->Product->setData($_GET)->printBarCode();
    }
    public function print_production_barcode() {
        $print = $this->_registry->Product->setData($_GET)->print_production_barcode();
     }

    public function editInvoice() {
        if ($_POST['IsSalesMode']) {
            $update = $this->_registry->invoice->setData($_POST)->editInvoice(true);
            //                                                                                                                            die(print_r($update));
            die(json_encode(is_numeric($update[0]) ? ['OK', $update[0], $update[1]] : $update ));
        } else {
            $update = $this->_registry->purchase->setData($_POST)->editPurchase(true);
            die(json_encode(is_numeric($update[0]) ? ['OK', $update[0], $update[1]] : $update[0] ));
        }
        //                                                                                                                        die(json_encode(empty($update) ? ["OK"] : $update[0]));
    }

    public function editSalesPurchaseAjax() {


        $logged_id = Session::getUserID();
        $_POST['Logged_ID'] = $logged_id;
        if ($_POST['is_return'] == 1) {
            $salesPurchase = $this->_registry->salesPurchase->setData($_POST)->insertSalesPurchaseReturn(true);
        } else {
            $salesPurchase = $this->_registry->salesPurchase->setData($_POST)->insertSalesPurchase(true);
        }
        //        die(empty($sales) ? "OK" : $sales[0]);
        die(json_encode(is_numeric($salesPurchase[0]) ? ['OK', $salesPurchase[0], $salesPurchase[1]] : $salesPurchase[0] ));
    }

    public function HistoryReportForItem() {
        $current_date = $_GET['freq'];
        $data = $this->_registry->Product->setData($_GET)->mainItemsHistory($current_date);
        die(json_encode($data));
    }

    public function ReturnNoInvoice() {
        $insert = $this->_registry->return->setData($_POST)->ReturnNoInvoice();
        die(json_encode(is_numeric($insert) ? ['OK', $insert] : $insert ));
    }

    public function editReturnNoInvoice() {
        $insert = $this->_registry->return->setData($_POST)->editReturnNoInvoice();
        die(json_encode(is_numeric($insert) ? ['OK', $insert] : $insert ));
    }

    public function add_exchange() {
        $_POST['products'] = $_POST['Products'];
        $_POST['is_actual'] = $_POST['Is_Actual'];
        $_POST['Discount_Amount'] = $_POST['discount_amount'];
        $_POST['Invoice_Sub_Total'] = $_POST['Return_Invoice_Total'];
        $_POST['Paid_Amount'] = $_POST['Cash_Amount'] + $_POST['Check_Amount'] + $_POST['Card_Amount'];
        $_POST['cash_amount'] = $_POST['cash_cat_amount'] = $_POST['Cash_Amount'];
        $_POST['Invoice_Description'] = $_POST['Return_Invoice_Note'];
        $_POST['Net_Price'] = $_POST['Invoice_Net_Total'];
        $_POST['Invoice_Currency'] = $_POST['Currency_ID'];
        $_POST['Logged_ID'] = smc_session()['user_logged_id'];
        $_POST['Invoice_Shipping'] = $_POST['table_id'] = $_POST['pos_customer_id'] = $_POST['is_delivery'] = $_POST['service_value'] = 0;
        $_POST['invoice_unpaid_amount'] = $_POST['other_amount'] = $_POST['Invoice_Net_Total'] - ($_POST['Paid_Amount']);
        $_POST['Delivery_Date'] = $_POST['Delivery_Time'] = $_POST['postponed_note'] = '';
        $_POST['check_credit'] = $_POST['Check_Amount'] + $_POST['Card_Amount'];
        $_POST['invoice_type'] = 1;
        $_POST['posponted_status'] = $_POST['Persons_Count'] = 0;
        $_POST['is_committed'] = 1;
        $insert = $this->_registry->invoicepos->add_exchange($_POST);
        die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert[0] ));
    }

    public function edit_exchange() {
        $_POST['products'] = $_POST['Products'];
        $_POST['is_actual'] = $_POST['Is_Actual'];
        $_POST['Discount_Amount'] = $_POST['discount_amount'];
        $_POST['Invoice_Sub_Total'] = $_POST['Return_Invoice_Total'];
        $_POST['Paid_Amount'] = $_POST['Cash_Amount'] + $_POST['Check_Amount'] + $_POST['Card_Amount'];
        $_POST['cash_amount'] = $_POST['cash_cat_amount'] = $_POST['Cash_Amount'];
        $_POST['Invoice_Description'] = $_POST['Return_Invoice_Note'];
        $_POST['Net_Price'] = $_POST['Invoice_Net_Total'];
        $_POST['Invoice_Currency'] = $_POST['Currency_ID'];
        $_POST['Logged_ID'] = smc_session()['user_logged_id'];
        $_POST['Invoice_Shipping'] = $_POST['table_id'] = $_POST['pos_customer_id'] = $_POST['is_delivery'] = $_POST['service_value'] = 0;
        $_POST['invoice_unpaid_amount'] = $_POST['other_amount'] = $_POST['Invoice_Net_Total'] - ($_POST['Paid_Amount']);
        $_POST['Delivery_Date'] = $_POST['Delivery_Time'] = $_POST['postponed_note'] = '';
        $_POST['check_credit'] = $_POST['Check_Amount'] + $_POST['Card_Amount'];
        $_POST['invoice_type'] = 1;
        $_POST['posponted_status'] = $_POST['Persons_Count'] = 0;
        $_POST['Invoice_Status'] = 1;
        $_POST['is_committed'] = 1;

        $update = $this->_registry->invoicepos->edit_exchange($_POST);
        die(json_encode(is_numeric($update[0]) ? ['OK', $update[0], $update[1]] : $update[0] ));
    }

    public function addScale() {
        $insert = $this->_registry->Product->setData($_POST)->addScale();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function updateScale() {
        $update = $this->_registry->Product->setData($_POST)->updateScale();
        die(empty($update) ? 'OK' : 'error');
    }

    public function deleteScale() {
        $delete = $this->_registry->Product->setData($_POST)->deleteScale();
        die(empty($delete) ? 'OK' : 'error');
    }

    public function scaleList() {
        $_GET['scale_types_arr'] = CommonFunctions::get_scale_types();
        $columns = array(
            array('db' => 'scale_name', 'dt' => 0),
            array('db' => 'scale_ip', 'dt' => 1),
            array('db' => 'scale_ip', 'dt' => 2, "formatter" => function($d) {
                    $ping = CommonFunctions::check_ping_ip($d);
                    $Statuses = ["Online#label-info", "Offline#label-important"];
                    return '<span class="my-ip label ' . explode("#", ($ping ? $Statuses[0] : $Statuses[1]))[1] . '" data-status="' . $d . '" >' . explode("#", ($ping ? $Statuses[0] : $Statuses[1]))[0] . '</span>';

                    //                return ($ping ? 'online' : 'offine');
                }),
            array('db' => 'Class_Name', 'dt' => 3, "formatter" => function($d, $row) {
                    return '<span class="scale-class" data-class-name="' . $d . '" data-class="' . $row['class_id'] . '" data-scale_type="' . $row['scale_type'] . '">' . $d . '</span>';
                }),
            array('db' => 'scale_type', 'dt' => 4, "formatter" => function($d, $row) {
                    return $_GET['scale_types_arr'][$d];
                }),
            array('db' => 'scale_id', 'dt' => 5, "formatter" => function($d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil"
                                    ],
                                    ["title" => CommonLanguage::getMessage("sync"),
                                        "class" => "sync",
                                        "icon" => "fa-refresh"
                                    ],
                                    ["title" => CommonLanguage::getMessage("reset"),
                                        "class" => "reset",
                                        "icon" => "fa-recycle",
                                        "data-target" => "#ResetScaleModal"
                                    ]
                    ]]);
                    return $html;
                }), 'class_id', 'scale_type'
        );
        $key = 'scale_id';
        $table = 'scale_view';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function assign_product_key() {
        $assign = $this->_registry->Product->setData($_POST)->assign_product_key();
        $products = $this->_registry->Product->getKeysProducts($_POST['scale_id']);
        $grid = Forms::build_key_products($products);
        die(json_encode(empty($assign) ? ['OK', $grid] : ['error']));
    }

    public function unregister_product_key() {
        $assign = $this->_registry->Product->setData($_POST)->unregister_product_key();
        $products = $this->_registry->Product->getKeysProducts($_POST['scale_id']);
        $grid = Forms::build_key_products($products);
        die(json_encode(empty($assign) ? ['OK', $grid] : ['error']));
    }

    public function assign_product_skip_key() {
        $assign = $this->_registry->Product->setData($_POST)->assign_product_skip_key();
        $products = $this->_registry->Product->setData($_POST)->getSkipKeysProducts();
        $grid = Forms::build_skip_key_products($products);
        die(json_encode(empty($assign) ? ['OK', $grid] : ['error']));
    }

    public function unregister_product_skip_key() {
        $assign = $this->_registry->Product->setData($_POST)->unregister_product_skip_key();
        $products = $this->_registry->Product->setData($_POST)->getSkipKeysProducts();
        $grid = Forms::build_skip_key_products($products);
        die(json_encode(empty($assign) ? ['OK', $grid] : ['error']));
    }

    public function product_keys_by_scale() {
        $products = $this->_registry->Product->getKeysProducts($_GET['scale_id']);
        $grid = Forms::build_key_products($products);
        die($grid);
    }

    public function product_skip_keys() {
        $products = $this->_registry->Product->setData($_GET)->getSkipKeysProducts();
        $grid = Forms::build_skip_key_products($products);
        die($grid);
    }

    public function syncScaleProducts() {
        $sync = $this->_registry->Product->syncScaleProducts($_POST['sid']);
        die(empty($sync) ? 'OK' : 'error');
    }

    public function resetScale() {
        $ping = CommonFunctions::check_ping_ip($_POST['scale_ip']);
        if (!$ping) {
            die(CommonLanguage::getMessage('check_scale_online'));
        } else {
            $reset = $this->_registry->Product->setData($_POST)->resetAllScale();
            die($reset ? 'OK' : $reset[0]);
        }
    }

    public function userInvoicesReport() {
        $condition = $_GET['user'] == 0 ? '' : ' and user = "' . $_GET['user'] . '" ';
        $condition .= ' AND date_created >= "' . $_GET['From_Date'] . '" AND date_created <= "' . $_GET['To_Date'] . '"';
        //        $condition .= ' AND date_created >= STR_TO_DATE("' . $_GET['From_Date'] . '", "%Y-%m-%d %h:%i:%s %p") AND date_created <= STR_TO_DATE("' . $_GET['To_Date'] . '", "%Y-%m-%d %h:%i:%s %p") ';
        if (isset($_GET['salesman']) && $_GET['salesman'] != '') {
            $condition .= ' and Sales_ID = "' . $_GET['salesman'] . '"';
        }
        if ($_GET['type'] != "0") {
            $condition .= ' and type = "' . $_GET['type'] . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $condition .= ' and is_actual = 0 ';
        }
        if (!empty($_GET['class_id'])) {
            $condition .= ' AND class_id ="' . $_GET['class_id'] . '"';
        }
        if (is_numeric($_GET['customer_id'])) {
            $condition .= ' AND current_customer_id ="' . $_GET['customer_id'] . '"';
            if (!empty($_GET['customer_branch_id']))
                $condition .= ' AND customer_branch_id ="' . $_GET['customer_branch_id'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $condition .= ' AND branch_id ="' . $_GET['branch_id'] . '"';
        }
        if (!empty($_GET['created_by'])) {
            $condition .= ' AND created_logged_id ="' . $_GET['created_by'] . '"';
        }
        if (!empty($_GET['shipping_company_id'])) {
            $condition .= ' AND shipping_company_id ="' . $_GET['shipping_company_id'] . '"';
        }
        if (!empty($_GET['shipping_status_id'])) {
            $condition .= ' AND shipping_status_id ="' . $_GET['shipping_status_id'] . '"';
        }
        if (!empty($_GET['pick_up_from_date']) && !empty($_GET['pick_up_to_date'])) {
            $condition .= ' and pick_up_date between "' . $_GET['pick_up_from_date'] . '" AND  "' . $_GET['pick_up_to_date'] . '"';
        }
        if (!empty($_GET['drop_off_from_date']) && !empty($_GET['drop_off_to_date'])) {
            $condition .= ' and drop_off_date between "' . $_GET['drop_off_from_date'] . '" AND  "' . $_GET['drop_off_to_date'] . '"';
        }
        if (!empty($_GET['invoice_from_date']) && !empty($_GET['invoice_to_date'])) {
            $condition .= ' and inv_date between "' . $_GET['invoice_from_date'] . '" AND  "' . $_GET['invoice_to_date'] . '"';
        }

        $_GET['local_sym'] = CurrencyFactory::getLocalCurrencySymbol();
        $total_var = empty($_GET['exclude_shipping']) ? 'total' : 'total_no_shipping';
        $columns = array(array('db' => 'id', 'dt' => 0, "formatter" => function($d, $row) {
                    return $row['type'] == 'Invoice' ? (!$this->controller_permission->hasPermission('ViewSalesInvoice') ? $d : '<a  href="javascript:;" class="openFrame" data-src="Inventory/ViewInvoice/' . $row['current_id'] . '/?is_pop=1">' . $d . '</a>') : (!$this->controller_permission->hasPermission('ViewReturnDebit') ? $d : '<a  href="javascript:;" class="openFrame" data-src="Inventory/ViewReturnDebit/' . $row['current_id'] . '?is_pop=1">' . $d . '</a>');
                }), array('db' => 'customer_name', 'dt' => 1, "formatter" => function($d) {
                    return $d ? $d : '-- --';
                }), 'inv_date', 'date_created', array('db' => $total_var, 'dt' => 4, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d * $row[8]);
                }), array('db' => 'discount', 'dt' => 5, "formatter" => function($d, $row) {
                    return $d != '' ? CommonFunctions::formatNumber($d * $row[8]) : '-- --';
                }), 'type', 'currency', 'current_rate', 'current_id');
        $key = 'id';
        $table = 'user_invoices';
        if (empty($_GET['order'][0]['column'])) {
            $_GET['order'][0]['column'] = 2;
            $_GET['order'][0]['dir'] = 'desc';
        }
        $data = DataTable::complex($_GET, $table, $key, $columns, ' is_committed = 1 ' . $condition);
        echo json_encode($data);
    }

    public function getUserInvoiceTotals() {
        $sales_id = !empty($_GET['salesman']) ? $_GET['salesman'] : 0;
        $data = $this->_registry->invoice->setData($_GET)->totalUserInvoices($_GET['From_Date'], $_GET['To_Date'], $_GET['user'], $sales_id, $_GET['is_actual']);
        die(json_encode($data));
    }

    public function PricingListRequest() {
        //        $time_start = microtime(true);
        $cond = '';
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        /*if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and multi_branch_id in (' . ($_GET['search_branch_id']) . ') OR multi_branch_id LIKE "' . ($_GET['search_branch_id']) . ',%" OR multi_branch_id LIKE "%,' . ($_GET['search_branch_id']) . ',%" OR multi_branch_id like "%,' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and (multi_branch_id in (' . (smc_session()['user_accounts']['branch_id']) . ') OR multi_branch_id LIKE "' . (smc_session()['user_accounts']['branch_id']) . ',%" OR multi_branch_id LIKE "%,' . (smc_session()['user_accounts']['branch_id']) . ',%" OR multi_branch_id like "%,' . (smc_session()['user_accounts']['branch_id']) . '" ) ' ;
        } */

        if (!empty($_GET['Category_ID']))
            $cond .= ' and p.Category_ID IN (' . $_GET['Category_ID'] . ') ';
        if (!empty($_GET['Brand_ID']))
            $cond .= ' and p.brand_id IN (' . $_GET['Brand_ID'] . ') ';
        if (!empty($_GET['family_id']))
            $cond .= ' and p.family_id IN (' . $_GET['family_id'] . ') ';
        //        if (!empty($_GET['main_supplier']))
        //            $cond .= ' and ppc.supplier_id ="' . $_GET['main_supplier'] . '" ';
        if (empty($_GET['Class_ID']))    //required to specify the class or will get same product uom multi times
            $cond .= ' and 1=2 ';   //$_GET['Class_ID'] = smc_session()['pricing_class_id'];

        if (!empty($_GET['class_zero_price'])) {
            $prod_ids = array();
            $query = $this->db->query('select Product_ID from tbl_item_price_by_classes
                where Class_ID = "' . $_GET['class_zero_price'] . '" and Product_Price=0');
            while ($row = $this->db->assoc($query))
                $prod_ids[] = $row['Product_ID'];
            if (!empty($prod_ids))
                $cond .= ' and p.Product_ID in (' . implode(',', $prod_ids) . ') ';
        }








        //        if(!empty($_GET['purchase_id']))
        //            $cond.=' and p.Product_ID in ('.$_GET['prod_ids'].') ';
        $class_arr = empty($_GET['class_ids']) ? array() : explode(",", $_GET['class_ids']);
        $class_full_arr = empty($_GET['Class_ID']) ? array() : $_GET['Class_ID'];
        $class_cond = '';
        $_GET['has_cost_perm'] = (($_GET['is_supp'] && $this->controller_permission->hasPermission('view_cost_supp_pricing_list')) || (!$_GET['is_supp'] && $this->controller_permission->hasPermission('view_cost_pricing_list')));
        $crnt_col_no = $_GET['has_cost_perm'] ? 3 : 2;
        $col_no_aftr_class = $crnt_col_no + count($class_arr);

        if (!empty($class_arr)) {
            $class_id = $class_arr[0];
            $class_currency_query = $this->db->query('select class.Currency_ID,currency.Currency_Symbol from tbl_pricing_class `class` inner join tbl_common_currency currency using(Currency_ID) where class.Class_ID = "' . $class_id . '"');
            $row = $this->db->assoc($class_currency_query);
            $first_class_currency = $row['Currency_ID'];
            $first_currency_symbol = $row['Currency_Symbol'];
        }
        if (empty($first_class_currency)) {
            $first_class_currency = smc_session()['local_currency'];
            $first_currency_symbol = smc_session()['local_currency_symbol'];
        }
        $columns = array(
            array('db' => 'Product_Code', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1, 'full_search' => true),
            array('db' => 'UOM_Name', 'dt' => 2),
        );
        if ($_GET['has_cost_perm']) {
            $columns[] = array('db' => 'Product_ID', 'dt' => 3, 'formatter' => function($d, &$row) use( $col_no_aftr_class, $first_class_currency, $first_currency_symbol) {
                    $last_product_cost = CommonFunctions::public_round_number(CommonBusiness::viewLastProductCost($row[$col_no_aftr_class + 1])*$row['conversion_amount']);
                    $value = CommonFunctions::public_round_number(CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $first_class_currency, $last_product_cost));
                    $row['tmp_last_cost_in_local'] = $last_product_cost;
                    return CommonFunctions::public_round_number($value) . ' ' . $first_currency_symbol;
                });
        }
        foreach ($class_full_arr as $class_details) {
            $class_id = $class_details['id'];
            $is_virtual = $class_details['is_virtual'];
            $columns[] = array('db' => ($_GET['is_disc'] == 1 ? 'ClassDisc' : ($_GET['is_amt'] == 1 ? 'ClassAftrDisc' : 'ClassPrices')), 'dt' => ++$crnt_col_no, "formatter" => function($d, $row, $is_export) use($class_id, $col_no_aftr_class, $is_virtual) {
                    $main_price = 0;
                    $class_price = 0;
                    $classes_prices_str = "||{$d}||";

                    $class_id_pos = strpos($classes_prices_str, "||{$class_id}__");
                    $class_currency = 0;
                    if ($class_id_pos !== false) {
                        $class_id_pos += 2; //for || sep
                        $classes_prices_str = substr($classes_prices_str, $class_id_pos);
                        $classes_prices_str = substr($classes_prices_str, 0, strpos($classes_prices_str, "||"));
                        $str_arr = explode('__', $classes_prices_str);
                        $class_price = $str_arr[1];
                        $class_currency = $str_arr[2];
                        $main_price = $str_arr[3];
                        //                        return $class_price.'=='.$class_currency;
                        //                        $class_price = substr($classes_prices_str, strpos($classes_prices_str, "__") + 2);
                    }
                    $percent_span = '';
                    if (!empty($_GET['purchase_id'])) {
                        $class_local_price = CommonFunctions::public_round_number(CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $class_currency, $class_price));
                        $percent = 100;   //if no cost then full profit 100%
                        if ($row['tmp_last_cost_in_local'] > 0)
                            $percent = (($class_local_price - $row['tmp_last_cost_in_local']) / ($row['tmp_last_cost_in_local'] * 100));
                        $percent_span = '<span class=" percent-span bold ' . ($percent < 0 ? 'red-star' : '') . '">' . (CommonFunctions::public_round_number($percent) . ' %') . '</span>';
                    }
                    if ($is_virtual == 1)
                        $class_price = $main_price = CommonFunctions::public_round_number(Product::get_product_price($row['Product_ID'], $class_id, $row[$col_no_aftr_class + 2]));
                    if ($is_export)
                        return CommonFunctions::public_round_number($class_price);
                    return '<span class="print-only">' . CommonFunctions::public_round_number($class_price) . '</span>' . ($_GET['is_amt'] == 1 ? '<span class="bold" style="font-size:11px;">' . CommonFunctions::public_round_number($main_price) . '&nbsp;&nbsp;</span>' : '') . '<input class="PriceVal no-print" type="text" value="' . CommonFunctions::public_round_number($class_price) . '" main-price="' . CommonFunctions::public_round_number($main_price) . '" data-class="' . $class_id . '" data-id="' . $row[$col_no_aftr_class + 1] . '" data-uom="' . $row[$col_no_aftr_class + 2] . '" data-uom-conv = "' . $row['conversion_amount'] . '"  ' . ($_GET['has_cost_perm'] ? 'data-cost="' . CommonFunctions::public_round_number($row['tmp_last_cost_in_local']) . '" ' : '') . ($is_virtual == 0 ? '' : 'readonly') . ' data-is-virtual="' . $is_virtual . '">&nbsp;' . $percent_span . '';
                    //                return '<span class="print-only">' . number_Xformat($class_price, 2) . '</span><input class="PriceVal no-print" type="text" value="' . $class_price . '" data-class="' . $class_id . '" data-id="' . $row[$col_no_aftr_class + 1] . '" data-uom="' . $row[$col_no_aftr_class + 2] . '" data-uom-conv = "' . $row['conversion_amount'] . '" data-cost="' . $row['tmp_last_cost_in_local'] . '" ' . ($is_virtual == 0 ? '' : 'readonly') . ' data-is-virtual="' . $is_virtual . '">&nbsp;' . $percent_span . '';
                });
        }
        $columns[] = array('db' => 'Product_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'UOM_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Currency_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'conversion_amount', 'dt' => ++$crnt_col_no);
        if (!empty($_GET['bar_code'])) {
            $cond .= ' and uc.Bar_Code = "' . $_GET['bar_code'] . '"';
        }
        if (!empty($_GET['search_branch_id'])) {
            $cond .= ' and p.branch_id = "' . $_GET['search_branch_id'] . '"';
        }

        //
        $key = 'unq_col';
        if (empty($_GET['purchase_id'])) {
            $table = '(SELECT concat(p.Product_ID,"_",u.UOM_ID) as unq_col,p.branch_id, p.Product_ID,p.Product_Code,p.Product_Name,p.Category_ID,p.brand_id,u.UOM_Name,u.UOM_ID,uc.conversion_amount,ppc.Currency_ID
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",c.Product_Price,"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassPrices
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",c.product_disc,"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassDisc
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",((100-c.product_disc)*c.Product_Price/100),"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassAftrDisc
                    FROM tbl_stock_products p
                        inner join `tbl_uom_conversions` uc on p.Product_ID = uc.Product_ID
                        inner join tbl_stock_uom u on u.UOM_ID = uc.uom_from
                        left join `tbl_item_price_by_classes` c on c.Product_ID = p.Product_ID and uc.uom_from = c.UOM_ID  ' . (empty($_GET['class_ids']) ? ' and 1=2 ' : ' AND c.Class_ID in (' . $_GET['class_ids'] . ') ') . '
                    left join tbl_pricing_class ppc on ppc.Class_ID = c.Class_ID
                    where true ' . $cond . ' group by p.Product_ID, u.UOM_ID
                         order by p.Product_ID asc, uc.conversion_amount asc
                     )  as pricing_table';
            //            echo $table;die();
            if (empty($_GET['order'][0]['column'])) {
                $_GET['order'][0]['column'] = 1;    //sort by product name
                $_GET['order'][0]['dir'] = 'asc';
            }
        } else {
            $table = '(SELECT concat(p.Product_ID,"_",u.UOM_ID) as unq_col, p.Product_ID,p.branch_id,p.Product_Code,p.Product_Name,p.Category_ID,p.brand_id,u.UOM_Name,uc.conversion_amount,uc.uom_from as UOM_ID,ppc.Currency_ID
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",c.Product_price,"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassPrices
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",c.Product_price,"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassDisc
            ,group_concat(if(isnull(c.Class_ID),"__0",concat(c.Class_ID,"__",((100-c.product_disc)*c.Product_Price/100),"__",ppc.Currency_ID,"__",c.Product_Price)) SEPARATOR "||") as ClassAftrDisc

                    FROM tbl_inventory_purchase_items pur join tbl_stock_products p
                        on pur.Product_ID = p.Product_ID and pur.Purchase_ID_Auto="' . $_GET['purchase_id'] . '"
                        inner join `tbl_uom_conversions` uc on p.Product_ID = uc.Product_ID
                        inner join tbl_stock_uom u on u.UOM_ID = uc.uom_from
                        left join `tbl_item_price_by_classes` c on c.Product_ID = p.Product_ID and uc.uom_from = c.UOM_ID  ' . (empty($_GET['class_ids']) ? ' and 1=2 ' : ' AND c.Class_ID in (' . $_GET['class_ids'] . ') ') . '
                        left join tbl_pricing_class ppc on ppc.Class_ID = c.Class_ID
                        where true ' . $cond . ' group by p.Product_ID, u.UOM_ID
                         order by pur.Item_ID asc
                     )  as pricing_table';
        }


        $data = DataTable::complex($_GET, $table, $key, $columns);
        //      
        //         $time_end = microtime(true);
        //        echo $time_end - $time_start;

        echo json_encode($data);
    }

    public function ProductBranchesAjax() {
        $_GET['branches'] = CommonFunctions::CommonView('tbl_organization_branches');
        $_GET['printers'] = CommonFunctions::CommonView('tbl_printers');
        $cond = '';
        if (empty($_GET['product_options']))
            $cond .= ' and 1=2 ';

        if (!empty($_GET['Category_ID']))
            $cond .= ' and Category_ID  ="' . $_GET['Category_ID'] . '" ';
        if (!empty($_GET['product_name']))
            $cond .= ' and Product_Name LIKE "%' . $_GET['product_name'] . '%" ';
        $product_options_arr = empty($_GET['product_options']) ? array() : $_GET['product_options'];

        $crnt_col_no = 1;
        $col_no_aftr_options = $crnt_col_no + count($product_options_arr);
        $columns = array(
            array('db' => 'Product_Code', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1, "formatter" => function($d, $row) {
                    return '<span class="product_name_span" data-id="' . $row['Product_ID'] . '">' . $d . '</span>';
                })
        );
        foreach ($product_options_arr as $product_option) {
            $columns[] = array('db' => 'Product_ID', 'dt' => ++$crnt_col_no, "formatter" => function($d, $row) use($product_option, $col_no_aftr_options) {
                    if ($product_option == 1) {
                        $data = !empty($row['branch_id']) ? explode(',', $row['branch_id']) : '';
                        $select_content = '';
                        $select_content .= '<select data-id="' . $d . '"  name="product_branch_id" multiple  class="full-width "  data-init-plugin="select2">';
                        foreach ($_GET['branches'] as $branch) {
                            $select_content .= '<option ' . ((!empty($data) && in_array($branch['branch_id'], $data)) ? 'selected' : '') . ' value="' . $branch['branch_id'] . '">' . $branch['branch_name'] . '</option>';
                        }
                        $select_content .= '</select>';
                        return $select_content;
                    } else if ($product_option == 2) {
                        $data = !empty($row['printer_id']) ? explode(',', $row['printer_id']) : '';
                        $select_content = '';
                        $select_content .= '<select data-id="' . $d . '"  name="product_printer_id" multiple  class="full-width "  data-init-plugin="select2">';
                        foreach ($_GET['printers'] as $branch) {
                            $select_content .= '<option ' . ((!empty($data) && in_array($branch['printer_id'], $data)) ? 'selected' : '') . ' value="' . $branch['printer_id'] . '">' . $branch['printer_title'] . '</option>';
                        }
                        $select_content .= '</select>';
                        return $select_content;
                    } else if ($product_option == 3) {
                        return '<input class="PriceVal no-print" name="Product_Limit_Discount" type="text" value="' . $row['Product_Limit_Discount'] . '" >';
                    } else if ($product_option == 4) {
                        return '<input type="hidden"  name="product_family_id" value="' . (!empty($row['family_id']) ? $row['family_id'] : '') . '"  data-select-name="' . (!empty($row['family_name']) ? $row['family_name'] : '') . '"  class="full-width"/>';
                    } else if ($product_option == 5) {
                        return '<input type="hidden"  name="product_category_id" value="' . (!empty($row['Category_ID']) ? $row['Category_ID'] : '') . '"  data-select-name="' . (!empty($row['Category_ID']) ? $row['Cat_Name'] : '') . '"  class="full-width"/>';
                    } else if ($product_option == 6) {
                        return '<input class="" ' . ($row['Status_ID'] == 1 ? 'checked' : '') . ' name="Status_ID" type="checkbox" >';
                    } else if ($product_option == 7) {
                        return '<input type="hidden"  name="brand_id" value="' . (!empty($row['brand_id']) ? $row['brand_id'] : '') . '"  data-select-name="' . (!empty($row['brand_name']) ? $row['brand_name'] : '') . '"  class="full-width"/>';
                    } else if ($product_option == 8) {
                        return '<input class=" no-print" name="vat_percent" type="text" value="' . $row['vat_percent'] . '" >';
                    } else if ($product_option == 9) {
                        return '<input class=" no-print" name="vat2_percent" type="text" value="' . $row['vat2_percent'] . '" >';
                    } else if ($product_option == 10) {
                        return '<input class="PriceVal no-print" name="Product_Reorder_Point" type="number" value="' . $row['Product_Reorder_Point'] . '" >';
                    } else if ($product_option == 11) {
                        return '<input class=" no-print" name="positive_points" type="text" value="' . $row['positive_points'] . '" >';
                    } else if ($product_option == 12) {
                        return '<input class=" no-print" name="negative_points" type="text" value="' . $row['negative_points'] . '" >';
                    }
                });
        }
        $columns[] = array('db' => 'branch_id', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'printer_id', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Product_Limit_Discount', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'family_id', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Category_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Status_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'brand_id', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'brand_name', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'family_name', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Cat_Name', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'vat_percent', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'vat2_percent', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'Product_Reorder_Point', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'positive_points', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'negative_points', 'dt' => ++$crnt_col_no);

        $key = 'Product_ID';
        $table = 'product_list';

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

        echo json_encode($data);
    }

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

    //                                                                                                                                    public function PricingListRequest() {
    //                                                                                                                                        $cond = '';
    //                                                                                                                                        if (isset($_GET['Class_ID'])) {
    //                                                                                                                                            $cond .= ' AND c.Class_ID = "' . $_GET['Class_ID'] . '"';
    //                                                                                                                                        }
    //                                                                                                                                        $columns = array(
    //                                                                                                                                            array('db' => 'Product_Code', 'dt' => 0),
    //                                                                                                                                            array('db' => 'Product_Name', 'dt' => 1),
    //                                                                                                                                            array('db' => 'UOM_Name', 'dt' => 2),
    //                                                                                                                                            array('db' => 'Price', 'dt' => 3, "formatter" => function($d, $row) {
    //                                                                                                                                                    return '<input class="PriceVal" type="text" value="' . $d . '" data-id="' . $row[4] . '" data-uom="' . $row[5] . '">';
    //                                                                                                                                                }), array('db' => 'Product_ID', 'dt' => 4),
    //                                                                                                                                            array('db' => 'UOM_ID', 'dt' => 5)
    //                                                                                                                                        );
    //                                                                                                                                        $key = 'Product_ID';
    //                                                                                                                                        $table = '(SELECT p.Product_ID,p.Product_Code,p.Product_Name,if(isnull(c.`Product_Price`),0,c.Product_price) as Price,u.UOM_Name,c.UOM_ID 
    //                FROM tbl_stock_products p left join `tbl_item_price_by_classes` c 
    //                on c.Product_ID = p.Product_ID ' . $cond . ' left join tbl_stock_uom u on u.UOM_ID = c.UOM_ID order by p.Product_ID )  as pricing_table';
    //                                                                                                                                        $data = DataTable::complex($_GET, $table, $key, $columns);
    //                                                                                                                                        echo json_encode($data);
    //                                                                                                                                    }

    public function UserCustomersList() {
        $cond = ' 1=1 and (user_id = "' . $_GET['uid'] . '" or isnull(user_id)) ';
        $columns = array(
            array('db' => 'Account_Code', 'dt' => 1),
            array('db' => 'Customer_Name', 'dt' => 2),
            array('db' => 'Customer_Phone', 'dt' => 3),
            array('db' => 'Customer_Address', 'dt' => 4),
            array('db' => 'Customer_ID', 'dt' => 0, "formatter" => function($d, $row) {
                    $html = '<div class="checkbox check-primary  ">
                    <input type="checkbox"  class="chooseCust" id = "check' . $row[6] . '" value = "' . (is_null($row[5]) ? 0 : 1) . '" data-id="' . $d . '" ' . (is_null($row[5]) ? '' : 'checked') . '/>
             <label for="check' . $row[6] . '"></label>
                </div>';

                    //                $html = '<input type="checkbox" class="chooseCust" data-id="'.$d.'" '.(is_null($row[4]) ? '' : 'checked').'/>';
                    return $html;
                }),
            array('db' => 'user_id', 'dt' => 5),
            array('db' => '(@cnt := @cnt + 1)', 'dt' => 6),
        );
        $key = '(@cnt := @cnt + 1)';
        $table = 'user_customers  CROSS JOIN (SELECT @cnt := 0) AS dummy';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function assignUserCustomer() {
        $assign = $this->_registry->user->setData($_POST)->assignUserCustomer();
        die(empty($assign) ? 'OK' : 'error');
    }

    public function salesConsolidateByUser() {
        $data = $this->_registry->sales->setData($_GET)->salesConsilidateByUser($_GET['user'], $_GET['From_Date'], $_GET['To_Date'], $_GET['is_actual']);
        $html = Forms::build_table_html($data);
        die($html);
        //                                                                                                                                echo json_encode(array("data" => $data, "draw" => 1, "recordsFiltered" => count($data), "recordsTotal" => count($data)));
    }

    public function dailyActivityByUser() {
        $_GET['local_symbol'] = smc_session()['local_currency_symbol'];
        $cond = ' Date <= "' . $_GET['To_Date'] . '" and Date >= "' . $_GET['From_Date'] . '"';
        if (!empty($_GET['user'])) {
            $cond .= ' and Logged_ID = "' . $_GET['user'] . '"';
        }
        if (!empty($_GET['sales_man_id'])) {
            $cond .= ' and Sales_ID = "' . $_GET['sales_man_id'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_id'] . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        $columns = array(
            array('db' => 'User_Name', 'dt' => 0),
            array('db' => 'Date', 'dt' => 1),
            array('db' => 'Name', 'dt' => 2),
            array('db' => 'type', 'dt' => 3),
            array('db' => 'number', 'dt' => 4),
            array('db' => 'invoice_total', 'dt' => 5, "formatter" => function($d) {
                    return $_GET['local_symbol'] . ' ' . CommonFunctions::public_round_number($d);
                }),
            array('db' => 'paid_amount', 'dt' => 6, "formatter" => function($d) {
                    return $_GET['local_symbol'] . ' ' . CommonFunctions::public_round_number($d);
                })
        );
        $key = '(@cnt := @cnt + 1)';
        $table = 'user_activities  CROSS JOIN (SELECT @cnt := 0) AS dummy';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function invoiceDistByCustomer() {
        $_GET['local_symbol'] = smc_session()['local_currency_symbol'];
        $cond = ' Invoice_Date <= "' . $_GET['To_Date'] . '" and Invoice_Date >= "' . $_GET['From_Date'] . '" and is_committed = 1 ';
        if (isset($_GET['customer']) && $_GET['customer'] != '') {
            $cond .= ' and Customer_ID = "' . $_GET['customer'] . '"';
            if (!empty($_GET['customer_branch_id']))
                $cond .= ' and customer_branch_id = "' . $_GET['customer_branch_id'] . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0';
        }
        if (!empty($_GET['sales_man_id'])) {
            $cond .= ' and Sales_ID = "' . $_GET['sales_man_id'] . '"';
        }
        if (!empty($_GET['group_id'])) {
            $cond .= ' and customer_group_id = "' . $_GET['group_id'] . '"';
        }
        if (!empty($_GET['class_id'])) {
            $cond .= ' and customer_class_id = "' . $_GET['class_id'] . '"';
        }
        $columns = array(
            array('db' => 'Customer_Name', 'dt' => 0),
            array('db' => 'sum(invoice_total)', 'dt' => 1, "formatter" => function($d, $row, $is_excel) {
                    return ($is_excel ? '' : $_GET['local_symbol'] . ' ' ) . CommonFunctions::public_round_number($d);
                }),
            array('db' => 'count(Invoice_ID)', 'dt' => 2)
        );
        $key = 'Customer_ID';
        $table = 'customer_invoice_distribution';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, 'group by Customer_ID');
        echo json_encode($data);
    }

    public function addProductionTemplate() {
        $insert = $this->_registry->production->setData($_POST)->add_production_template();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function update_production_template() {
        $update = $this->_registry->production->setData($_POST)->update_production_template();
        die(empty($update) ? 'OK' : 'error');
    }

    public function production_template_list() {
        $cond = ' 1=1 ';
        if (isset($_GET['is_adv']))
            $cond .= ' and template_type="' . $_GET['is_adv'] . '" ';
        $columns = array(
            array('db' => 'template_name', 'dt' => 0),
            array('db' => 'template_id', 'dt' => 1, "formatter" => function($d) {
                    $html = Forms::action_snippet(["color" => "success-dark", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "Edit",
                                "icon" => "fa-pencil"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => ($_GET['is_adv'] == 1 ? "delete_adv_production_template" : "delete_production_template")
                                    ],
                                    ["title" => CommonLanguage::getMessage("copy"),
                                        "class" => "copy",
                                        "icon" => "fa-copy",
                                        "permission" => ($_GET['is_adv'] == 1 ? "copy_adv_production_template" : "copy_production_template")
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'template_id';
        $table = 'tbl_production_template';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function production_process_list() {
        $cond = ' ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '" ';
        if (!empty($_GET['barcode'])){
        $cond .= ' and barcode_nb ="' . $_GET['barcode'] . '"  ';
        }else{
            $cond .= ' and p.states_name ="Pending"  ';
        }

            $columns = array('template_name', 'date', 'barcode_nb', array('db' => 'position_name', 'dt' => 3, "formatter" => function($d) {
                    $html = Forms::action_snippet(["color" => "success-dark", "isDropDown" => false, "data_id" => $d,
                                "ActionOption" => [["title" => $d,
                                "class" => "color_$d"
                                    ]
                    ]]);
                    return $html;
                }),
            array('db' => 'process_id', 'dt' => 4, "formatter" => function($d) {
                    $html = Forms::action_snippet(["color" => "success-dark", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "Edit",
                                "attr" => "data-id={$d}",
                                "data-target" => "#add_production_process",
                                "icon" => "fa-pencil",
                                "permission" => "edit_production_process"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_production_process"
                                    ]
                                    ,
                                    ["title" => CommonLanguage::getMessage("print"),
                                        "class" => "print",
                                        "icon" => "fa-print",
                                        "permission" => "print_production_process"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'process_id';
        $table = ' (SELECT
        t.template_name,
        l.line_name,
        p.date,
        p.process_id,
        p.barcode_nb,
        p.states_name,
        p.production_color_id,
        co.position_name
    FROM
        tbl_production_process p
    JOIN tbl_production_template t USING(template_id)
    LEFT JOIN tbl_line l USING(line_id)
    LEFT JOIN tbl_production_color co
    ON co.id = p.production_color_id
    where 1=1    
    ' . $cond . ' ) as temp ';
        $options = array();
        $options['order'] = ' `date` desc,process_id desc';
        $data = DataTable::complex($_GET, $table, $key, $columns, null, null, null, $options);
        echo json_encode($data);
    }

    public function get_production_template_id() {
        $data = $this->_registry->production->get_production_template_id($_GET['id'], $_GET['with_optional']);
        die(json_encode($data));
    }

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

    public function add_production_process() {
        $insert = $this->_registry->production->setData($_POST)->add_production_process();
        die(json_encode(empty($insert) ? ['OK'] : $insert));
    }

    public function update_production_process() {
        $update = $this->_registry->production->setData($_POST)->update_production_process();
        die(json_encode(empty($update) ? ['OK'] : $update));
    }

    public function deleteProductionProcess() {
        $delete = $this->_registry->production->setData($_GET)->deleteProductionProcess();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function invoiceFiles() {
        $cond = ' type_id = 1 ';
        $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" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("invoice"),
                                "class" => "Edit",
                                "icon" => "fa-pencil",
                                "href" => "Inventory/addpurchase/sales/collector/" . $d
                                    ],
                                    ["title" => CommonLanguage::getMessage("Transfers"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil",
                                        "href" => "Stock/RequestOrder/transfer/collector/" . $d
                                    ]
                    ]]);


                    //                                                                                                                                                                    $html = '<a href="' . SITE_LINK . 'Inventory/appInvoice/' . $d . '"><button class="btn View" data-id="' . $d . '" data-toggle="modal" data-target="">
                    //                                                                                                                                            <i class="fa fa-money"></i> ' . CommonLanguage::getMessage('invoice') . ' </button></a>
                    //                                                                                                                                            <a href="' . SITE_LINK . 'Stock/RequestOrder/app/' . $d . '"><button class="btn transfer" data-id="' . $d . '" data-toggle="modal" data-target="">
                    //                                                                                                                                            <i class="fa fa-money"></i> ' . CommonLanguage::getMessage('Transfers') . '  </button></a>';
                    //                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                    //                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                    //                                "class" => "View",
                    //                                "icon" => "fa-money",
                    //                                "href" => "Inventory/appInvoice/{$d}"
                    //                                    ]
                    //                    ]]);
                    return $html;
                }
            )
        );
        $key = 'file_id';
        $table = 'app_files';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function SalesPurchaseListRequests() {
        $cond = '';
        if (isset($_GET['Date_From']) && isset($_GET['Date_To'])) {
            $FromDate = $_GET['Date_From'];
            $ToDate = $_GET['Date_To'];
            $cond .= ' Date >= "' . $FromDate . '" AND Date <= "' . $ToDate . '"';
        }

        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        $columns = array(
            array('db' => 'sales_purchase_number', 'dt' => 0),
            array('db' => 'Name', 'dt' => 1, "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
            array('db' => 'Date', 'dt' => 2),
            array('db' => 'Due_Date', 'dt' => 3),
            array('db' => 'VAT', 'dt' => 4),
            array('db' => 'SubTotal', 'dt' => 5, "formatter" => function($d) {
                    return CommonFunctions::formatNumber($d);
                }),
            array('db' => 'NetTotal', 'dt' => 6, "formatter" => function($d) {
                    return CommonFunctions::formatNumber($d);
                }),
            array(
                'db' => 'sales_purchase_id_auto',
                'dt' => 7,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, 'data_id' => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "View",
                                "permission" => "ViewSalesInvoice",
                                "icon" => "fa-eye",
                                "href" => "Inventory/" . ($_GET['is_return'] ? "ViewReturnDebit/" . $row[8] : "ViewInvoice/" . $row[8] . '/' . $row[9])
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "permission" => ($_GET['is_return'] == 1 ? "edit_sales_purchase_return" : "edit_sales_purchase"),
                                        "icon" => "fa-pencil",
                                        "href" => "Inventory/salesPurchase/" . ($_GET['is_return'] == 1 ? 'return/' : '') . $d
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete",
                                        "permission" => ($_GET['is_return'] ? "delete_return_sales_purchase" : "delete_sales_purchase" ),
                                        "icon" => "fa-trash",
                                    ],
                    ]]);
                    return $html;
                }
            ),
            array('db' => 'Invoice_ID_Auto', 'dt' => 8),
            array('db' => 'Person_ID', 'dt' => 9)
        );
        $key = 'sales_purchase_id_auto';
        $table = $_GET['is_return'] == 1 ? 'sales_purchase_return_list' : 'sales_purchase_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function export_invoices() {
        $this->_registry->invoice->export_invoices($_GET['from'], $_GET['to'], $_GET['is_actual']);
        $this->_registry->invoice->export_invoice_details($_GET['from'], $_GET['to'], $_GET['is_actual']);
    }

    public function insert_customer_details() {
        //die('here');
        $insert = $this->_registry->customer->setData($_POST)->insert_customer_details();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function end_of_shift_report() {
        $condition = empty($_GET['user']) ? '' : ' and user_id = "' . $_GET['user'] . '" ';
        $condition .= isset($_GET['is_actual']) ? 'and is_actual = "' . $_GET['is_actual'] . '"' : '';
        $condition .= ' AND ((open_time between STR_TO_DATE("' . $_GET['From_Date'] . '", "%Y-%m-%d %h:%i:%s %p") 
								AND STR_TO_DATE("' . $_GET['To_Date'] . '", "%Y-%m-%d %h:%i:%s %p"))
								or (close_time between STR_TO_DATE("' . $_GET['From_Date'] . '", "%Y-%m-%d %h:%i:%s %p") 
									AND STR_TO_DATE("' . $_GET['To_Date'] . '", "%Y-%m-%d %h:%i:%s %p")) 
							) ';
        if (isset($_GET['type']))
            $condition .= ' and type="' . $_GET['type'] . '" ';
        $columns = array('User_Name', 'open_time', 'close_time',
            array('db' => 'total_net_invoices', 'dt' => 3, "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row[7];
                }),
            array('db' => 'total_net_returns', 'dt' => 4, "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row[7];
                }),
            array('db' => 'total_balance', 'dt' => 5, "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row[7];
                }),
            array(
                'db' => 'shift_id',
                'dt' => 6,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => false, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("print"),
                                "class" => "print_end_shift",
                                "attr" => "data-type='" . $row['type'] . "'",
                                "permission" => "end_of_shift_report_print",
                                "icon" => "fa-print"]]]);
                    return $html;
                }
            ), 'Currency_Symbol', 'type'
        );
        $key = 'shift_id';
        $table = 'end_shift_view';

        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }

    public function TotalReturnItemsPerDateAjax() {
        $cond = ' current_year_id="' . $this->year_id . '" and Is_Customer_Invoice = "' . $_GET['is_customer'] . '"';
        if (isset($_GET['From_Date'])) {
            $cond .= ' AND Date >= "' . $_GET['From_Date'] . '" AND Date <= "' . $_GET['To_Date'] . '"';
        }
        if (isset($_GET['users']) && !empty($_GET['users'])) {
            $cond .= ' AND Logged_ID in (' . implode(",", $_GET['users']) . ')';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        $group = ' GROUP BY Product_ID,Currency_ID ';
        $columns = array(
            array('db' => 'Item_Name', 'dt' => 0),
            array('db' => 'Code', 'dt' => 1),
            array('db' => 'SUM(Quantity)', 'dt' => 2, "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row[4];
                }),
            array('db' => 'SUM(Product_Total_Price)', 'dt' => 3, "formatter" => function($d, $row) {
                    return $row[5] . ' ' . Forms::DecimalNumber($d);
                }),
            array('db' => 'UOM_Name', 'dt' => 4),
            array('db' => 'Currency_Symbol', 'dt' => 5)
        );
        //return_mov
        $key = '(@cnt := @cnt + 1)';
        $table = 'return_report  CROSS JOIN (SELECT @cnt := 0) AS dummy';                                                                                                                                                                    //       die($table);
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }

    public function editPurchaseOrderAjax() {
        $RET = $this->_registry->purchase->setData($_POST)->editPurchaseOrder();
        die(json_encode(is_numeric($RET[0]) ? ['OK', $RET[0], $RET[1]] : $RET ));
        //        die(empty($RET) ? json_encode("OK") : json_encode($RET));
    }

    public function get_costing_report() {
        $options = array('depot_id' => $_GET['depot_id'], 'date' => $_GET['date'],
            'type' => $_GET['type'], 'type_id' => $_GET['type_id'],
            'operation' => $_GET['operation'], 'category' => $_GET['category'],
            'show_zero_qty' => $_GET['show_zero_qty'], 'brand_id' => $_GET['brand_id'],
            'supplier_id' => $_GET['supplier_id'], 'cost_filter' => $_GET['cost_filter'], 'search_branch_id' => $_GET['search_branch_id']);
        $data_result = $this->_registry->Product->costing_report($options);
        //                                                                                                                                                                        echo"<pre>";
        //                                                                                                                                                                        die(print_r($data_result));
        $html = Forms::build_table_html($data_result['data']);
        die(json_encode(["html" => $html, "stock_total" => $data_result['total'], "stock_total_sec" => $data_result['sec_total']]));
        $data = $data_result['data'];
        echo json_encode(array("stock_total" => $data_result['total'], "data" => $data, "draw" => 1, "recordsFiltered" => count($data), "recordsTotal" => count($data)));
    }

    public function movement_control() {
        //        $IsVendor = true;
        $is_actual_col = $_GET['type'] == 'rin' || $_GET['type'] == 'rpr' ? 'Is_Actual' : 'is_actual';
        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        if (isset($_GET['Date_From']) && isset($_GET['Date_To'])) {
            $FromDate = $_GET['Date_From'];
            $ToDate = $_GET['Date_To'];
            $cond .= ' and Date >= "' . $FromDate . '" AND Date <= "' . $ToDate . '"';
        }
        if (is_numeric($_GET['person'])) {
            $cond .= ' and Person_ID = "' . $_GET['person'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_id'] . '"';
        }
        if (isset($_GET['foreign']) && $_GET['foreign'] != 'both') {
            $cond .= ' and Country_ID ' . ($_GET['foreign'] == 0 ? ' = ' : ' <> ') . '"' . smc_session()['org_detail']['Organization_Country'] . '"';
        }
        if (!empty($_GET['sales_man_id']) && $_GET['type'] != 'pur')
            $cond .= ' and Sales_ID ="' . $_GET['sales_man_id'] . '"';
        $id_col = $_GET['type'] == 'rin' || $_GET['type'] == 'rpr' ? 'return_nb' : 'ID';
        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        $columns = array(
            array('db' => $id_col, 'dt' => 0),
            array('db' => 'Name', 'dt' => 1, "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
            array('db' => 'Date', 'dt' => 2),
            array('db' => 'Due_Date', 'dt' => 3),
            array('db' => 'VAT', 'dt' => 4),
            array('db' => 'SubTotal', 'dt' => 5),
            array('db' => 'NetTotal', 'dt' => 6)
        );

        $table_view = $_GET['type'] == 'pur' ? 'purchase_list' : ($_GET['type'] == 'inv' ? 'invoice_list' : ($_GET['type'] == 'rin' ? 'customer_return_list' : 'vendor_return_list'));
        $cond .= $_GET['type'] == 'inv' ? ' and is_committed = 1' : '';
        $key = '(@cnt := @cnt + 1)';
        $table = $table_view . '  CROSS JOIN (SELECT @cnt := 0) AS dummy';
        //                $key = 'ID';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

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

    public function delete_sales_invoice() {
        $delete = !empty($_GET['is_purchase']) ? $this->_registry->purchase->delete_purchase($_GET['ids']) : $this->_registry->invoice->deleteSalesInvoice($_GET['ids']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function last_insert_sales_invoice() {
        $delete = $this->_registry->purchase->last_insert_sales_invoice();
        die(json_encode($delete[0]));
    }

    public function delete_return() {
        $delete = $this->_registry->return->deleteReturn($_POST['ids']);
        die(empty($delete) ? 'OK' : $delete[0]);
    }

    public function updateCustomerPassword() {
        $submit = $this->_registry->customer->setData($_POST)->updateCustomerPassword();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('customer_password_updated'), 'success'] : [$submit[0], 'danger']));
    }

    public function print_customer_qrcode() {
        $data = $this->_registry->customer->getCustomerByID($_GET['customer_id']);
        //  echo "<pre>";die(print_r($data));
        $data['qrcode'] = SITE_LINK . 'common_controller/GenerateQRCode?code=' . $_GET['current_value'];
        $data['barcode'] = SITE_LINK . 'common_controller/GenerateBarCodeImage?code=' . $_GET['current_value'];
        $data['full_name'] = $data['Name'];
        $template_row = Forms::build_print_template('customer_qrcode', $data);
        $html = $template_row['html'];
        die($html);
    }
    public function print_production_process() {
        $data = $this->_registry->production->get_production_process_id($_GET['production_process_id']);
        //  echo "<pre>";die(print_r($data));
        
        $data['template_name']=$data['main']['template_name'];
        $data['date']=$data['main']['date'];
        $data['process_note']=$data['main']['process_note'];
        $data['barcode']=$data['main']['barcode'].''.$data['main']['order_nb'];

        $production_of="";
        foreach  ( $data['plus'] as $row) {
            $Product_Name=$row['Product_Name'];
            $initial_current_quantity=$row['initial_current_quantity'];

            $production_of .= "<tr>
            <td>$Product_Name</td>
            <td>$initial_current_quantity</td>
        </tr>";
        }
        
        $production_employee="";
        foreach  ( $data['employee_type'] as $row) {
            $type_name=$row['type_name'];
            $employee_name= $row['employees'][0]['employee_name'];

            $production_employee .= "<tr>
            <td>$type_name</td>
            <td>$employee_name</td>
        </tr>";
        }
        $data['production_of']=$production_of;
        $data['production_employee']=$production_employee;


        $template_row = Forms::build_print_template('production_process_print', $data);
        $html = $template_row['html'];
        die($html);
    }
    public function view_customer_visits() {
        $cond = ' 1=1 ';
        if (isset($_GET['from']) && isset($_GET['to'])) {
            $FromDate = $_GET['from'];
            $ToDate = $_GET['to'];
            $cond .= ' and date >= "' . $FromDate . '" AND date <= "' . $ToDate . '"';
        }
        if (!empty($_GET['user'])) {
            $cond .= ' and app_user_id = "' . $_GET['user'] . '"';
        }
        if (!empty($_GET['customer'])) {
            $cond .= ' and  customer_id = "' . $_GET['customer'] . '"';
        }

        $columns = array(
            array('db' => 'User_Name', 'dt' => 0),
            array('db' => 'Customer_Name', 'dt' => 1),
            array('db' => 'date', 'dt' => 2),
            array('db' => 'time', 'dt' => 3),
            array(
                'db' => 'visit_id',
                'dt' => 4,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("view"),
                                "class" => "view_map openFrame",
                                "icon" => "fa-map",
                                "attr" => "data-src='others/app_tracking_map?is_pop=1&visit_id={$d}'"
                                    //                                                                       "href" => "Inventory/" . ($_GET['is_return'] ? "ViewReturnDebit/" : "ViewInvoice/") . $row[8] . '/' . $row[9]
                    ]]]);
                    return $html;
                }
            )
        );
        $key = 'visit_id';
        $table = 'customer_visits';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function CustomerSupplierContacts() {
        $cond = ' 1=1 ';
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        $columns = array('main_name', 'phone');
        $key = 'mykey';
        $table = 'customer_supplier_contacts';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function CashDrawerLog() {
        $condition = '';
        if (!empty($_GET['user_id'])) {
            $condition .= ' and user_id ="' . $_GET['user_id'] . '"';
        }
        if (!empty($_GET['cash_drawer_id'])) {
            $condition .= ' and cash_drawer_id ="' . $_GET['cash_drawer_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $condition .= ' and (( Date(login_date_time)	 between "' . $_GET['Date_From'] . '" and  "' . $_GET['Date_To'] . '") or (Date(logout_date_time) between "' . $_GET['Date_From'] . '" and  "' . $_GET['Date_To'] . '") )';
        }
        $columns = array(array(
                'db' => 'login_system_amount',
                'dt' => 0,
                'formatter' => function( $d) {
                    return CommonFunctions::formatNumber($d);
                }
            ), array(
                'db' => 'real_amount',
                'dt' => 1,
                'formatter' => function( $d) {
                    return CommonFunctions::formatNumber($d);
                }
            ), array(
                'db' => 'cash_drawer_amount_id',
                'dt' => 2,
                'formatter' => function( $d, $row) {
                    $difference = $row[0] - $row[1];
                    return $difference == 0 ? CommonFunctions::formatNumber($difference) : '<span class="red-star">' . CommonFunctions::formatNumber($difference) . '</span>';
                }
            ), 'login_date_time', 'cash_drawer_title', 'User_Name', array(
                'db' => 'logout_system_amount',
                'dt' => 6,
                'formatter' => function( $d) {
                    return CommonFunctions::formatNumber($d);
                }
            ), array(
                'db' => 'withdrawal_amount',
                'dt' => 7,
                'formatter' => function( $d) {
                    return CommonFunctions::formatNumber($d);
                }
            ), array(
                'db' => 'remaining_amount',
                'dt' => 8,
                'formatter' => function( $d) {
                    return CommonFunctions::formatNumber($d);
                }
            ), array(
                'db' => 'cash_drawer_amount_id',
                'dt' => 9,
                'formatter' => function( $d, $row) {
                    $difference = $row[6] - ($row[7] + $row[8]);
                    return $difference == 0 ? CommonFunctions::formatNumber($difference) : '<span class="red-star">' . CommonFunctions::formatNumber($difference) . '</span>';
                }
            ), 'logout_date_time');
        $key = 'cash_drawer_amount_id';
        $table = 'cash_drawer_log';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1' . $condition);
        echo json_encode($data);
    }

    public function submitAllergyIntolerance() {
        $submit = $this->_registry->customer->setData($_POST)->submitAllergyIntolerance();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('piece_service_updated'), 'success'] : [$submit[0], 'danger']));
    }

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

    public function generalCriteria() {
        $columns = array('criteria_name', array(
                'db' => 'criteria_type',
                'dt' => 1,
                'formatter' => function( $d) {
                    return CommonLanguage::getMessage($d == 1 ? 'multiple_option' : 'one_option');
                }
            ), 'criteria_details', array(
                'db' => 'criteria_id',
                'dt' => 3,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => false,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit_criteria",
                                "icon" => "fa-pencil",
                                "attr" => "data-id={$d}",
                                "data-target" => "#general-criteria-modal"
                                    ]
                    ]]);
                    return $html;
                }
        ));
        $key = 'criteria_id';
        $table = 'product_criteria';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' Product_ID = 0');
        echo json_encode($data);
    }

    public function get_total_sold_items_totals() {
        $data = $this->_registry->invoice->setData($_GET)->get_total_sold_items_totals($_GET['with_return'], $_GET['From_Date'], $_GET['To_Date'], $_GET['users'], $_GET['is_actual'], $_GET['customer_id'], $_GET['is_day'], $_GET['From_Date_invoice'], $_GET['To_Date_invoice'], $_GET['branch_id'], $_GET['category_id'], $_GET['sales_man_id']);
        die(json_encode($data));
    }

    public function generate_prod_barcode() {
        $code = Forms::build_barcode_text(null, $_GET['code']);
        die($code);
    }

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

    public function reorder_invoices() {
        //        die('here');
        $reorder = $this->_registry->invoice->reorderInvNum($_POST['from_date'], $_POST['is_actual']);
        die(empty($reorder) ? 'OK' : 'error');
    }

    public function pricing_class_ajax() {
        $cond = ' 1=1 ';
        if (isset($_GET['is_supp']))
            $cond .= ' and type="' . $_GET['is_supp'] . '" ';
        $columns = array('Class_Name',
            array(
                'db' => 'is_ttc',
                'dt' => 1,
                'formatter' => function( $d ) {

                    return CommonLanguage::getMessage($d == 1 ? 'yes' : 'no');
                }
            ),
            array(
                'db' => 'Class_ID',
                'dt' => 2,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => false,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit_class",
                                "icon" => "fa-pencil",
                                "attr" => "data-id={$d}",
                                "permission" => ($_GET['is_supp'] == 1 ? "edit_supplier_pricing_class" : "edit_pricing_class")
                                    ]
                    ]]);
                    return smc_session()['default_setting']['sync_type'] != 2 ? $html : '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>';
                }
        ));
        $key = 'Class_ID';
        $table = 'tbl_pricing_class';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function add_edit_pricing_class() {
        $insert = $this->_registry->Product->setData($_POST)->add_edit_pricing_class();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

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

    public function listBrandRequest() {
        $columns = array(
            array(
                'db' => 'brand_id',
                'dt' => 2,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "edit_brand",
                                        "icon" => "fa-pencil",
                                        "data-target" => '#addBrand',
                                        "permission" => "edit_brand",
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete_brand",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_brand",
                                    ]
                    ]]);
                    return $html;
                }
            ),
            array('db' => 'brand_name', 'dt' => 0),
            array('db' => 'order_nb', 'dt' => 1),
        );
        $key = 'brand_id';
        $data = DataTable::complex($_GET, 'tbl_brand_products', $key, $columns);
        echo json_encode($data);
    }

    public function listDeliveryRequest() {
        $columns = array(
            array(
                'db' => 'delivery_fees_id',
                'dt' => 2,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "edit_delivery",
                                        "icon" => "fa-pencil",
                                        "data-target" => '#addDelivery',
                                        "permission" => "edit_delivery_fees",
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete_delivery",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_delivery_fees",
                                    ]
                    ]]);
                    return $html;
                }
            ),
            array('db' => 'delivery_fees_amount', 'dt' => 0),
            array('db' => 'delivery_fees_view', 'dt' => 1),
        );
        $key = 'delivery_fees_id';
        $data = DataTable::complex($_GET, 'tbl_delivery_fees', $key, $columns);
        echo json_encode($data);
    }

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

    public function deleteDelivery() {
        $delete = $this->_registry->invoice->deleteDelivery($_GET['entry_value']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function submitBrand() {
        $submit = $this->_registry->Product->setData($_POST)->submitBrand();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_production_barcode() {
        $submit = $this->_registry->Product->setData($_POST)->submit_production_barcode();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_production_color() {
        $submit = $this->_registry->Product->setData($_POST)->submit_production_color();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function get_production_barcode()
    {
        $data =  $this->_registry->Product->setData($_GET)->get_production_barcode();
        die(json_encode($data));
    }
     public function get_production_color()
    {
        $data =  $this->_registry->Product->setData($_GET)->get_production_color();
        die(json_encode($data));
     }
    public function deleteBrand() {
        $submit = $this->_registry->Product->setData($_GET)->deleteBrand();
        die(empty($submit) ? "ok" : $submit);
    }

    public function get_total_sales_purchase_invoices() {
        $FromDate = $ToDate = null;
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $FromDate = $_GET['from_date'];
            $ToDate = $_GET['to_date'];
        }
        $_GET['IsVendor'] = ($_GET['IsVendor'] == 'true' ? 1 : 0 );
        $data = $this->_registry->invoice->setdata($_GET)->get_total_sales_purchase_invoices($_GET['IsVendor'], $FromDate, $ToDate, $_GET['is_actual'], $_GET['customer_supplier_id'], $_GET['branch_id'], $_GET['print_filter']);
        die(json_encode($data));
    }

    public function get_total_inv_dist_by_customer() {
        $data = $this->_registry->invoice->setdata($_GET)->get_total_inv_dist_by_customer();
        die(json_encode($data));
    }

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

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

    public function get_total_sales_invoices() {
        $data = $this->_registry->invoice->setData($_GET)->get_total_sales_invoices($_GET['freq'], $_GET['Date'], $_GET['is_actual'], $_GET['customer_id']);
        die(json_encode($data));
    }

    public function get_total_sold_brand_items_totals() {
        $data = $this->_registry->invoice->setData($_GET)->get_total_sold_brand_items_totals($_GET['with_return'], $_GET['From_Date'], $_GET['To_Date'], $_GET['users'], $_GET['is_actual'], $_GET['brand_id']);
        die(json_encode($data));
    }

    public function TotalItemsPerBrandAjax() {
        $cond = ' current_year_id="' . $this->year_id . '" and is_actual = "' . $_GET['is_actual'] . '" ';
        if (isset($_GET['From_Date'])) {
            $cond .= ' AND date_created between "' . $_GET['From_Date'] . '" AND  "' . $_GET['To_Date'] . '"';
        }
        if (isset($_GET['users']) && !empty($_GET['users'])) {
            $cond .= ' AND Logged_ID in (' . $_GET['users'] . ')';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_id'] . '" ';
        }
        if (!empty($_GET['sales_man_id'])) {
            $cond .= ' and Sales_ID = "' . $_GET['sales_man_id'] . '" ';
        }
        if (!empty($_GET['brand_id'])) {
            $cond .= ' and  ' . ($_GET['is_brand'] ? 'brand_id' : 'Category_ID') . '  in (' . $_GET['brand_id'] . ')';
        }
        $group = ' GROUP BY ' . ($_GET['is_brand'] ? 'brand_id' : 'Category_ID') . ',Currency_ID ';
        $columns = array(
            array('db' => $_GET['is_brand'] ? 'brand_name' : 'Cat_Name',),
            array('db' => 'SUM(Quantity)', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d);   // . ' ' . $row[3];
                }),
            array('db' => ('SUM(Product_Total_Price)'), "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }),
            array('db' => ('SUM(vat_amount)'), "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                })
        );
        if (smc_session()['default_setting']['activate_second_vat'] == 1) {
            $columns[] = array('db' => ('SUM(vat2_amount)'), "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                });
        }
        $columns[] = array('db' => ('SUM(Product_Total_Price+vat_amount+vat2_amount)'), "formatter" => function($d, $row) {
                return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
            });
        $columns[] = 'UOM_Name';
        $columns[] = 'Currency_Symbol';
        //sales_return_mov
        $key = $_GET['with_return'] == 0 ? ($_GET['is_brand'] ? 'table_key1' : 'table_key2') : 'table_key';
        $table = $_GET['with_return'] == 0 ? 'product_mov_invoice' : '(select  b.brand_id, brand_name,Product_Name,u.*,um.UOM_Name,
        concat_ws("",' . ($_GET['is_brand'] ? 'b.brand_id' : 'u.Category_ID') . ',u.Currency_ID)as table_key,
            p.Product_Name as Item_Name,p.Product_Code as Code,c.Currency_Symbol,category.Cat_Name from
            (select i.date_created,`d`.`Product_ID`,`d`.`Product_Quantity` AS `Quantity`,`d`.`Product_Total_Price` AS `Product_Total_Price`,
            `i`.`Invoice_Date` AS `Date`,`i`.`Invoice_Currency` AS `Currency_ID`,i.current_year_id,i.Logged_ID ,
            i.created_logged_id,i.is_actual,p1.Category_ID,i.branch_id,i.Sales_ID,d.vat_amount,d.vat2_amount 
            from `tbl_invoice_products_details` `d`
            inner join `tbl_invoices` `i` on `i`.`Invoice_ID_Auto` = `d`.`Invoice_ID_Auto`
            inner join tbl_stock_products p1 on d.Product_ID = p1.Product_ID 
            where i.is_committed = 1
            union all
            select  i.date_created,d.Product_ID,(d.Return_Product_Quantity *(-1)) as Quantity,
            (d.Return_Product_Total * (-1)) as Product_Total_Price,i.Return_Invoice_Date AS `Date`,i.Currency_ID,i.current_year_id,
            i.Logged_ID,i.created_logged_id,i.Is_Actual as is_actual,p2.Category_ID,i.branch_id,i.Sales_ID ,
            (d.vat_amount* (-1)) as vat_amount,(d.vat2_amount* (-1)) as vat2_amount
            from tbl_accounting_return_items d 
            join tbl_accounting_return_invoices i on d.Return_Invoice_ID = i.Return_Invoice_ID
            inner join tbl_stock_products p2 on d.Product_ID = p2.Product_ID 
            ) u 
            join tbl_stock_products p on u.Product_ID = p.Product_ID 
            inner join tbl_product_cat category on category.Cat_ID = p.Category_ID
            left join tbl_brand_products b on b.brand_id = p.brand_id
            join tbl_common_currency c on c.Currency_ID = u.Currency_ID left join tbl_stock_uom um 
            on um.UOM_ID = p.UOM_ID ) as movement';
        $cond .= $_GET['with_return'] == 0 ? ' and is_committed = 1' : '';
        //        echo $cond;
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }

    public function detailed_purchase_report_request() {
        $cond = ' current_year_id = "' . $this->year_id . '" ';

        $_GET['depot_arr'] = array();
        $query = $this->db->query('select Depot_ID,Depot_Name from tbl_stock_depot_warehouse');
        while ($row = $this->db->assoc($query))
            $_GET['depot_arr'][$row['Depot_ID']] = $row['Depot_Name'];
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and (Purchase_Date between "' . smc_escape($_GET['from_date']) . '" and "' . smc_escape($_GET['to_date']) . '" )  ';
        if (!empty($_GET['product']))
            $cond .= ' and  Product_ID = ' . smc_escape($_GET['product']) . '';
        if (empty($_GET['is_actual']))
            $cond .= ' and  is_actual = 0';
        if (!empty($_GET['supplier']) || is_numeric($_GET['supplier'])) //we put it for zero : cash supplier
            $cond .= ' and Supplier_ID = ' . smc_escape($_GET['supplier']) . ' ';
        if (!empty($_GET['depot_id']))
            $cond .= ' and  detail_depot_id = ' . smc_escape($_GET['depot_id']) . '';
        if (!empty($_GET['category_id']))
            $cond .= ' and  Category_ID = ' . smc_escape($_GET['category_id']) . '';
        if (!empty($_GET['brand_id']))
            $cond .= ' and  brand_id = ' . smc_escape($_GET['brand_id']) . '';
        if (!empty($_GET['serial_nb']))
            $cond .= ' and  serial_nb = ' . smc_escape($_GET['serial_nb']) . '';
        if (!empty($_GET['lot_nb']))
            $cond .= ' and  lot_nb = ' . smc_escape($_GET['lot_nb']) . '';
        $columns = array(
            array('db' => 'Purchase_ID_Auto', 'formatter' => function($d, $row) {
                    $html = '';
                    if (($row['is_actual'] == 1 && $this->controller_permission->hasPermission('editPurchaseActual')) || ($row['is_actual'] == 0 && $this->controller_permission->hasPermission('editPurchase')))
                        $html .= '<span class="openFrame cursor" data-src="Inventory/addpurchase/' . ($row['is_actual'] == 1 ? 'act/' : '') . $d . '?is_pop=1"><i class="fa fa-pencil"></i></span>&nbsp;';
                    $html .= '<a href="javascript:void(0);" data-src="Inventory/ViewInvoice/vendor/' . $d . '/' . $row['Supplier_ID'] . '?is_pop=1" class="openFrame">' . $row['Purchase_ID'] . '</a>';
                    return $html;
                }),
            array('db' => 'Supplier_Name', "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
            array('db' => 'Product_Name', "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
            array('db' => 'product_description', "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }), 'Purchase_Date',
            array('db' => 'detail_depot_id', "formatter" => function($d) {
                    return $_GET['depot_arr'][$d];
                }),
            array('db' => 'Item_Quantity_Current', "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row['UOM_Name'];
                }),
            array('db' => 'Item_Price', "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'Item_Discount', "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' %';
                }),
            array('db' => 'Product_Total_Price', "formatter" => function($d, $row) {
                    return CommonFunctions::public_round_number($d) . ' ' . $row['Currency_Symbol'];
                }), 'Supplier_ID', 'UOM_Name', 'Currency_Symbol', 'Purchase_ID', 'is_actual'
        );
        $key = 'Item_ID';
        $table = 'detailed_purchase_report';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function product_sections_ajax() {
        $columns = array('section_name',
            array(
                'db' => 'section_id',
                'dt' => 1,
                'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit_section",
                                "icon" => "fa-pencil",
                                "attr" => "data-id={$d}",
                                "permission" => "edit_product_sections"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete_section",
                                        "icon" => "fa-trash",
                                        "attr" => "data-id={$d}",
                                        "permission" => "delete_product_sections"
                                    ]
                    ]]);
                    return $html;
                }
        ));
        $key = 'section_id';
        $table = 'tbl_product_sections';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function add_edit_product_section() {
        $insert = $this->_registry->Product->setData($_POST)->add_edit_product_section();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function delete_product_section() {
        $insert = $this->_registry->Product->delete_product_section($_GET['id']);
        die(empty($insert) ? 'OK' : $insert[0]);
    }

    public function ExpiryDateReport() {
        $cond = '';
        if (!empty($_GET['ex_from']) && !empty($_GET['ex_to']))
            $cond .= '  and expiry_date between "' . $_GET['ex_from'] . '" and "' . $_GET['ex_to'] . '" ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= '  and Transaction_Date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '" ';
        if (!empty($_GET['cat_id']))
            $cond .= ' and Category_ID = "' . $_GET['cat_id'] . '"';
        if (!empty($_GET['product_id']))
            $cond .= ' and Product_ID = "' . $_GET['product_id'] . '"';
        $slctd_fld = ($_GET['type'] == 1 ? 'expiry_date' : ($_GET['type'] == 2 ? 'lot_nb' : 'serial_nb'));
        $columns = array('Product_Code', 'Product_Name',
            array('db' => 'sum_quantity', 'dt' => 2, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['UOM_Name'];
                }),
            $slctd_fld
            , 'UOM_Name'
        );
        $key = 'Transaction_ID';
        $table = '(select  trans.Transaction_ID,trans.Product_ID,
            (trans.Product_Quantity/products.default_view_rate) as Product_Quantity,
            trans.lot_nb,trans.serial_nb,
            SUM(if(trans.Operation_Type="-",trans.Product_Quantity*(-1),trans.Product_Quantity)/products.default_view_rate) as sum_quantity,
            trans.expiry_date,products.Product_Code, products.Product_Name,products.Category_ID,uom.UOM_Name,
            Operation_Type
                    from tbl_stock_product_transactions  trans
                    inner join tbl_stock_products products using (Product_id) 
                    inner join tbl_stock_uom uom on  products.default_view_uom_id = uom.UOM_ID
                    where ifNull(trans.' . $slctd_fld . ', "") <> "" ' . $cond . '
                    group by trans.Product_ID, trans.' . $slctd_fld . ' having sum_quantity <> 0) as dummy ';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function ajaxProductDetails() {
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $id = isset($_GET["product_id"]) ? intval($_GET["product_id"]) : 0;
        $RET = $this->_registry->Product->setData($_GET)->viewProductDetails($id);
        for ($x = 0; $x < count($RET); $x++) {
            $RET2 = $this->_registry->Product->setData($_GET)->viewProductDetails(intval($RET[$x]["part_product_id"]));
            if (count($RET2) > 0)
                $RET[$x]["isLazy"] = true;
            $RET[$x]["key"] = $RET[$x]["part_product_id"];
        }
        die(json_encode($RET));
    }

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

    public function submitNewMachinePart() {
        $product_id = $_POST['current_product_id'];
        if ($product_id == 0) {
            $_POST['Product_Reorder_Point'] = NULL;
            $submit = $this->_registry->Product->setData($_POST)->addProduct();
        } else {
            $_POST['Product_ID'] = $product_id;
            $_POST['Product_Reorder_Point'] = NULL;
            $submit = $this->_registry->Product->setData($_POST)->updateProduct();
        }
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

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

    public function submitUnlinkDeleteMachPart() {
        $submit = $this->_registry->Product->setData($_POST)->submitUnlinkDeleteMachPart();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0] == 'unable_delete_product' ? CommonLanguage::getMessage('unable_delete_product') : $submit[0], 'danger']));
    }

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

    public function get_total_receipe_product_cost() {
        $data = $this->_registry->Product->setData($_GET)->getTotalCostProductRecipe();
        die($data);
    }

    public function getMaxProductCode() {
        $data = $this->_registry->Product->getMaxProductCode();
        die(json_encode($data));
    }

    public function get_total_purchased_items() {
        $data = $this->_registry->purchase->setData($_GET)->get_total_purchased_items();
        die($data);
    }

    // Station

    public function customerCouponsList() {
        //        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        $cond = ' AND current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['from']) && isset($_GET['to'])) {
            $FromDate = $_GET['from'];
            $ToDate = $_GET['to'];
            $cond .= ' and invoice_date >= "' . $FromDate . '" AND invoice_date <= "' . $ToDate . '"';
        }
        $columns = array('ID', 'Customer_Name', 'bone_type_name', 'TotalVat', 'SubTotal', 'NetTotal',
            array('db' => 'auto_id', 'dt' => 6, 'formatter' => function( $d, $row) {
                    $option_arr = [["title" => CommonLanguage::getMessage("Edit"),
                    "class" => "Edit",
                    "permission" => "edit_customer_coupon",
                    "icon" => "fa-pencil",
                    "href" => "Inventory/customer_coupons/{$d}"
                        ],
                        ["title" => CommonLanguage::getMessage("view"),
                            "class" => "View openFrame",
                            "permission" => "view_customer_coupon",
                            "icon" => "fa-eye",
                            "attr" => "data-src='Inventory/view_customer_coupon/{$d}?is_pop=1'"
                        ],
                        ["title" => CommonLanguage::getMessage("Delete"),
                            "class" => "delete_coupon",
                            "permission" => "delete_customer_coupon",
                            "icon" => "fa-trash"
                        ]
                    ];
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $option_arr]);
                    return $html;
                }));
        $key = 'auto_id';
        $table = 'customer_coupons_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1  ' . $cond);
        echo json_encode($data);
    }

    public function stationInvoiceList() {
        //        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        $cond = ' AND current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['from']) && isset($_GET['to'])) {
            $FromDate = $_GET['from'];
            $ToDate = $_GET['to'];
            $cond .= ' and invoice_date >= "' . $FromDate . '" AND invoice_date <= "' . $ToDate . '"';
        }
        $columns = array('inv_num', 'Customer_Name', 'invoice_date', 'InvoiceVat', 'sub_total', 'NetTotal',
            array('db' => 'invoice_id', 'dt' => 6, 'formatter' => function( $d, $row) {
                    $option_arr = [
                        ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "Edit",
                            "permission" => "edit_station_invoice",
                            "icon" => "fa-pencil",
                            "href" => "Inventory/station_invoice/{$d}"
                        ],
                        ["title" => CommonLanguage::getMessage("View"),
                            "class" => "openFrame",
                            "permission" => "view_station_invoice",
                            "icon" => "fa-eye",
                            "attr" => "data-src='Inventory/view_station_invoice/{$d}?is_pop=1'"

                        //                                    "href" => "Inventory/view_station_invoice/{$d}"
                        ]
                    ];
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $option_arr]);
                    return $html;
                }));
        $key = 'invoice_id';
        $table = 'station_invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1  ' . $cond);
        echo json_encode($data);
    }

    public function stationPurchaseList() {
        //        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        $cond = ' AND current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['from']) && isset($_GET['to'])) {
            $FromDate = $_GET['from'];
            $ToDate = $_GET['to'];
            $cond .= ' and Date >= "' . $FromDate . '" AND Date <= "' . $ToDate . '"';
        }
        $columns = array('ID', 'Name', 'Date', 'VAT', 'SubTotal', 'NetTotal',
            array('db' => 'ID_Auto', 'dt' => 6, 'formatter' => function( $d, $row) {
                    $option_arr = [["title" => CommonLanguage::getMessage("view"),
                    "class" => "View openFrame",
                    "permission" => "view_station_purchase",
                    "icon" => "fa-eye",
                    "attr" => "data-src='Inventory/view_station_purchase/{$row[6]}?is_pop=1'"
                        ], ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "Edit",
                            "permission" => "edit_station_purchase",
                            "icon" => "fa-pencil",
                            "href" => "Inventory/station_purchase/{$d}"
                    ]];
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $option_arr]);
                    return $html;
                }));
        $key = 'ID_Auto';
        $table = 'purchase_invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' purchase_type_id =1  ' . $cond);
        echo json_encode($data);
    }

    public function addCustomerCoupon() {
        $insert = $this->_registry->station->setData($_POST)->addCustomerCoupon();
        die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
    }

    public function editCustomerCoupon() {
        $update = $this->_registry->station->setData($_POST)->editCustomerCoupon();
        die(json_encode(is_numeric($update[0]) ? ['OK', $update[0], $update[1]] : $update ));
    }

    public function bone_type_ajax() {
        $columns = array('bone_type_name', 'Account_Name', 'vat_account_name', 'service_account_name',
            array(
                'db' => 'bone_type_id',
                'dt' => 4,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "data_id" => $d,
                                "isDropDown" => true,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit_bone_type",
                                "icon" => "fa-pencil",
                                "attr" => "data-account-id={$row[5]} data-vat-account-id={$row[6]} data-service-account-id={$row[7]}",
                                "data-target" => "#add-edit-bone-type-modal",
                                "permission" => "edit_bone_type"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete_bone_type",
                                        "icon" => "fa-trash",
                                        "attr" => "data-id={$row[5]}",
                                        "permission" => "delete_bone_type"
                                    ]
                    ]]);
                    return $html;
                }
            ), 'Account_ID', 'vat_account_id', 'service_account_id');
        $key = 'bone_type_id';
        $table = 'bone_type_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function jobOrderList() {
        $cond = ' current_year_id = "' . $this->year_id . '"';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and job_order_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }
        if (!empty($_GET['customer_id'])) {
            $customer_id = $_GET['customer_id'];
            $cond .= ' and customer_id = "' . $customer_id . '"';
        }
        $columns = array('job_order_nb', 'customer_name',
            'company', 'job_order_date',
            'print_ref', 'person_in_charge',
            'conform_date', 'delivery_date',
            array(
                'db' => 'job_order_id',
                'dt' => 8,
                'formatter' => function( $d, $row ) {
                    $option_arr = [
                        //                                     ["title" => CommonLanguage::getMessage("view"),
                        //                                                 "class" => "view",
                        //                                                 "icon" => "fa-eye",
                        //                                                 "permission" => "view_job_order"
                        //                                                ],
                        ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "edit",
                            "icon" => "fa-pencil",
                            "href" => "Inventory/job_order/{$d}",
                            "permission" => "edit_job_order"
                        ],
                        ["title" => CommonLanguage::getMessage("Delete"),
                            "class" => "delete",
                            "icon" => "fa-trash",
                            "attr" => "data-id={$d}",
                            "permission" => "delete_job_order"
                        ]
                    ];
                    if ($row[9] == 1) {
                        $option_arr [] = ["title" => CommonLanguage::getMessage("change_stage"),
                            "class" => "change_stage ",
                            "icon" => "fa-retweet",
                            "attr" => "data-id={$row['stage_id']}",
                            "data-target" => "#change_job_order_stage",
                            "permission" => "change_job_order_stage",
                        ];
                    }
                    return Forms::action_snippet(["color" => "primary",
                                "data_id" => $d,
                                "isDropDown" => true,
                                "ActionOption" => $option_arr]);
                }
            ), 'is_published', 'stage_id');
        $key = 'job_order_id';
        $table = 'job_order_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function jobOrderOptionList() {
        $columns = array('option_title',
            array(
                'db' => 'option_id',
                'dt' => 1,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "data_id" => $d,
                                "isDropDown" => true,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit",
                                "icon" => "fa-pencil",
                                "data-target" => "#job_order_options_modal",
                                "permission" => "edit_job_order_option"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "attr" => "data-id={$d}",
                                        "permission" => "delete_job_order_option"
                                    ]
                    ]]);
                    return $html;
                }
        ));
        $key = 'option_id';
        $table = 'tbl_job_order_option';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function job_order_block_list() {
        $columns = array('block_name', 'sort_nb',
            array(
                'db' => 'block_id',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "data_id" => $d,
                                "isDropDown" => true,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                "class" => "edit",
                                "icon" => "fa-pencil",
                                "data-target" => "#job_order_block",
                                "permission" => "edit_job_order_block"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "attr" => "data-id={$d}",
                                        "permission" => "delete_job_order_block"
                                    ]
                    ]]);
                    return $html;
                }
        ));
        $key = 'block_id';
        $table = 'tbl_job_order_block';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function pump_ajax() {
        $columns = array('pump_name', 'Product_Name',
            array('Status_ID', 'formatter' => function($d, $row, $excel) {
                    return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
                }),
            array(
                'db' => 'pump_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "data_id" => $d,
                                "isDropDown" => true,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "edit_pump",
                                        "icon" => "fa-pencil",
                                        "attr" => "data-id={$row['Product_ID']}",
                                        "data-target" => "#add-edit-pump-modal",
                                        "permission" => "edit_pump"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete_pump",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_pump"
                                    ],
                                    ["title" => CommonLanguage::getMessage($row['Status_ID'] == 1 ? "disable" : "enable"),
                                        "class" => "enable_disable_pump",
                                        "data-target" => "#enable-disable-modal",
                                        "attr" => "data-id={$row['Status_ID']}",
                                        "permission" => "enable_disable_pump",
                                        "icon" => "fa-" . ($row['Status_ID'] == 1 ? 'lock' : 'unlock')
                                    ]
                    ]]);
                    return $html;
                }
            ), 'Product_ID');
        $key = 'pump_id';
        $table = 'pump_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function deletePump() {
        $delete_pump = $this->_registry->station->setData($_GET)->deletePump();
        die(empty($delete_pump) ? "ok" : $delete_pump[0]);
    }

    public function enableDisablePump() {
        $submit = $this->_registry->station->setData($_POST)->enableDisablePump();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage($_POST['status_id'] == 0 ? 'pump_enabled_success' : 'pump_disabled_success'), 'success'] : [$submit[0], 'danger']));
    }

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

    public function deleteBoneType() {
        $delete_bone_type = $this->_registry->station->setData($_GET)->deleteBoneType();
        die(empty($delete_bone_type) ? "ok" : "error");
    }

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

    public function deleteJobOrderOption() {
        $delete = $this->_registry->jobOrder->setData($_GET)->deleteJobOrderOption();
        die(empty($delete) ? "ok" : $delete[0]);
    }

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

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

    public function deleteJobOrder() {
        $delete = $this->_registry->jobOrder->setData($_GET)->deleteJobOrder();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getJobOrderBlock() {
        $data = $this->_registry->jobOrder->setData($_GET)->getJobOrderBlockOptionData();
        $html = Forms::buildJobOrderBlock($data, $_GET['index']);
        die(json_encode($html));
    }

    public function job_order_stage_list() {
        $columns = array('stage_title', 'sort_nb',
            array(
                'db' => 'stage_id',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#job_order_stage_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_job_order_stage"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_job_order_stage"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'stage_id';
        $table = 'tbl_job_order_stage';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function deleteJobOrderStage() {
        $delete = $this->_registry->jobOrder->setData($_GET)->deleteJobOrderStage();
        die(empty($delete) ? "ok" : $delete[0]);
    }

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

    public function deleteJobOrderBlock() {
        $delete = $this->_registry->jobOrder->setData($_GET)->deleteJobOrderBlock();
        die(empty($delete) ? "ok" : "error");
    }

    public function getBoneTypeData() {
        $data['main'] = CommonFunctions::CommonView('bone_type_list', ['bone_type_id'], [$_GET['bone_type_id']]);
        $data['details'] = CommonFunctions::CommonView('bone_type_service_list', ['bone_type_id'], [$_GET['bone_type_id']]);
        die(json_encode($data));
    }

    public function getJobOrderOptionData() {
        $data = $this->_registry->jobOrder->setData($_GET)->getSpecificJobOrderOptionData();
        die(json_encode($data));
    }

    public function getJobOrderBlockData() {
        $data['main'] = CommonFunctions::CommonView('tbl_job_order_block', ['block_id'], [$_GET['block_id']])[0];
        $data['options'] = CommonFunctions::ViewByTableEntry('tbl_job_order_option', 'option_id', 'option_title', $data['main']['option_ids']);
        die(json_encode($data));
    }

    public function add_station_purchase() {

        if (isset($_POST["Supplier_ID"]) && isset($_POST["Purchase_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $insert = $this->_registry->purchase->setData($_POST)->add_station_purchase(true);
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
        }
    }

    public function edit_station_purchase() {
        if (isset($_POST["Supplier_ID"]) && isset($_POST["Purchase_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $insert = $this->_registry->purchase->setData($_POST)->edit_station_purchase(true);
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
        }
    }

    public function get_prod_default_price() {
        $data = $this->_registry->Product->setData($_GET)->get_prod_default_price($_GET['pid']);
        die(json_encode($data));
    }

    public function get_prod_price() {
        $class_id = smc_session()['pricing_class_id'];
        $data = $this->_registry->Product->get_product_price($_GET['pid'], $class_id, $_GET['uom']);
        die(json_encode($data));
    }

    public function get_product_by_id() {
        $cid = isset($_GET['cid']) ? $_GET['cid'] : null;
        $data = $this->_registry->Product->get_product_by_id($_GET['pid'], $cid);
        die(json_encode($data));
    }

    public function add_station_invoice() {
        $insert = $this->_registry->station->setData($_POST)->add_station_invoice();
        die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
    }

    public function edit_station_invoice() {
        $insert = $this->_registry->station->setData($_POST)->edit_station_invoice();
        die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : $insert ));
    }

    public function coupon_type_balance_ajax() {
        $cond = ' 1=1 ';
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and date between "' . $_GET['Date_From'] . '" and "' . $_GET['Date_To'] . '" ';
        }
        if (!empty($_GET['coupon_type'])) {
            $cond .= ' and bone_type_id = "' . $_GET['coupon_type'] . '"';
        }
        $columns = array('product_name', 'date', 'product_quantity');
        $key = '(@cnt := @cnt + 1)';
        $table = ' purchase_invoice_coupon_details CROSS JOIN (SELECT @cnt := 0) AS dummy';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function get_coupon_type_balance() {
        $data = $this->_registry->station->setData($_GET)->get_coupon_type_balance();
        $html = Forms::build_table_html($data);
        die($html);
    }

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

    public function change_invoice_actual() {
        $change = $this->_registry->invoice->change_invoice_actual($_POST['id'], $_POST['is_actual']);
        die(empty($change) ? 'OK' : 'error');
    }

    public function change_purchase_actual() {
        $change = $this->_registry->purchase->change_purchase_actual($_POST['id'], $_POST['is_actual']);
        die(empty($change) ? 'OK' : 'error');
    }

    public function change_return_actual() {
        $change = $this->_registry->return->change_return_actual($_POST['id'], $_POST['is_actual'], $_POST['is_customer']);
        die(json_encode([empty($change[0]) ? 'OK' : 'error', $change[1] ? '' : CommonLanguage::getMessage('linked_return_alert')]));
    }

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

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

    public function product_note_list() {
        $columns = array('note_title',
            array(
                'db' => 'is_linked',
                'dt' => 1,
                'formatter' => function( $d, $row ) {
                    return '<span class="is_linked" data-type="' . $d . '">' . CommonLanguage::getMessage($d == 0 ? 'is_not_linked' : 'is_linked') . '</span>';
                }),
            array(
                'db' => 'note_id',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#add_edit_product_note_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_product_note"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_product_note"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'note_id';
        $table = 'tbl_product_note';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function printer_list() {
        $columns = array('printer_name', 'printer_title', 'printer_key', 'branch_name',
            array(
                'db' => 'is_default',
                'dt' => 4,
                'formatter' => function( $d, $row ) {
                    return '<span class="is_default" data-type="' . $d . '">' . CommonLanguage::getMessage($d == 0 ? 'no' : 'yes') . '</span>';
                }),
            array(
                'db' => 'printer_id',
                'dt' => 5,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#add_edit_printer_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_printer"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_printer"
                                    ]
                    ]]);
                    return smc_session()['default_setting']['sync_type'] != 2 ? $html : '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>';
                })
        );
        $key = 'printer_id';
        $table = 'printer_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function family_list() {
        $columns = array('family_name',
            array(
                'db' => 'family_id',
                'dt' => 1,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#add_edit_family_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_family"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_family"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'family_id';
        $table = 'tbl_inventory_family';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function deleteFamily() {
        $delete_family = $this->_registry->Product->deleteFamily($_GET['family_id']);
        die(empty($delete_family) ? "ok" : $delete_family[0]);
    }

    public function customerCouponPerDateAjax() {
        $cond = ' and invoice_date between "' . $_GET['Date_From'] . '" and "' . $_GET['Date_To'] . '"';
        $columns = array('Customer_Name', 'bone_type_name', 'Product_Name', 'total_liter');
        $key = 'current_key';
        $table = '(select p.Product_Name,cust_coupon_list.*,sum(details.default_quantity) as total_liter,concat_ws(",",cust_coupon_list.Customer_ID,cust_coupon_list.bone_type_id) as current_key
                   from tbl_customer_coupon_details  details
                   inner join customer_coupons_list cust_coupon_list on details.auto_id = cust_coupon_list.auto_id
                   inner join tbl_stock_products p on p.Product_ID = details.product_id
                    where 1=1 ' . $cond . '
                   group by  cust_coupon_list.Customer_ID,cust_coupon_list.bone_type_id,details.product_id) as dummy';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function submitProductNote() {
        $submit = $this->_registry->Product->setData($_POST)->submitProductNote();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [CommonLanguage::getMessage('Failed_Submit'), 'danger']));
    }

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

    public function deleteProductNote() {
        $submit = $this->_registry->Product->setData($_GET)->deleteProductNote();
        die(empty($submit) ? "ok" : "error");
    }

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

    public function deleteProductSpecificationOptions() {
        $submit = $this->_registry->Product->setData($_GET)->deleteProductSpecificationOptions();
        die(empty($submit) ? "ok" : "error");
    }

    public function getProductInfo() {
        $data = $this->_registry->Product->getProductInfo($_GET['product_id']);
        $data['pricing_class'] = $this->_registry->Product->getPricingClasses($_GET['product_id']);
        $data['uom_conversion'] = $this->_registry->Product->getUOMPricesByProduct($_GET['product_id']);
        $data['products_links'] = $this->_registry->Product->getProductLinks($_GET['product_id']);
        $data['products_options'] = $this->_registry->Product->get_prod_options($_GET['product_id']);
        $data['product_criteria'] = $this->_registry->restaurantPos->setData(['Product_ID' => $_GET['product_id']])->getProductCriteria();
        $data['product_add_ons'] = CommonFunctions::CommonView('product_add_ons', ['product_id'], [$_GET['product_id']]);
        die(json_encode($data));
    }

    public function submitMultiProduct() {
        $current_type = $_POST['current_type'];
        $deleted_products_array = json_decode($_POST['deleted_products_array'], true);
        if ($current_type == 1 || $current_type == 3) {
            $db = DBConnectorFactory::loadDriver();
            $returne_data = array();
            $db->query('START TRANSACTION');
            if (!empty($_POST['family_id']) && !empty($_POST['delete_old_prod'])) {
                $this->_registry->Product->checkIfFamilyProductUsed($_POST['family_id']);
            }
        }
        $product_combinations = $this->combinations(json_decode($_POST['data'], true), $_POST['current_index'], $_POST['current_code_index']);
        $this->_registry->Product->stop_transaction_start_end = true;
        $product_name_separator = $_POST['Product_Name_Separator'] == '' ? ' ' : $_POST['Product_Name_Separator'];
        $product_code_separator = $_POST['Product_Code_Separator'] == '' ? '' : $_POST['Product_Code_Separator'];
        $current_product_array = array();
        $current_product_index = 0;
        foreach ($product_combinations as $product) {
            $product_name = $_POST['Product_Name'] . $product_name_separator . implode($product_name_separator, $product['name']);
            $product_code = $_POST['Product_Code'] . $product_code_separator . implode($product_code_separator, $product['code']);
            $current_image_name = 'image_file_' . $_POST['current_index'] . '_' . $product['image_name_index'];
            $product_second_code = NULL;
            if ($_POST['current_code_index'] != '') {
                $product_second_code_index = 'product_second_code_' . $_POST['current_code_index'] . '_' . $product['second_code_index'];
                $product_second_code = !empty($_POST[$product_second_code_index]) ? $_POST[$product_second_code_index] : NULL;
            }
            $product_post = ['Category_ID' => $_POST['Category_ID'], 'UOM_ID' => $_POST['UOM_ID'],
                'Product_Reorder_Point' => $_POST['Product_Reorder_Point'],
                'family_id' => $_POST['family_id'],
                'Product_Limit_Discount' => $_POST['Product_Limit_Discount'],
                'product_description' => $_POST['product_description'],
                'brand_id' => $_POST['brand_id'],
                'Product_Name' => $product_name, 'Product_Code' => $product_code,
                'product_second_code' => $product_second_code,
                'price_arr' => $_POST['price_arr'], 'current_image_file' => $current_image_name];
            //
            if (!empty($product['save_in'])) {
                foreach ($product['save_in'] as $save_in_indx => $save_in_val)
                    if (!empty($save_in_val))
                        $product_post['product_param' . $save_in_val] = $product['name'][$save_in_indx];
            }
            if (!empty($_POST['auto_generate_code']) && $_POST['auto_generate_code'] == 1)
                $product_post['Product_Code'] = $this->_registry->Product->getMaxProductCode();
            $product_post['current_product_index'] = $current_product_index;
            $action = '<input class="check_current_row" type="checkbox" data-current-index = "' . $current_product_index . '"/>';
            $current_product_array[] = [$action, $product_code, $product_second_code, $product_name];
            if ($current_type == 1 ||
                    ($current_type == 3 && !in_array($current_product_index, $deleted_products_array))) {
                $this->_registry->Product->setData($product_post)->addProduct();
            }
            $current_product_index++;
        }
        if ($current_type == 1 || $current_type == 3) {
            $error = $db->error();
            if (empty($error))
                $db->query('COMMIT');
            else
                $db->query('ROLLBACK');
            die(json_encode(empty($error) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$error[0], 'danger']));
        }
        $html = Forms::build_table_html($current_product_array);
        return die(json_encode([$html]));
    }

    //    public function submitMultiProduct() {
    //        $db = DBConnectorFactory::loadDriver();
    //        $returne_data = array();
    //        $db->query('START TRANSACTION');
    //        if (!empty($_POST['family_id']) && !empty($_POST['delete_old_prod'])) {
    //            $this->_registry->Product->checkIfFamilyProductUsed($_POST['family_id']);
    //        }
    //        $product_combinations = $this->combinations(json_decode($_POST['data'], true), $_POST['current_index'], $_POST['current_code_index']);
    //        $this->_registry->Product->stop_transaction_start_end = true;
    //        $product_name_separator = $_POST['Product_Name_Separator'] == '' ? ' ' : $_POST['Product_Name_Separator'];
    //        $product_code_separator = $_POST['Product_Code_Separator'] == '' ? '' : $_POST['Product_Code_Separator'];
    //        foreach ($product_combinations as $product) {
    //            $product_name = $_POST['Product_Name'] . $product_name_separator . implode($product_name_separator, $product['name']);
    //            $product_code = $_POST['Product_Code'] . $product_code_separator . implode($product_code_separator, $product['code']);
    //            $current_image_name = 'image_file_' . $_POST['current_index'] . '_' . $product['image_name_index'];
    //            $product_second_code = NULL;
    //            if ($_POST['current_code_index'] != '') {
    //                $product_second_code_index = 'product_second_code_' . $_POST['current_code_index'] . '_' . $product['second_code_index'];
    //                $product_second_code = !empty($_POST[$product_second_code_index]) ? $_POST[$product_second_code_index] : NULL;
    //            }
    //            $product_post = ['Category_ID' => $_POST['Category_ID'], 'UOM_ID' => $_POST['UOM_ID'],
    //                             'Product_Reorder_Point' => $_POST['Product_Reorder_Point'], 'family_id' => $_POST['family_id'],
    //                             'Product_Limit_Discount' => $_POST['Product_Limit_Discount'],
    //                             'product_description' => $_POST['product_description'],
    //                             'brand_id' => $_POST['brand_id'],
    //                             'Product_Name' => $product_name, 'Product_Code' => $product_code,
    //                             'product_second_code' => $product_second_code,
    //                             'price_arr' => $_POST['price_arr'], 'current_image_file' => $current_image_name];
    //            //
    //            if (!empty($product['save_in'])) {
    //                foreach ($product['save_in'] as $save_in_indx => $save_in_val)
    //                    if (!empty($save_in_val))
    //                        $product_post['product_param' . $save_in_val] = $product['name'][$save_in_indx];
    //            }
    //            if (!empty($_POST['auto_generate_code']) && $_POST['auto_generate_code'] == 1)
    //                $product_post['Product_Code'] = $this->_registry->Product->getMaxProductCode();
    //
    //            $this->_registry->Product->setData($product_post)->addProduct();
    //        }
    //        $error = $db->error();
    //        if (empty($error))
    //            $db->query('COMMIT');
    //        else
    //            $db->query('ROLLBACK');
    //        die(json_encode(empty($error) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$error[0], 'danger']));
    //    }

    public function combinations($options, $current_index, $code_index) {
        $combinations = [[]];
        for ($count = 0; $count < count($options); $count++) {
            $tmp = [];
            foreach ($combinations as $v1) {
                foreach ($options[$count]['products'] as $v2) {
                    $current_name = array_merge(empty($v1) ? [] : $v1['name'], [$v2['name']]);
                    $current_code = array_merge(empty($v1) ? [] : $v1['code'], [$v2['code']]);
                    $tmp_save_in = array_merge(empty($v1) ? [] : $v1['save_in'], [$options[$count]['save_in']]);
                    $tmp[] = ['name' => $current_name,
                        'code' => $current_code,
                        'image_name_index' => '',
                        'second_code_index' => '',
                        'save_in' => $tmp_save_in
                    ];
                }
            }
            $combinations = $tmp;
        }

        if ($current_index == '' && $code_index == '') {
            return $combinations;
        } else {
            $combinations_arr = [];
            if ($current_index != '')
                $image_main_index_arr = $options[$current_index]['products'];
            if ($code_index != '')
                $second_code_index_arr = $options[$code_index]['products'];
            foreach ($combinations as $combination) {
                if ($current_index != '') {
                    $combination_name_image = $combination['name'][$current_index];
                    $key = array_search($combination_name_image, array_column($image_main_index_arr, 'name'));
                    $combination['image_name_index'] = $image_main_index_arr[$key]['index'];
                }
                if ($code_index != '') {
                    $combination_second_code = $combination['name'][$code_index];
                    $key = array_search($combination_second_code, array_column($second_code_index_arr, 'name'));
                    $combination['second_code_index'] = $second_code_index_arr[$key]['index'];
                }
                $combinations_arr [] = $combination;
            }
            return $combinations_arr;
        }
    }

    public function deletePrinter() {
        $delete_printer = $this->_registry->Product->deletePrinter($_GET['printer_id']);
        die(empty($delete_printer) ? "ok" : $delete_printer[0]);
    }

    public function viewProductSpecificationOptions() {
        $data = $this->_registry->Product->viewProductSpecificationOptions($_GET['product_specification_id']);
        die(json_encode($data));
    }

    public function product_specification_options_list() {
        $columns = array('product_specification_name', 'all_options',
            array(
                'db' => 'product_specification_id',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#product_specification_option_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_product_specification_options"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_product_specification_options"
                                    ]
                    ]]);
                    return smc_session()['default_setting']['sync_type'] != 2 ? $html : '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>';
                })
        );
        $key = 'product_specification_id';
        $table = 'product_specification_options';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function get_product_default_uom() {
        $data = $this->_registry->Product->get_product_default_uom($_GET['pid'], true);
        die(json_encode($data));
    }

    public function get_category_prefix_barcode() {
        $data = $this->_registry->Product->get_category_prefix_barcode($_GET['cat_id']);
        die(json_encode($data));
    }


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

    public function get_item_prices() {
        if ($_GET['id'] == 0) {
            $data = $this->_registry->Product->get_item_by_last_cost($_GET['item_ids'], $_GET['adjust_class_id']);
        } else {
            $data = $this->_registry->Product->get_item_prices($_GET['item_ids'], $_GET['id'], $_GET['is_purchase'], $_GET['adjust_class_id']);
        }
        die(json_encode($data));
    }

    public function sales_to_purchase_ajax() {
        $insert = $this->_registry->purchase->convert_sales_to_multi_purchase($_POST['Products']);
        die(empty($insert) ? 'OK' : $insert[0]);
    }

    public function sales_quotatin_revision_ajax() {
        $columns = array('date_time', 'version_nb',
            array(
                'db' => 'version_id',
                'dt' => 2,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "isDropDown" => false,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("View"),
                                        "class" => "view_rev",
                                        "icon" => "fa-eye",
                                        "href" => "Inventory/quotationOrder/quotation/sales/rev/" . $d,
                                        "permission" => "view_sales_quotation_revesion"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'version_id';
        $table = 'tbl_versions';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' main_id = "' . $_GET['id'] . '"');
        echo json_encode($data);
    }

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

    public function deleteShippingCompany() {
        $delete = $this->_registry->shipping->setData($_GET)->deleteShippingCompany();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getShippingCompanyData() {
        $data = CommonFunctions::CommonView('shipping_company_list', ['shipping_company_id'], [$_GET['shipping_company_id']])[0];
        die(json_encode($data));
    }

    public function shipping_company_ajax() {
        $columns = array('shipping_company_name', 'shipping_account_name', 'shipping_company_fees',
            array(
                'db' => 'shipping_company_id',
                'dt' => 3,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#shipping_company_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_shipping_company"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_shipping_company"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'shipping_company_id';
        $table = 'shipping_company_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function shipping_list_ajax() {
        $cond = ' current_year_id = "' . $this->year_id . '"';
        if (!empty($_GET['shipping_company_id']))
            $cond .= 'And shipping_company_id = "' . $_GET['shipping_company_id'] . '"';
        else
            $cond .= ' and shipping_company_id is not null';
        if (is_numeric($_GET['customer_id'])) {
            $customer_id = $_GET['customer_id'];
            $cond .= ' and Customer_ID = "' . $customer_id . '"';
        }
        if (is_numeric($_GET['shipping_status_id'])) {
            $shipping_status = $_GET['shipping_status_id'];
            $cond .= ' and shipping_status_id = "' . $shipping_status . '"';
        }
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and Invoice_Date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }
        if (!empty($_GET['pick_up_from_date']) && !empty($_GET['pick_up_to_date'])) {
            $cond .= ' and pick_up_date between "' . $_GET['pick_up_from_date'] . '" AND  "' . $_GET['pick_up_to_date'] . '"';
        }
        if (!empty($_GET['drop_off_from_date']) && !empty($_GET['drop_off_to_date'])) {
            $cond .= ' and drop_off_date between "' . $_GET['drop_off_from_date'] . '" AND  "' . $_GET['drop_off_to_date'] . '"';
        }
        if (!empty($_GET['paid_type_id'])) {
            if ($_GET['paid_type_id'] == 1)
                $cond .= ' and Payment_Paid_Amount = 0';
            else
            if ($_GET['paid_type_id'] == 2)
                $cond .= ' and Payment_Paid_Amount = Invoice_Net_Total';
        }


        $columns = array(
            array('db' => 'Invoice_ID_Auto', 'dt' => 0, "formatter" => function($d, $row) {
                    return (($row['shipping_status_id'] == 1 && !empty($_GET['shipping_api']) || ($row['shipping_status_id'] <= 2 && empty($_GET['shipping_api']) && !empty($_GET['shipping_company_id'])) || ($row['shipping_status_id'] == 8 || $row['shipping_status_id'] == 4) && !empty($_GET['shipping_company_id'])) ? '<input type="checkbox" data-id="' . $d . '"  class="inv_check_td pull-left"/>' : '') . (!$this->controller_permission->hasPermission('ViewSalesInvoice') ? $row['invoice_nb'] : '<a  href="javascript:;" class="openFrame" data-src="Inventory/' . ((!empty($_GET['shipping_folder']) && $_GET['shipping_folder'] == 'aramex') ? 'view_shipment' : 'ViewInvoice') . '/' . $row['Invoice_ID_Auto'] . ((!empty($_GET['shipping_folder']) && $_GET['shipping_folder'] == 'aramex') ? '' : '/') . '?is_pop=1">' . $row['invoice_nb'] . '</a>' . ((!empty($_GET['shipping_folder']) && $_GET['shipping_folder'] == 'aramex') ? '<a  href="javascript:;" class="openFrame" data-src="Inventory/ViewInvoice/' . $row['Invoice_ID_Auto'] . '/?is_pop=1">  <i class="fa fa-eye"></i></a>' : ''));
                }),
            array('db' => 'Customer_Name', 'dt' => 1, "formatter" => function($d, $row, $is_excel) {
                    return $is_excel ? $d : '<a href="javascript:;" class="openFrame" data-src="Inventory/viewCustomerDetails/' . $row['Customer_ID'] . '?is_pop=1&modal=1">' . $d . '</a>';
                }), 'Invoice_Date',
            array('db' => 'Collection', 'dt' => 3, "formatter" => function($d, $row) {
                    $collection_value = $row['Collection'];
                    if ($row['Invoice_Currency'] != 84)
                        $collection_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Invoice_Currency'], 84, $row['Collection']);
                    return CommonFunctions::formatNumber($collection_value) . ' L.L.';
                }),
            array('db' => 'Customer_ID', 'dt' => 4, "formatter" => function($d, $row) {
                    return '<input type="hidden" name="shipping_address" value="' . ((!empty($row['address_id']) && !empty($_GET['shipping_company_id'])) ? $row['address_id'] : '') . '" data-select-name="' . ((!empty($row['shipping_title']) && !empty($_GET['shipping_company_id'])) ? $row['shipping_title'] : '') . '" class="full-width" data-invoice-id="' . $row['Invoice_ID_Auto'] . '"  ' . (empty($_GET['shipping_company_id']) ? 'disabled' : '') . ' data-customer-id="' . $d . '"/>';
                }), 'pick_up_date', 'drop_off_date', 'DBNumber', 'Invoice_Description', 'shipping_note', 'shipping_status',
            'api_other_response', 'Invoice_Currency', 'invoice_nb', 'address_id', 'shipping_title', 'shipping_status_id');
        $key = 'Invoice_ID_Auto';
        $table = 'shipping_list';
        //                $key = 'ID';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function get_total_shippings() {
        $data = $this->_registry->shipping->setData($_GET)->get_total_shippings();
        die($data);
    }

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

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

    public function cancel_private_shipping() {
        $submit = $this->_registry->shipping->setData($_GET)->cancel_private_shipping();
        die(empty($submit) ? "ok" : $submit[0]);
    }

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

    public function total_ordered_items_report() {
        $cond = ' current_year_id="' . $this->year_id . '"';
        if (!empty($_GET['From_Date'])) {
            $cond .= ' AND date(delivery_date) between "' . $_GET['From_Date'] . '" AND  "' . $_GET['To_Date'] . '"';
        }
        if (isset($_GET['category']) && !empty($_GET['category'])) {
            $cond .= ' AND Category_ID in (' . $_GET['category'] . ')';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' AND Supplier_ID = "' . $_GET['customer_id'] . '" ';
        }
        if (!empty($_GET['date_created_from'])) {
            $cond .= ' AND date_created between "' . $_GET['date_created_from'] . '" AND  "' . $_GET['date_created_to'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' AND branch_id = "' . $_GET['branch_id'] . '" ';
        }
        if (isset($_GET['is_sales'])) {
            $cond .= ' AND is_sales = "' . $_GET['is_sales'] . '" ';
        }
        if (isset($_GET['users']) && !empty($_GET['users'])) {
            $cond .= ' AND Logged_ID in (' . $_GET['users'] . ')';
        }

        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (!empty($_GET['status_id']) && $_GET['status_id'] != 0) {
            $cond .= ' and is_converted = "' . ($_GET['status_id'] == 1 ? '0' : '1') . '"';
        }
        $group = ' GROUP BY Item_ID,UOM_ID,Currency_ID ';
        $columns = array('Product_Name', 'Product_Code',
            array('db' => 'SUM(Quantity)', 'dt' => 2, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['UOM_Name'];
                }),
            array('db' => 'SUM(total_price+vat_amount)', "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }), 'UOM_Name', 'Currency_Symbol'
        );
        //sales_return_mov
        $key = 'Item_ID';
        $table = 'mov_sales_order';
        //                       die($cond);
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group);
        echo json_encode($data);
    }

    public function submitCustomer() {
        $submit = $_POST['Customer_ID'] == '' ? $this->_registry->customer->setData($_POST)->createCustomer() : $this->_registry->customer->setData($_POST)->updateCustomer();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function updateInvoiceShippingAddress() {
        $submit = $this->_registry->customer->setData($_GET)->updateInvoiceShippingAddress();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getCustomerDetails() {
        $data['main'] = $this->_registry->customer->ViewAllCustomerDetails($_GET['Customer_ID'])[0];
        $data['allergies'] = $data['intolerances'] = array();
        unset($data['main']['password']);
        if (!empty($data['main']['allergy_id']))
            $data['allergies'] = $this->_registry->customer->ViewByTableEntry('tbl_allergy', 'allergy_id', 'allergy_name', $data['main']['allergy_id']);
        if (!empty($data['main']['intolerance_id']))
            $data['intolerances'] = $this->_registry->customer->ViewByTableEntry('tbl_intolerance', 'intolerance_id', 'intolerance_name', $data['main']['intolerance_id']);
        $data['contacts'] = CommonFunctions::CommonView('tbl_customer_supplier_contacts', ['main_id', 'type_id'], [$_GET['Customer_ID'], '1']);
        $data['branches'] = CommonFunctions::CommonView('tbl_customer_branches', ['customer_id'], [$_GET['Customer_ID']]);
        $data['shipping_address'] = $this->_registry->customer->getShippingAddresses($_GET['Customer_ID']);
        $data['customer_sales_man'] = $this->_registry->customer->getCustomerSales($_GET['Customer_ID']);
        $data['customer_user_data'] = $this->_registry->customer->getCustomerUser($_GET['Customer_ID']);
        die(json_encode($data));
    }

    public function get_default_uom() {
        $data = Product::get_default_uom($_GET['pid'], $_GET['type']);
        die(json_encode($data));
    }

    public function get_products_to_build() {
        $data = $this->_registry->Product->get_products_to_build($_GET);
        $html = Forms::build_table_html($data['data']);
        die(json_encode(['html' => $html, 'show_alert' => $data['show_alert'], 'row_count' => $data['row_count']]));
        //                                                                                                                                echo json_encode(array("data" => $data, "draw" => 1, "recordsFiltered" => count($data), "recordsTotal" => count($data)));
    }

    public function build_products_with_prices() {
        $data = $this->_registry->Product->setData($_GET)->build_products_with_prices();
        die(json_encode($data));
        //                                                                                                                                echo json_encode(array("data" => $data, "draw" => 1, "recordsFiltered" => count($data), "recordsTotal" => count($data)));
    }

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

    public function deleteSubscriptionSetting() {
        $delete = $this->_registry->subscriptions->setData($_GET)->deleteSubscriptionSetting();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getSubscriptionSettingData() {
        $data = $this->_registry->subscriptions->getSubscriptionSettingData($_GET['subscription_id']);
        die(json_encode($data));
    }

    public function subscription_list_ajax() {
        $columns = array('subscription_name', 'Currency_Name',
            array('db' => 'is_active', 'dt' => 2, 'formatter' => function( $d, $row, $excel ) {
                    return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
                }),
            array(
                'db' => 'subscription_id',
                'dt' => 3,
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#subscription_setting_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_subscription_setting"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_subscription_setting"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'subscription_id';
        $table = 'subscription_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function deleteCustomerSubscription() {
        $delete = $this->_registry->subscriptions->setData($_GET)->deleteCustomerSubscription();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getCustomerSubscriptionData() {
        $check_cust_sub_used = $this->_registry->subscriptions->checkCustomerSubscription($_GET['customer_subscription_id']);
        $data = CommonFunctions::CommonView('customer_subscription_list', ['customer_subscription_id'], [$_GET['customer_subscription_id']])[0];
        $data['check_cust_sub_used'] = $check_cust_sub_used;
        die(json_encode($data));
    }

    public function customer_subscription_list_ajax() {
        $condition = '';
        if (is_numeric($_GET['status_id']))
            $condition .= ' and is_active ="' . $_GET['status_id'] . '"';
        if (!empty($_GET['customer_address']))
            $condition .= ' and Customer_Address  LIKE "' . $_GET['customer_address'] . '"';
        if (!empty($_GET['main_block_id']) && empty($_GET['block_id'])) {
            $block_ids = CommonFunctions::get_blocks($_GET['main_block_id']);
            $condition .= ' and block_id in (' . $block_ids . ') ';
        } else {
            if (!empty(smc_session()['block_ids']) && empty($_GET['block_id'])) {
                $block_ids_str = '';
                $block_ids = explode(",", smc_session()['block_ids']);
                foreach ($block_ids as $block_id)
                    $block_ids_str .= ($block_ids_str == '' ? '' : ',') . CommonFunctions::get_blocks($block_id);
                $condition .= ' and (block_id in (' . $block_ids_str . ') or block_id is null) ';
            }
        }
        if (!empty($_GET['block_id'])) {
            $block_ids = CommonFunctions::get_blocks($_GET['block_id']);
            $condition .= ' and block_id in (' . $block_ids . ') ';
        }
        $columns = array('Customer_Name', 'Customer_Address', 'block_name', 'subscription_name',
            'start_date', 'next_due_date', 'note',
            array('db' => 'is_active', 'formatter' => function( $d, $row, $excel ) {
                    return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
                }),
            array(
                'db' => 'customer_subscription_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "primary",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#customer_subscription_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_customer_subscription"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_customer_subscription"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'customer_subscription_id';
        $table = 'customer_subscription_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }

    public function SubscriptionFeesList() {
        $cond = '';

        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and Invoice_Date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }

        if (!empty($_GET['from_paid_date']) && !empty($_GET['to_paid_date'])) {
            $cond .= ' and date_time between "' . $_GET['from_paid_date'] . '" AND  "' . $_GET['to_paid_date'] . '" or date_time like "' . $_GET['from_paid_date'] . '%" ';
        }

        if (empty($this->controller_permission->hasPermission('show_all_subscriptions')) && !empty( smc_session()['user_details']['Employee_ID'])) {
            $Employee_ID = smc_session()['user_details']['Employee_ID'];
            $cond .= ' and  `sales_emp_id`  = "' . $Employee_ID . '"';
        }
        if (is_numeric($_GET['salesman_id'])) {
            $Employee_ID = $_GET['salesman_id'];
            $cond .= ' and  `sales_emp_id`  = "' . $Employee_ID . '"';
        }

        if (is_numeric($_GET['customer_id'])) {
            $customer_id = $_GET['customer_id'];
            $cond .= ' and Customer_ID = "' . $customer_id . '"';
        }

        if (!empty($_GET['paid_status'])) {
            if ($_GET['paid_status'] == 4) {
                $cond .= ' and paid_status in (1,2)';
            } else {
                $cond .= ' and paid_status ="' . $_GET['paid_status'] . '"';
            }
        }
        if (is_numeric($_GET['paid_type']))
            $cond .= ' and paid_type ="' . $_GET['paid_type'] . '"';
        if (!empty($_GET['subscription_id'])) {
            $cond .= ' and subscription_id = "' . $_GET['subscription_id'] . '"';
        }
        if (!empty($_GET['category_id'])) {
            $cond .= ' and category_id = "' . $_GET['category_id'] . '"';
        }
        if (!empty($_GET['main_block_id']) && empty($_GET['block_id'])) {
            $block_ids = CommonFunctions::get_blocks($_GET['main_block_id']);
            $cond .= ' and block_id in (' . $block_ids . ') ';
        } else {
            if (!empty(smc_session()['block_ids']) && empty($_GET['block_id'])) {
                $block_ids_str = '';
                $block_ids = explode(",", smc_session()['block_ids']);
                foreach ($block_ids as $block_id)
                    $block_ids_str .= ($block_ids_str == '' ? '' : ',') . CommonFunctions::get_blocks($block_id);
                $cond .= ' and (block_id in (' . $block_ids_str . ') or block_id is null) ';
            }
        }
        if (!empty($_GET['block_id'])) {
            $block_ids = CommonFunctions::get_blocks($_GET['block_id']);
            $cond .= ' and block_id in (' . $block_ids . ') ';
        }
        $_GET['cond'] = $cond;
        $act_cust_total_sub_fees = smc_session()['default_setting']['act_cust_total_sub_fees'];
        $columns = array(
            array('db' => 'ID_Auto', "formatter" => function($d, $row) {
                    return '<input type="checkbox" data-inv="' . $row['ID_Auto'] . '" data-customer-id="' . $row['Customer_ID'] . '" data-main-id="' . $row['main_id'] . '" data-nb="' . $d . '" data-currency-id="' . $row['Invoice_Currency'] . '" data-total="' . ($row['Invoice_Net_Total'] + $row['inv_currency_round']) . '" data-job-id="' . $row['job_id'] . '" data-project-id="' . $row['project_id'] . '" data-customer-subscription-id="' . $row['customer_subscription_id'] . '" class="inv_td pull-left"/>' . $d;
                }),
            array('db' => 'Customer_Name', "formatter" => function($d, $row) {
                    return (smc_session()['default_setting']['act_cust_total_sub_fees'] == 1 ? '<input type="checkbox" name="cust_name_checkbox" class="cust_name_checkbox" data-customer-id="' . $row['Customer_ID'] . '"/>' : '') . $d;
                })
            ,'date_time', 'Customer_Address', 'subscription_name', 'block_name', 'Invoice_Date',
            array('db' => 'Invoice_Net_Total', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d + $row['inv_currency_round']) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'paid_amount', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'Invoice_Net_Total', "formatter" => function($d, $row) {
                    return ($_GET['paid_status'] == 1 || $_GET['paid_status'] == 2 || $_GET['paid_status'] == 4) ? '<input type="number" class="form-control remaining_amount" data-remaining="' . round(($d + $row['inv_currency_round'] - $row['paid_amount']), 7) . '"   value="' . round(($d + $row['inv_currency_round'] - $row['paid_amount']), 7) . '" ' . ($this->controller_permission->hasPermission('subscription_paid_amount_input') ? '' : 'readonly') . '/>' : (CommonFunctions::formatNumber($d + $row['inv_currency_round'] - $row['paid_amount']) . ' ' . $row['Currency_Symbol']);
                }),
            array('db' => 'discount_amount', "formatter" => function($d, $row) {
                    return (($_GET['paid_status'] == 1 || $_GET['paid_status'] == 2 || $_GET['paid_status'] == 4) && $this->controller_permission->hasPermission('add_discount_on_subscription') ? '<input type="number" class="form-control disc_amount" data-total="' . round(($row['Invoice_Net_Total'] + $row['inv_currency_round']), 7) . '" data-disc="' . $d . '" value="' . $d . '"/>' : CommonFunctions::formatNumber($d));
                })
        );
        if ($act_cust_total_sub_fees == 1) {
            $columns[] = array('db' => 'Customer_ID', 'formatter' => function( $d, $row) {
                    return '<b>' . CommonFunctions::formatNumber($_GET['customer_totals'][$row['Customer_ID']]['local_amount']) . '</b>';
                });
        }
        $columns[] = array('db' => 'Invoice_Net_Total');
        $columns[] = array('db' => 'Currency_Symbol');
        $columns[] = array('db' => 'Invoice_Currency');
        $columns[] = array('db' => 'main_id');
        $columns[] = array('db' => 'paid_status');
        $columns[] = array('db' => 'Customer_ID');
        $columns[] = array('db' => 'job_id');
        $columns[] = array('db' => 'project_id');
        $columns[] = array('db' => 'customer_subscription_id');
        $columns[] = array('db' => 'inv_currency_round');

        $table_view = 'subscription_fees_list';
        $key = 'ID_Auto';
        $table = $table_view;
        $row_cb = [];
        if ($act_cust_total_sub_fees == 1) {
            $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'sub_fees_ftch_row']],
                'fetch_all_callback' => ['ft' => [$this, 'sub_fees_ftch_all']],
                'order' => ' Customer_ID,subscription_id,Invoice_Date '];
        }
        $data = DataTable::complex($_GET, $table, $key, $columns, (' current_year_id = "' . $this->year_id . '" and is_open_balance = 0 ' . $cond), null, null, $row_cb);
        echo json_encode($data);
    }

    public function sub_fees_ftch_row(&$data, &$row) {
        $_GET['tmp__all_ids'][$row['Customer_ID']] = false;
    }

    public function sub_fees_ftch_all(&$data) {
        if (empty($_GET['tmp__all_ids']))
            return true;
        $query = $this->db->query('SELECT 
                sum((Invoice_Net_Total+inv_currency_round)*current_rate) as local_amount,
                Customer_ID
            from  subscription_fees_list
            where Customer_ID in (' . implode(',', array_keys($_GET['tmp__all_ids'])) . ')  ' . $_GET['cond'] . '
            group by Customer_ID');
        while ($row = $this->db->assoc($query)) {
            $_GET['customer_totals'][$row['Customer_ID']] = $row;
        }

        //                echo"<pre>";die(print_r($_GET['customer_totals']));
    }

    public function deleteSubscriptionFees() {
        $delete = $this->_registry->subscriptions->setData($_GET)->deleteSubscriptionFees();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function deleteSubscriptionFeesPayments() {
        $delete = $this->_registry->subscriptions->setData($_GET)->deleteSubscriptionFeesPayments();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function subscription_details_list() {
        $cond = '';
        if (!empty($_GET['subscription_id']))
            $cond .= ' and subscription_id ="' . $_GET['subscription_id'] . '"';
        if (!empty($_GET['product_id']))
            $cond .= ' and product_id ="' . $_GET['product_id'] . '"';
        if (!empty($_GET['type_id']))
            $cond .= ' and type_id ="' . $_GET['type_id'] . '"';
        $columns = array('subscription_name', 'Product_Name', 'UOM_Name',
            array('db' => 'start', 'dt' => 3, "formatter" => function($d, $row) {
                    return $row['type_id'] == 1 ? '--- ---' : $d;
                }), array('db' => 'end', 'dt' => 4, "formatter" => function($d, $row) {
                    return $row['type_id'] == 1 ? '--- ---' : $d;
                }), array('db' => 'price', 'dt' => 5, "formatter" => function($d, $row) {
                    return '<input  type="number" name="current_price" class="form-control" value="' . $d . '" data-id="' . $row['detail_fees_id'] . '"/>';
                }), 'Currency_Symbol',
            array('db' => 'fees_type_id', 'dt' => 7, "formatter" => function($d, $row) {
                    return CommonLanguage::getMessage($d == 1 ? 'fixed' : 'per_qty');
                }), 'type_id', 'detail_fees_id');
        $table_view = 'subscription_details_list';
        $key = 'detail_fees_id';
        $table = $table_view;
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function customer_subscription_open_balance() {
        $condition = '';
        $customer_sub_ids_array = $this->_registry->subscriptions->setData($_GET)->getCustomerSupscriptionIdsUsed();
        if (!empty($_GET['subscription_id']))
            $condition .= ' and subscription_id = "' . $_GET['subscription_id'] . '"';
        if (is_numeric($_GET['customer_id']))
            $condition .= ' and Customer_ID = "' . $_GET['customer_id'] . '"';
        if (!empty($_GET['period_unit']))
            $condition .= ' and period_unit = "' . $_GET['period_unit'] . '"';
        if (!empty($customer_sub_ids_array) && $_GET['current_balance_type'] == 'open')
            $condition .= ' and customer_subscription_id not in (' . implode(",", $customer_sub_ids_array) . ')';
        if ($_GET['current_balance_type'] == 'close') {
            if (empty($customer_sub_ids_array))
                $condition .= ' and 1=2';
            else
                $condition .= ' and customer_subscription_id in (' . implode(",", $customer_sub_ids_array) . ')';
        }
        $columns = array('subscription_name', 'Customer_Name', 'Customer_Address', 'customer_subscription_title', 'product_uom',
            array('db' => 'customer_subscription_id', 'dt' => 5, "formatter" => function($d, $row) {
                    $current_value = '';
                    if ($_GET['current_type'] == 2) {
                        $current_value = $this->_registry->subscriptions->getSubscriptionPreviousBalance($row['subscription_id'], $row['detail_id'], $row['customer_subscription_id']);
                    }
                    return '<input type="number" name="open_balance" class="form-control" data-customer-subscription-id="' . $row['customer_subscription_id'] . '" data-subscription-id="' . $row['subscription_id'] . '" data-subscription-detail-id="' . $row['detail_id'] . '" data-main-date="' . $row['next_due_date'] . '" value="' . $current_value . '"/>';
                }), 'detail_id', 'subscription_id', 'customer_subscription_id', 'next_due_date');
        $table = 'customer_subscription_setting_details';
        $key = 'detail_id';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' sub_active_flag = 1 and cust_sub_active_flag = 1 and depend_previous = 1' . $condition);
        echo json_encode($data);
    }

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

    public function customer_subscription_fees() {
        $data = $this->_registry->subscriptions->setData($_GET)->customerSubscriptionFees();
        $html = Forms::build_table_html($data);
        die($html);
    }

    //    public function customer_subscription_open_balance() {
    //        $data = $this->_registry->subscriptions->setData($_GET)->getCustomerSubscriptionOpenBalances();
    //        $html = Forms::build_table_html($data);
    //        die($html);
    //    }

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

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

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

    public function submitSubscriptionMultiDiscount() {
        $submit = $this->_registry->subscriptions->setData($_POST)->edit_disc_cust_subscription();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function check_supplier_classes() {
        $data = $this->_registry->vendor->check_supplier_classes($_GET['supp_id']);
        die(json_encode($data));
    }

    public function get_prod_disc_by_class() {
        $disc = $this->_registry->Product->get_prod_disc_by_class($_GET['pid'], $_GET['class_id'], $_GET['uom_id']);
        die($disc);
    }

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

    public function InvoiceDiscountList() {
        //        $IsVendor = true;
        $cond = ' is_actual = "' . $_GET['is_actual'] . '"';
        if (isset($_GET['Date_From']) && isset($_GET['Date_To'])) {
            $FromDate = $_GET['Date_From'];
            $ToDate = $_GET['Date_To'];
            $cond .= ' and Invoice_Date >= "' . $FromDate . '" AND Invoice_Date <= "' . $ToDate . '"';
        }

        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        if (!empty($_GET['branch_id'])) {
            $cond .= ' AND branch_id = "' . $_GET['branch_id'] . '"';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' AND Customer_ID = "' . $_GET['customer_id'] . '"';
        }
        if (!empty($_GET['user_id'])) {
            $cond .= ' AND Logged_ID = "' . $_GET['user_id'] . '"';
        }

        if (empty($_GET['show_all_invoice'])) {
            $cond .= ' and (`total_details_discount` > 0 or `total_invoice_discount` > 0) ';
        }
        $columns = array('invoice_nb',
            array('db' => 'Customer_Name', 'dt' => 1, "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }), 'Invoice_Date',
            array('db' => 'Invoice_Net_Total', 'dt' => 3, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'total_invoice_discount', 'dt' => 4, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'total_details_discount', 'dt' => 5, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'total_details_discount', 'dt' => 6, "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($row['total_invoice_discount'] + $row['Invoice_Net_Total'] + $d) . ' ' . $row['Currency_Symbol'];
                }),
            'User_Full_Name', 'Currency_Symbol'
        );




        $key = 'Invoice_ID_Auto';
        $table = 'invoice_discount_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function ExchangeListRequests() {
        //        $IsVendor = true;
        $cond = ' is_actual = "' . $_GET['is_actual'] . '" ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and exchange_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }
        if (is_numeric($_GET['customer_id']))
            $cond .= ' and Customer_ID ="' . $_GET['customer_id'] . '"';
        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        $columns = array('exch_nb', 'Customer_Name', 'exchange_date',
            array('db' => 'inv_nb', 'dt' => 3, "formatter" => function($d, $row) {
                    return $d;
                }),
            array('db' => 'ret_nb', 'dt' => 4, "formatter" => function($d, $row) {
                    return $d;
                }),
            array('db' => 'exchange_id', 'dt' => 5, 'formatter' => function( $d, $row) {
                    $option_arr = [["title" => CommonLanguage::getMessage("view"),
                    "class" => "View openFrame",
                    "permission" => "view_exchange",
                    "icon" => "fa-eye",
                    "attr" => "data-src='Inventory/pos_view_exchange/{$row['exchange_id']}?is_pop=1'"
                        ],
                        ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "edit",
                            "permission" => "edit_exchange",
                            "icon" => "fa-pencil",
                            "href" => "Inventory/ReturnNoInvoice/sales/exchange/{$row['exchange_id']}"
                        ],
                        ["title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete",
                            "permission" => "delete_exchange",
                            "icon" => "fa-trash"]];
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $row['exchange_id'],
                                "ActionOption" => $option_arr]);
                    return $html;
                }));

        $key = 'exchange_id';
        $table = 'exchange_list';
        //                $key = 'ID';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function return_damage_report() {
        $cond = ' where Is_Actual = "' . $_GET['is_actual'] . '" AND current_year_id = "' . $this->year_id . '"';

        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and r.branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and r.branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and Return_Invoice_Date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }
        $columns = array('Product_Code', 'Product_Name', 'returned_qty', 'damaged_qty', 'UOM_Name', 'total_price', 'UOM_Name'
        );
 
        $key = 'Return_Invoice_ID';
        $table = '(SELECT d.Return_Invoice_ID,p.Product_Code,p.Product_Name,
            sum(if(`is_damaged`=0,`Return_Product_Quantity`,0)) as returned_qty,
            sum(if(`is_damaged`=1,`Return_Product_Quantity`,0)) as damaged_qty,sum(`unit_price`*r.current_rate) as total_price,
            u.UOM_Name ,r.branch_id FROM `tbl_accounting_return_items` d 
            join tbl_accounting_return_invoices r on r.`Return_Invoice_ID` = d.`Return_Invoice_ID` 
            join tbl_stock_products p on p.Product_ID = d.Product_ID join tbl_stock_uom u 
            on u.UOM_ID = p.UOM_ID  ' . $cond . ' group by d.Product_ID) as dummy';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function DetailedOrderProductReportAjax() {
        $freq = smc_escape($_GET['freq']);
        $date = $_GET['Date'];
        $cond = ' current_year_id="' . $this->year_id . '" ';
        if ($freq == 1) {
            $cond .= '  AND Date = "' . smc_escape($date) . '"';
        } else if ($freq == 2) {
            $cond .= '  AND MONTH(Date) = "' . smc_escape($date[1]) . '" AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        } else if ($freq == 3) {
            $cond .= '  AND YEAR(Date) = "' . smc_escape($date[0]) . '"';
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= ' and is_actual = 0 ';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' and Supplier_ID = "' . $_GET['customer_id'] . '" ';
        }
        if (!empty($_GET['product_id'])) {
            $cond .= ' and Product_ID = "' . $_GET['product_id'] . '" ';
        }
        if (!empty($_GET['created_by_id'])) {
            $cond .= ' and created_logged_id = "' . $_GET['created_by_id'] . '" ';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_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 (isset($_GET['is_sales'])) {
            $cond .= ' and is_sales = "' . $_GET['is_sales'] . '" ';
        }
        if (!empty($_GET['status_id']) && $_GET['status_id'] != 0) {
            $cond .= ' and is_converted = "' . ($_GET['status_id'] == 1 ? '0' : '1') . '"';
        }
        $columns = array(array('db' => 'order_nb', 'formatter' => function($d, $row) {
                    return '<span class="openFrame" style="cursor:pointer;" data-src="Inventory/ViewQuotationOrder/order/' . $row['Order_ID'] . '?is_pop=1">' . $d . '</span>';
                }),
            array('db' => 'Name', 'formatter' => function($d) {
                    return $d ? $d : '-- --';
                }), 'Product_Name', 'date_created',
            array('db' => 'Item_Quantity_Current', "formatter" => function($d, $row) {
                    return Forms::DecimalNumber($d) . ' ' . $row['UOM_Name'];
                }),
            array('db' => 'Unit_Price', "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }),
            array('db' => 'discount_amount', "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . CommonFunctions::formatNumber($d);
                }),
            array('db' => 'total_price', "formatter" => function($d, $row) {
                    return $row['Currency_Symbol'] . ' ' . Forms::DecimalNumber($d);
                }), 'UOM_Name', 'Currency_Symbol', 'Order_ID'
        );
        $key = 'Entry_ID';
        $table = 'mov_sales_order';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY date_created asc');
        echo json_encode($data);
    }

    public function importRecipe() {
        $Ret = $this->_registry->Product->import_recipe();
        //        die(empty($Ret) ? "OK" : "error");
        die(json_encode($Ret));
    }

    public function category_trial_balance() {
        if (!empty($_GET['is_disc']))
            $data = $this->_registry->Product->setData($_GET)->cat_trial_blanc_with_disc_report();
        else
            $data = $this->_registry->Product->setData($_GET)->category_trial_balance();
        $html = Forms::build_table_html($data['data']);
        die(json_encode(['html' => $html, 'totals' => $data['totals']]));
    }

    public function periodic_sales_purchase_mov() {
        $cond = ' ';
        if (!empty($_GET['From_Date']) && !empty($_GET['To_Date'])) {
            if (!empty($_GET['is_sales']))
                $cond .= ' and Invoice_Date between "' . $_GET['From_Date'] . '" and "' . $_GET['To_Date'] . '" ';
            else
                $cond .= ' and i.Purchase_Date between "' . $_GET['From_Date'] . '" and "' . $_GET['To_Date'] . '" ';
        }
        if (!empty($_GET['date_created_from']) && !empty($_GET['date_created_to']))
            $cond .= ' and i.date_created between "' . $_GET['date_created_from'] . '" and "' . $_GET['date_created_to'] . '" ';
        if (!empty($_GET['customer_id'])) {
            if (!empty($_GET['is_sales']))
                $cond .= ' and i.Customer_ID = "' . $_GET['customer_id'] . '" ';
            else
                $cond .= '  and i.Supplier_ID = "' . $_GET['customer_id'] . '" ';
        }
        if (!empty($_GET['users']))
            $cond .= ' and i.Logged_ID in (' . $_GET['users'] . ') ';
        if (empty($_GET['is_actual']))
            $cond .= ' and i.is_actual = "' . $_GET['is_actual'] . '" ';
        if (!empty($_GET['branch_id']))
            $cond .= ' and i.branch_id = "' . $_GET['branch_id'] . '" ';
        if (!empty($_GET['sales_man_id']) && !empty($_GET['is_sales']))
            $cond .= ' and i.Sales_ID = "' . $_GET['sales_man_id'] . '" ';
        $columns = array(
            array('db' => (!empty($_GET['is_sales']) ? 'Invoice_Date' : 'Purchase_Date'), 'formatter' => function($d) {
                    return $_GET['period'] == 1 ? $d : ($_GET['period'] == 2 ? substr($d, 0, 7) : substr($d, 0, 4) );
                }),
            array('db' => ($_GET['type'] == 2 ? 'Product_Name' : 'Cat_Name'), 'formatter' => function($d) {
                    return empty($_GET['type']) ? CommonLanguage::getMessage(!empty($_GET['is_sales']) ? 'total_sales' : 'total_purchase') : $d;
                }),
            array('db' => 'quantity', "formatter" => function($d, $row) {
                    return ($_GET['type'] == 2 ? Forms::DecimalNumber($d) : '--');
                }), 'UOM_Name',
            array('db' => 'unit_price', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d);
                })
        );
        $group_period_col = '';
        if (!empty($_GET['period'])) {
            if ($_GET['period'] == 1)
                $group_period_col = !empty($_GET['is_sales']) ? 'i.Invoice_Date' : 'i.Purchase_Date';
            elseif ($_GET['period'] == 2)
                $group_period_col = !empty($_GET['is_sales']) ? 'month(i.Invoice_Date)' : 'month(i.Purchase_Date)';
            elseif ($_GET['period'] == 3)
                $group_period_col = !empty($_GET['is_sales']) ? 'year(i.Invoice_Date)' : 'year(i.Purchase_Date)';
        }

        $group = ' ';
        if (empty($_GET['type']))
            $group .= ' group by ' . $group_period_col;
        else if ($_GET['type'] == 1)
            $group .= ' group by ' . $group_period_col . ',p.Category_ID';
        else if ($_GET['type'] == 2)
            $group .= ' group by ' . $group_period_col . ',d.Product_ID';
        $key = 'Entery_ID';
        if (!empty($_GET['is_sales'])) {
            $table = '(SELECT d.Entery_ID,`Invoice_Date`,p.Product_Code,p.Product_Name,
            sum(d.Product_Quantity/uc.conversion_amount) as quantity,u.UOM_Name,
            sum(d.Product_Total_Price*' . ($_GET['currency_id'] == 1 ? 'i.current_rate' : 'i.second_currency_rate') . ') as unit_price,i.is_actual,cat.Cat_Name
            FROM tbl_invoice_products_details d 
            join `tbl_invoices` i on d.Invoice_ID_Auto = i.`Invoice_ID_Auto` 
            join tbl_stock_products p on p.Product_ID = d.Product_ID 
            join tbl_uom_conversions uc on uc.Product_ID = d.Product_ID and uc.uom_from = if(p.default_sales_uom<>0,p.default_sales_uom,p.UOM_ID) 
            join tbl_stock_uom u on (u.UOM_ID = if(p.default_sales_uom<>0,p.default_sales_uom,p.UOM_ID) )
            join tbl_product_cat cat on cat.Cat_ID = p.Category_ID
            where 1=1 ' . $cond . ' ' . $group . '
            ) as dump';
        } else {
            $table = '(SELECT d.`Item_ID` as Entery_ID,`Purchase_Date`,p.Product_Code,p.Product_Name,
            sum(d.`Item_Quantity`/uc.conversion_amount) as quantity,u.UOM_Name,
            sum(d.`Product_Total_Price`*' . ($_GET['currency_id'] == 1 ? 'i.current_rate' : 'i.second_currency_rate') . ') as unit_price,i.is_actual,cat.Cat_Name
            FROM tbl_inventory_purchase_items d 
            join `tbl_inventory_purchases` i on d.Purchase_ID_Auto = i.`Purchase_ID_Auto` 
            join tbl_stock_products p on p.Product_ID = d.Product_ID 
            join tbl_uom_conversions uc on uc.Product_ID = d.Product_ID and uc.uom_from = if(p.default_purchase_uom<>0,p.default_purchase_uom,p.UOM_ID) 
            join tbl_stock_uom u on (u.UOM_ID = if(p.default_purchase_uom<>0,p.default_purchase_uom,p.UOM_ID) )
            join tbl_product_cat cat on cat.Cat_ID = p.Category_ID
            where 1=1 ' . $cond . ' ' . $group . '
            ) as dump';
        }


        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function customer_supplier_codes() {

        $cond = ' 1=1 ';
        $person_cond = '';
        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 (!empty($_GET['family_id'])) {
            $cond .= ' and family_id = "' . $_GET['family_id'] . '" ';
        }
        //        if (!empty($_GET['person_id'])) {
        //            $cond .= ' and cust_supp_id = "' . $_GET['person_id'] . '" ';
        //        }
        if (isset($_GET['is_cust']) && isset($_GET['person_id']) && $_GET['person_id'] != '') {
            $person_cond .= ' and ' . ($_GET['is_cust'] == 1 ? 'customer_id' : 'supplier_id') . ' = "' . $_GET['person_id'] . '" ';
        }
        //       echo $cond;
        $columns = array('product_name',
            array('db' => 'cust_supp_code', 'formatter' => function($d, $row) {
                    return '<input type="text" value="' . $d . '" class="product_code form-control" data-id="' . $row['Product_ID'] . '" data-code="' . $d . '"/>';
                }), 'Product_ID'
        );
        $key = 'Product_ID';
        $table = '(select c.`customer_id`,c.supplier_id,p.Product_ID,concat(p.Product_Code," - ",p.Product_Name) as product_name,p.Category_ID,
            p.brand_id,p.family_id,ifnull(c.product_code,"") as cust_supp_code
                FROM tbl_stock_products p 
                left join `tbl_cust_supp_prod_codes` c on c.product_id = p.Product_ID ' . $person_cond . '
                where ' . $cond . ') as dump';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function add_cust_supp_codes() {
        $insert = $this->_registry->Product->setData($_GET)->add_cust_supp_codes();
        die(empty($insert) ? 'OK' : $insert[0]);
    }

    //    public function salesman_customer_list() {
    //        $cond = '  ';
    //        if (!empty($_GET['employee_id']))
    //            $cond .= ' and (employee_id = "' . $_GET['employee_id'] . '" or isnull(employee_id))';
    //        $columns = array(
    //            array('db' => 'Customer_ID', "formatter" => function($d, $row) {
    //                $html = '<div class="checkbox check-primary  ">
    //                    <input type="checkbox"  class="chooseCust" id = "check' . $row['auto_id'] . '" value = "' . (is_null($row['employee_id']) ? 0 : 1) . '" data-id="' . $d . '" ' . (is_null($row['employee_id']) ? '' : 'checked') . '/>
    //             <label for="check' . $row['auto_id'] . '"></label>
    //                </div>';
    //
    //                //                $html = '<input type="checkbox" class="chooseCust" data-id="'.$d.'" '.(is_null($row[4]) ? '' : 'checked').'/>';
    //                return $html;
    //            }), 'Account_Code', 'Customer_Name', 'Customer_Phone', 'Customer_Address', 'employee_id', 'auto_id', 'Customer_ID'
    //        );
    //        $key = 'auto_id';
    //        $table = '(select (@cnt := @cnt + 1) as auto_id,`c`.`Customer_ID`,`c`.`Customer_Name`,`c`.`Customer_Phone`,
    //            `c`.`Customer_Work_Phone`,c.Customer_Address,
    //            `uc`.`entry_id`,`uc`.`employee_id`,`a`.`Account_Code` AS `Account_Code` 
    //            from `tbl_customers` `c` left join `tbl_salesman_customers` `uc` 
    //            on `uc`.`customer_id` = `c`.`Customer_ID` ' . $cond . ' join `tbl_chart_of_accounts` `a` 
    //            on (`a`.`main_id` = `c`.`Customer_ID` and `a`.`main_type` = "cust" and `a`.`sub_type` = "main")) as cust
    //            ';
    //        //DataTable::db()->prepare("set @cnt := 0;")->execute();
    //        $stmt = DataTable::db()->prepare("set @cnt := 0");
    //        $stmt->execute();
    //        //
    //        $data = DataTable::complex($_GET, $table, $key, $columns);
    //        echo json_encode($data);
    //    }
    public function salesman_customer_list() {
        $cond = '  ';
        if (!empty($_GET['employee_id'])) {
            $emp_cust_arr = array();
            $emp_cond = "";
            if ($_GET['employee_id'] != 'no_link')
                $emp_cond .= " and employee_id = '{$_GET['employee_id']}' ";
            $query = $this->db->query('select customer_id from tbl_salesman_customers 
                where 1=1 ' . $emp_cond);
            while ($row = $this->db->assoc($query))
                $emp_cust_arr[] = $row['customer_id'];
            if (!empty($emp_cust_arr))
                $cond .= ' and c.Customer_ID ' . ($_GET['employee_id'] == 'no_link' ? ' not ' : ' ') . ' in (' . implode(',', $emp_cust_arr) . ') ';
            else
                $cond .= ($_GET['employee_id'] == 'no_link' ? '' : ' and 1=2 ');
        }
        if (!empty($_GET['user_id'])) {
            $user_cust_arr = array();
            $user_cond = "";
            if ($_GET['user_id'] != 'no_link')
                $user_cond .= " and user_id = '{$_GET['user_id']}' ";
            $query = $this->db->query('select customer_id from tbl_user_customers 
                where 1=1 ' . $user_cond);
            while ($row = $this->db->assoc($query))
                $user_cust_arr[] = $row['customer_id'];
            if (!empty($user_cust_arr))
                $cond .= ' and c.Customer_ID ' . ($_GET['user_id'] == 'no_link' ? ' not ' : ' ') . ' in (' . implode(',', $user_cust_arr) . ') ';
            else
                $cond .= ($_GET['user_id'] == 'no_link' ? '' : ' and 1=2 ');
        }

        //        if(!empty($cust_arr))
        //            $cond .= ' and c.Customer_ID in (' . implode(',',$cust_arr) . ') ';
        $_GET['salesman_arr'] = array();
        $query = $this->db->query('select Employee_ID,
            concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as Employee_Name
            from tbl_hrm_employee where Status_ID = 1');
        while ($row = $this->db->assoc($query)) {
            $_GET['salesman_arr'][$row['Employee_ID']] = $row['Employee_Name'];
        }
        $_GET['users_arr'] = array();
        $query = $this->db->query('select User_ID,User_Full_Name
            from tbl_common_users where is_app=1 and Status_ID = 1');
        while ($row = $this->db->assoc($query)) {
            $_GET['users_arr'][$row['User_ID']] = $row['User_Full_Name'];
        }
        $columns = array(
            'Account_Code', 'Customer_Name', 'Customer_Phone', 'Customer_Address',
            array('db' => 'salesman_ids', 'formatter' => function($d, $row) {
                    $str = ',' . $d . ',';
                    $html = '<select data-cust-id="' . $row['Customer_ID'] . '" class="sales_ids full-width" name="sales_ids" multiple data-init-plugin="select2" >
                    <option value="" disabled>' . CommonLanguage::getMessage('Select') . '</option>';
                    foreach ($_GET['salesman_arr'] as $sales_id => $sales_name) {
                        $html .= '<option value="' . $sales_id . '" ' . (strpos($str, ',' . $sales_id . ',') !== false ? 'selected' : '') . '>' . $sales_name . '</option>';
                    }
                    $html .= '</select>';
                    return $html;
                }),
            array('db' => 'user_ids', 'formatter' => function($d) {
                    $str = ',' . $d . ',';
                    $html = '<select class="user_ids full-width" name="user_ids" multiple data-init-plugin="select2" >
                    <option value="" disabled>' . CommonLanguage::getMessage('Select') . '</option>';
                    foreach ($_GET['users_arr'] as $user_id => $user_name) {
                        $html .= '<option value="' . $user_id . '" ' . (strpos($str, ',' . $user_id . ',') !== false ? 'selected' : '') . '>' . $user_name . '</option>';
                    }
                    $html .= '</select>';
                    return $html;
                }),
            'Customer_ID'
        );
        $key = 'Customer_ID';
        $table = '(select `c`.`Customer_ID`,`c`.`Customer_Name`,`c`.`Customer_Phone`,
            `c`.`Customer_Work_Phone`,c.Customer_Address,
            `uc`.`employee_id`,`a`.`Account_Code` AS `Account_Code`,
            group_concat(uc.employee_id) as salesman_ids,
            group_concat(u.user_id) as user_ids
            from `tbl_customers` `c` 
            left join `tbl_salesman_customers` `uc` on `uc`.`customer_id` = `c`.`Customer_ID` 
            left join `tbl_user_customers` `u` on `u`.`customer_id` = `c`.`Customer_ID`
             join `tbl_chart_of_accounts` `a` 
            on (`a`.`main_id` = `c`.`Customer_ID` and `a`.`main_type` = "cust" and `a`.`sub_type` = "main")
            where 1=1 ' . $cond . '
            group by c.Customer_ID
            ) as cust
            ';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function assign_salesman_user_customer() {
        $assign = $this->_registry->customer->setData($_POST)->assign_salesman_user_customer();
        die(empty($assign) ? 'OK' : 'error');
    }

    //    public function assign_salesman_customer() {
    //        $assign = $this->_registry->customer->setData($_POST)->assign_salesman_customer();
    //        die(empty($assign) ? 'OK' : 'error');
    //    }
    public function salesman_depot_list() {
        $columns = array(
            'employee_name', array('db' => 'depot_id', 'formatter' => function($d, $row) {
                    return '<input type="hidden" class="full-width depot_id" value="' . $d . '" data-select-name="' . $row['Depot_Name'] . '"/>';
                }), array('db' => 'Employee_ID', 'formatter' => function($d) {
                    return '<button class="btn btn-primary submit_salesman" data-emp="' . $d . '">' . CommonLanguage::getMessage('Save') . '</button>';
                }), 'Depot_Name'
        );
        $key = 'Employee_ID';
        $table = '(select Employee_ID,
            concat_ws(" ",`Employee_FirstName`,`Employee_MiddleName`,`Employee_LastName`) as employee_name,
            ifnull(s.depot_id,"") as depot_id,ifnull(d.Depot_Name,"") as Depot_Name
            from tbl_hrm_employee e left join tbl_salesman s on s.salesman_id = e.employee_id
            left join tbl_stock_depot_warehouse d on d.Depot_ID = s.depot_id
            ) as sales
            ';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function deleteGroup() {
        $delete = $this->_registry->common_inventory->setData($_GET)->deleteGroup();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function group_list() {
        $columns = array('group_name',
            array(
                'db' => 'group_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#group_modal',
                                                "class" => "edit",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_{$_GET['group_type']}_group"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_{$_GET['group_type']}_group"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'group_id';
        $table = 'tbl_general_groups';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' group_type ="' . $_GET['group_type'] . '"');
        echo json_encode($data);
    }

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

    public function deleteClass() {
        $delete = $this->_registry->common_inventory->setData($_GET)->deleteClass();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function class_list() {
        $columns = array('class_name',
            array(
                'db' => 'class_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#class_modal',
                                                "class" => "edit",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_{$_GET['class_type']}_group"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_{$_GET['class_type']}_group"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'class_id';
        $table = 'tbl_general_classes';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' class_type ="' . $_GET['class_type'] . '"');
        echo json_encode($data);
    }

    public function assign_salesman_depot() {
        $insert = $this->_registry->salesman->setData($_POST)->assign_salesman_depot();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function get_salesman_depot() {
        $data = $this->_registry->salesman->get_salesman_depot($_GET['salesman_id']);
        die(json_encode($data));
    }

    public function add_discount_report_setting_ajax() {
        $columns = array(
            'Cat_Name', 'current_type_name', 'percent', 'start_date',
            array('db' => 'report_setting_id', 'formatter' => function($d, $row) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#add_discount_modal',
                                                "class" => "edit",
                                                "attr" => "data-cat-id='{$row['category_id']}' data-cat-name='{$row['Cat_Name']}' data-date='{$row['start_date']}' data-percent='{$row['percent']}' data-type='{$row['current_type']}'",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_add_discount_percent_report"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_edit_discount_percent_report"
                                            ]
                    ]]);
                    return $html;
                }), 'category_id', 'current_type'
        );
        $key = 'report_setting_id';
        $table = '(select s.*,c.Cat_Name,if(current_type = 1,"Discount","Add") as current_type_name
            from tbl_add_discount_report_setting s join tbl_product_cat c on s.category_id = c.Cat_ID
            ) as temp
            ';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function submit_add_disc_report() {
        $insert = $this->_registry->Product->setData($_POST)->submit_add_disc_report();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function edit_add_disc_report() {
        $insert = $this->_registry->Product->setData($_POST)->edit_add_disc_report();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function delete_add_discount_report() {
        $insert = $this->_registry->Product->delete_add_discount_report($_GET['report_setting_id']);
        die(empty($insert) ? 'ok' : 'error');
    }

    public function get_add_disc_report_by_id() {
        $data = $this->_registry->Product->get_add_disc_report_by_id($_GET['report_setting_id']);
        die(json_encode($data));
    }

    public function delete_sales_purchase() {
        if ($_GET['is_return'] == 1) {
            $delete = $this->_registry->salesPurchase->delete_return_sales_purchase($_GET['id']);
        } else {
            $delete = $this->_registry->salesPurchase->delete_sales_purchase($_GET['id']);
        }
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function purchase_cat_list() {
        $columns = array('pur_cat_name',
            array('db' => 'pur_cat_id', 'formatter' => function($d, $row) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#add_pur_cat',
                                                "class" => "edit_cat",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_purchase_category"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete_cat",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_purchase_category"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'pur_cat_id';
        $table = 'tbl_purchase_cat';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function delete_pur_cat() {
        $submit = $this->_registry->Product->setData($_GET)->delete_pur_cat();
        die(empty($submit) ? "ok" : $submit);
    }

    public function multi_delete_product() {
        if (!empty($_POST['product_ids'])) {
            $msg = '';
            $products = json_decode($_POST['product_ids']);
            //            echo"<pre>";die(print_r($products));
            foreach ($products as $id) {
                $prod_arr['Product_ID'] = $id;
                $this->db->clear_error();
                $delete = $this->_registry->Product->setData($prod_arr)->deleteProduct();
                $msg = !empty($delete) ? CommonLanguage::getMessage('some_items_not_deleted') : $msg;
            }
            //            echo $msg.'==';
            die(empty($msg) ? "ok" : $msg);
        }
    }

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

    public function deleteInvoiceType() {
        $delete_printer = $this->_registry->invoice->deleteInvoiceType($_GET['invoice_type_id']);
        die(empty($delete_printer) ? "ok" : $delete_printer[0]);
    }

    public function invoice_type_list() {
        $columns = array('invoice_type_name', 'invoice_type_name_actual', /** 'Account_Name', * */ 'sort_order',
            array(
                'db' => 'show_on_menu',
                'formatter' => function( $d, $row ) {
                    return '<span class="label text-white" style="background-color:' . ($d == 0 ? 'red' : 'blue') . '" >' . CommonLanguage::getMessage($d == 0 ? 'no' : 'yes') . '</span>';
                }),
            array(
                'db' => 'invoice_type_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#invoice_type_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_invoice_type"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_invoice_type"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'invoice_type_id';
        $table = 'invoice_type_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function get_postponed_orders_total() {
        $data = $this->_registry->invoice->get_postponed_orders_total($_GET);
        die(json_encode($data));
    }

    public function PostponedOrderListByLoggedUser() {
        $cond = ' 1=1';
        if (isset($_GET['customer_supplier_id']) && $_GET['customer_supplier_id'] != '') {
            $cond .= ' and Supplier_ID = "' . $_GET['customer_supplier_id'] . '"';
        }
        if (!empty($_GET['inv_list_nb'])) {
            $cond .= ' and sale_nb = "' . $_GET['inv_list_nb'] . '"';
        }
        if (!empty($_GET['posponted_status'])) {
            $cond .= ' and postponed_status_id = "' . $_GET['posponted_status'] . '"';
        }
        if (!empty($_GET['branch_id'])) {
            $cond .= ' and branch_id = "' . $_GET['branch_id'] . '"';
        }
        if (!empty($_GET['due_date_from']) && !empty($_GET['due_date_to'])) {
            $cond .= ' and date(postponed_date_time) between  "' . $_GET['due_date_from'] . '"  and  "' . $_GET['due_date_to'] . '"';
        }
        $cond .= ' and is_actual="' . $_GET['is_actual'] . '" ';

        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and Order_Date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }
        $cond .= ' AND current_year_id = "' . $this->year_id . '" and  is_sales = 1 and is_quotation = 0 and postponed_status_id is not null';

        $columns = array('sale_nb', 'Person_Name', 'date_created',
            'postponed_date_time', 'postponed_note',
            array('db' => 'net_total', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
            array('db' => 'postponed_status_id', "formatter" => function($d, $row) {
                    $label_name = CommonLanguage::getMessage($d == 1 ? 'Request' : ($d == 2 ? 'production_line' : ($d == 3 ? 'production_done' : ($d == 4 ? 'delivered' : 'on_request'))));
                    $label_color = $d == 1 ? 'important' : ($d == 2 ? 'master' : ($d == 3 ? 'warning' : 'info'));
                    return '<span class="label label-' . $label_color . '" data-status="' . $d . '">' . $label_name . '</span>';
                }),
            array(
                'db' => 'Order_ID',
                'formatter' => function( $d, $row) {
                    $option_arr = [
                        ["title" => CommonLanguage::getMessage('posponted_status'),
                            "class" => "change_postpone_status",
                            'permission' => 'change_postpone_status',
                            "attr" => "data-status='" . $row['postponed_status_id'] . "' data-origin='order'",
                            "icon" => "fa-retweet",
                        ],
                        ["title" => CommonLanguage::getMessage('view'),
                            "class" => "view_postponed_details openFrame",
                            'attr' => "data-src='Inventory/ViewQuotationOrder/order/{$d}?is_pop=1'",
                            "icon" => "fa-eye",
                        ]
                    ];
                    $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $option_arr]);
                    return $html;
                }
            ), 'Currency_Symbol'
        );
        $key = 'Order_ID';
        $table = 'purchase_order_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function get_postponed_order_report() {
        $data = $this->_registry->invoice->setData($_GET)->get_postponed_order_report();
        //        echo"<pre>";die(print_r($data));
        $html = Forms::build_postponed_report($data);
        die($html);
    }

    public function update_order_postpone_status() {
        $update = $this->_registry->invoice->setData($_POST)->update_order_postpone_status($_POST['id'], $_POST['status']);
        die(empty($update) ? 'OK' : 'error');
    }

    public function driver_list() {
        $columns = array('driver_name',
            array('db' => 'driver_id', 'formatter' => function($d, $row) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#add_driver',
                                                "class" => "edit_driver",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_driver"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete_driver",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_driver"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'driver_id';
        $table = 'tbl_drivers';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function get_total_inv_pur_due_dates() {
        $data = $this->_registry->invoice->setData($_GET)->inv_pur_due_date_totals();
        die(json_encode($data));
    }

    public function delete_driver() {
        $submit = $this->_registry->common_inventory->setData($_GET)->delete_driver();
        die(empty($submit) ? "ok" : $submit);
    }

    public function customer_daily_report() {
        $data = $this->_registry->invoice->setData($_GET)->customer_daily_report();
        $html = Forms::build_table_html($data['html']);
        die(json_encode(['html' => $html, 'total_inv' => $data['total_inv'],
            'total_receipt' => $data['total_receipt'], 'balance' => $data['balance']]));
    }

    public function consumption_list() {
        $columns = array('consumption_id', 'Customer_Name', 'consumption_date',
            array('db' => 'consumption_auto_id',
                'formatter' => function($d, $row) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'href' => "Inventory/consumption/{$d}",
                                                "class" => "edit_consumption",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_consumption"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'consumption_auto_id';
        $table = 'consumption_list';

        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function submit_consumption() {
        $submit = $this->_registry->invoice->setData($_POST)->submit_consumption();
        die(json_encode(is_numeric($submit[0]) ? ['OK', $submit[0], $submit[1]] : $submit ));
    }

    public function submitDisplay() {
        $submit = $this->_registry->Product->setData($_POST)->submit_display();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getDisplay() {
        $data = $this->_registry->Product->get_display($_GET['display_id']);
        die(json_encode($data));
    }

    public function deleteDisplay() {
        $delete_display = $this->_registry->Product->delete_display($_GET['display_id']);
        die(empty($delete_display) ? "ok" : $delete_display[0]);
    }

    public function display_list() {
        $columns = array('display_name', 'display_blocks',
            array(
                'db' => 'display_id',
                'formatter' => function( $d, $row ) {
                    $html = Forms::action_snippet(["color" => "success",
                                "isDropDown" => true,
                                "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        'data-target' => '#display_modal',
                                        "class" => "edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_display"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "icon" => "fa-trash",
                                        "permission" => "delete_display"
                                    ],
                                    ["title" => CommonLanguage::getMessage("go_order_display"),
                                        'href' => "order_display/{$d}",
                                        'attr' => " target='_blank' ",
                                        "class" => "view",
                                        "icon" => "fa-eye"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'display_id';
        $table = 'tbl_display';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function customer_sold_items_report_ajax() {
        $data = $this->_registry->invoice->setData($_GET)->customer_sold_items_report();
        $limit = !empty($_GET['default_visible_product']) ? $_GET['default_visible_product'] : 10;
        $header_data = $this->_registry->invoice->get_cust_sold_header($limit);
        $header = Forms::customer_sold_item_report_header($header_data);
        $html = Forms::build_table_html($data);
        die(json_encode(['html' => $html, 'header' => $header]));
        //                                                                                                                                echo json_encode(array("data" => $data, "draw" => 1, "recordsFiltered" => count($data), "recordsTotal" => count($data)));
    }

    public function get_invoice_type_by_id() {
        $data = $this->_registry->invoice->get_invoice_type_by_id($_GET['entry_id']);
        die(json_encode($data));
    }

    public function monthly_sales_report_ajax() {

        $_POST['tmp__all_ids'] = array();
        $_POST['prod_val'] = array();
        $_POST['dates'] = array();
        $cond = ' ';
        $prod_cond = ' ';

        if (!empty($_POST['branch_id'])) {
            $cond .= ' AND branch_id = "' . $_POST['branch_id'] . '" ';
        }
        if (!empty($_POST['sales_man_id'])) {
            $cond .= ' AND Sales_ID = "' . $_POST['sales_man_id'] . '" ';
        }

        if (isset($_POST['users']) && !empty($_POST['users'])) {
            $cond .= ' AND Logged_ID in (' . $_POST['users'] . ')';
        }
        if (!empty($_POST['customer_id']) && is_numeric($_POST['customer_id'])) {
            $cond .= ' AND Customer_ID = "' . $_POST['customer_id'] . '" ';
            if (!empty($_POST['customer_branch_id'])) {
                $cond .= ' and customer_branch_id = "' . $_POST['customer_branch_id'] . '"';
            }
        }

        if (!empty($_POST['category_id'])) {
            $prod_cond .= ' AND Category_ID = "' . $_POST['category_id'] . '" ';
        }
        if (is_numeric($_POST['supplier_id'])) {
            $prod_cond .= ' AND main_supplier_id = "' . $_POST['supplier_id'] . '" ';
        }
        if (!empty($_POST['brand_id'])) {
            $prod_cond .= ' AND brand_id = "' . $_POST['brand_id'] . '" ';
        }
        if (!empty($_POST['customer_group_id'])) {
            $cust_ids = array();
            $query = $this->db->prepare_Stmt('select Customer_ID from tbl_customers 
                where customer_group_id = ?', [$_POST['customer_group_id']]);
            while ($row = $this->db->assoc($query))
                $cust_ids[] = $row['Customer_ID'];
            if (!empty($cust_ids))
                $cond .= ' AND Customer_ID in (' . implode(',', $cust_ids) . ') ';
            else
                $cond .= ' and 1=2 ';
        }

        if (empty($_POST['is_actual'])) {
            $cond .= ' and is_actual = 0 ';
        }
        $col_str = '';
        if (!empty($_POST['from_month']) && !empty($_POST['to_month'])) {
            $from = $_POST['from_month'];
            $to = $_POST['to_month'];
            while ($from <= $to) {
                $str_from = str_replace('-', '_', $from);
                $_POST['dates'][] = $str_from;
                $col_str .= ' 0 as `qty_' . $str_from . '`,0 as `price_' . $str_from . '`, ';
                $from = date("Y-m", strtotime("+1 month", strtotime($from)));
//                                echo $from.'==';
            }
        }
        $_POST['cond'] = $cond;
        //        echo $col_str.'<br>';
        //        echo '<pre>';
        //        die(print_r($_POST['dates']));

        $columns = array('Product_Code', 'Product_Name', 'UOM_Name');
        foreach ($_POST['dates'] as $date) {
            $columns[] = array('db' => 'qty_' . $date, 'formatter' => function($d, $row) use ($date) {
                    if (!empty($_POST['prod_val'][$row['Product_ID']][$date]))
                        return CommonFunctions::formatNumber($_POST['prod_val'][$row['Product_ID']][$date]['qty']);
                    return $d;
                });
            $columns[] = array('db' => 'price_' . $date, 'formatter' => function($d, $row) use ($date) {
                    if (!empty($_POST['prod_val'][$row['Product_ID']][$date]))
                        return CommonFunctions::formatNumber($_POST['prod_val'][$row['Product_ID']][$date]['price']);
                    return $d;
                });
        }
        $columns[] = 'Product_ID';
        $key = 'Product_ID';
        $table = '(select Product_Code,Product_Name,UOM_Name,' . $col_str . 'Product_ID 
            from  tbl_stock_products p join tbl_stock_uom u on u.UOM_ID = p.default_view_uom_id
            where 1=1 ' . $prod_cond . ') as products';
        $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'product_ftch_row']]
            , 'fetch_all_callback' => ['ft' => [$this, 'product_ftch_all']]];
        $data = DataTable::complex($_POST, $table, $key, $columns, '', null, null, $row_cb);
        echo json_encode($data);

        //        echo"<pre>";
        //        die(print_r($dates));
    }

    public function product_ftch_row(&$data, &$row) {
        $_POST['tmp__all_ids'][$row['Product_ID']] = false;
    }

    public function product_ftch_all(&$data) {
        if (empty($_POST['tmp__all_ids']))
            return true;
        $query = $this->db->query('SELECT d.Product_ID,
            sum(d.Product_Total_Price*' . ($_POST['currency_id'] == 1 ? 'i.current_rate' : 'i.second_currency_rate') . '*p.default_view_rate) as price,
            sum(d.Product_Quantity/p.default_view_rate) as qty,
            DATE_FORMAT(i.Invoice_Date,"%Y") as year,
            DATE_FORMAT(i.Invoice_Date,"%m") as month
            FROM tbl_invoice_products_details d join tbl_invoices i 
            on i.Invoice_ID_Auto = d.Invoice_ID_Auto
            join tbl_stock_products p on p.Product_ID = d.Product_ID
            where d.Product_ID in (' . implode(',', array_keys($_POST['tmp__all_ids'])) . ')  ' . $_POST['cond'] . '
            group by d.Product_ID,year(i.Invoice_Date),month(i.Invoice_Date)');
        while ($row = $this->db->assoc($query)) {
            $_POST['prod_val'][$row['Product_ID']][$row['year'] . '_' . $row['month']] = $row;
        }
        //        echo"<pre>";die(print_r($_POST['prod_val']));
    }

    public function subscription_category_list() {
        $columns = array('category_name', 'sort_order',
            array('db' => 'category_id', 'formatter' => function($d, $row) {
                    $html = Forms::action_snippet(
                                    ["color" => "primary",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                'data-target' => '#subscription_category_modal',
                                                "class" => "edit_subscription_category",
                                                "icon" => "fa-pencil",
                                                "permission" => "edit_subscription_category"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete_subscription_category",
                                                "icon" => "fa-trash",
                                                "permission" => "delete_subscription_category"
                                            ]
                    ]]);
                    return $html;
                })
        );
        $key = 'category_id';
        $table = 'tbl_subscription_category';

        //
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

    public function delete_subscription_category() {
        $submit = $this->_registry->subscriptions->setData($_GET)->delete_subscription_category();
        die(empty($submit) ? "ok" : $submit);
    }

    //
    //    public function subscription_block_list() {
    //        $columns = array('block_name',
    //                         array('db' => 'block_id', 'formatter' => function($d, $row) {
    //                             $html = Forms::action_snippet(
    //                                 ["color" => "primary",
    //                                  "isDropDown" => true,
    //                                  "data_id" => $d,
    //                                  "ActionOption" => [
    //                                      ["title" => CommonLanguage::getMessage("Edit"),
    //                                       'data-target' => '#subscription_block_modal',
    //                                       "class" => "edit_subscription_block",
    //                                       "icon" => "fa-pencil",
    //                                       "permission" => "edit_subscription_block"
    //                                      ],
    //                                      ["title" => CommonLanguage::getMessage("delete"),
    //                                       "class" => "delete_subscription_block",
    //                                       "icon" => "fa-trash",
    //                                       "permission" => "delete_subscription_block"
    //                                      ]
    //                                  ]]);
    //                             return $html;
    //                         })
    //                        );
    //        $key = 'block_id';
    //        $table = 'tbl_subscription_block';
    //
    //        //
    //        $data = DataTable::complex($_GET, $table, $key, $columns);
    //        echo json_encode($data);
    //    }

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

    public function delete_subscription_block() {
        $submit = $this->_registry->subscriptions->setData($_GET)->delete_subscription_block();
        die(empty($submit) ? "ok" : $submit);
    }

    public function get_subscription_block_tree() {
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        if ($cmd == "fetch") {
            $RET = $id == 0 ? $this->_registry->subscriptions->get_subscription_block_tree() : $this->_registry->subscriptions->get_subscription_block_tree($id);
            for ($x = 0; $x < count($RET); $x++) {
                $RET2 = $this->_registry->subscriptions->get_subscription_block_tree(intval($RET[$x]["block_id"]));
                if (count($RET2) > 0)
                    $RET[$x]["isLazy"] = true;
                $RET[$x]["key"] = $RET[$x]["block_id"];
            }
            echo json_encode($RET);
        }
    }

    public function category_fees_ajax() {
        $data = $this->_registry->subscriptions->setData($_GET)->category_fees_report();
        $body = Forms::build_table_html($data['body']);
        $footer = $data['footer'];
        
        die(json_encode(['body' => $body, 'footer' => $footer]));
    }

    public function subscription_block_report() {
        $data = $this->_registry->subscriptions->setData($_GET)->subscription_block_report();
        $body = Forms::build_table_html($data['data']);
        die(json_encode([$body, $data]));
    }

    public function import_customers_excel() {
        $Ret = $this->_registry->customer->setData($_POST)->import_customers_excel();
        die(json_encode($Ret));
    }
    public function import_supplier_excel() {
        $Ret = $this->_registry->customer->setData($_POST)->import_supplier_excel();
        die(json_encode($Ret));
    }

    public function get_max_product_code() {
        $max_code = $this->_registry->Product->getMaxProductCode();
        die(json_encode($max_code));
    }

    public function monthly_sales_graph() {
        $data = $this->_registry->invoice->setData($_POST)->monthly_sales_graph();
        die(json_encode($data));
    }

    public function monthly_year_sales_graph() {
        $data = $this->_registry->invoice->setData($_POST)->monthly_year_sales_graph();
        die(json_encode($data));
    }

    public function monthly_year_sales_list() {
        $data = $this->_registry->invoice->setData($_POST)->monthly_year_sales_list();
        die(json_encode($data));
    }

    public function monthly_year_sales_list_header() {
        $data = $this->_registry->invoice->setData($_POST)->monthly_year_products_sales_list();
        die(json_encode($data));
    }

    public function monthly_year_products_sales_list() {

        $cond = ' 1=1 ';


        if (!empty($_GET['start_date']) && !empty($_GET['end_date']))
            $cond .= ' and  month_year between "' . $_GET['start_date'] . '" and  "' . $_GET['end_date'] . '" ';
        if (!empty($_GET['currency_id']))
            $currency_id = ($_GET['currency_id'] == 1 ? smc_session()['local_currency'] : smc_session()['second_currency']['id']);
        if (isset($_GET['is_actual']))
            $cond .= '  and  is_actual = "' . $_GET['is_actual'] . '" ';


        $columns = array(
            'prd_name', array('db' => 'sum(total_qty)', 'formatter' => function($d, $row) {
                    return CommonFunctions::formatNumber($d);
                }), array('db' => 'sum(net_total)', 'formatter' => function($d, $row) {
                    return CommonFunctions::formatNumber($d);
                }), 'month_year'
        );

        $group = ' GROUP by month_year,Product_ID ';

        $table = ' (select d.Product_ID,is_actual,concat(Product_Code," - ",Product_Name) as prd_name,UOM_Name ,
                DATE_FORMAT(Invoice_Date, "%Y-%m") as month_year,
                (d.Product_Quantity) as total_qty ,
                (if(Invoice_Currency = "' . $currency_id . '" ,(Product_Total_Price),(Product_Total_Price)*second_currency_rate)) as net_total 
                from  tbl_invoice_products_details d      
                INNER JOIN
                      tbl_invoices i
                on i.Invoice_ID_Auto = d.Invoice_ID_Auto
                INNER JOIN
                      tbl_stock_products p
                on p.Product_ID = d.Product_ID
                INNER JOIN
                      tbl_stock_uom u
                on p.Uom_ID = u.Uom_ID ) as dump ';
        $key = '(@cnt := @cnt + 1)';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, $group, ['is_debug' => true]);

        echo json_encode($data);
    }

    public function forcast_sales_report_ajax() {
        $data = $this->_registry->invoice->forcast_sales_report($_GET['from_month'], $_GET['to_month'], $_GET['supplier_id'], $_GET['category_id']);
//        echo"<pre>";die(print_r($data['orders']));
        $html = Forms::build_table_html($data['data']);
        die(json_encode([$html, $data['orders']]));
    }
    public function check_customer_phone() {
        if(smc_session()['default_setting']['unique_customer_phone_number'] == 1 ){
            $data = $this->_registry->customer->check_customer_phone($_GET['Customer_Mobile']);
            die(json_encode(empty($data['Customer_Name'])? ['error' => 'error']:$data));    
        }else{
            die(json_encode(['error' => 'error']));
        }
    }
    public function check_supplier_phone() {
        if(smc_session()['default_setting']['unique_supplier_phone_number'] == 1 ){
            $data = $this->_registry->vendor->check_supplier_phone($_GET['Supplier_Mobile']);
            die(json_encode(empty($data['Supplier_Name'])? ['error' => 'error']:$data));
        }else{
            die(json_encode(['error' => 'error']));
        }
    }

    public function addCustomerScertificatee() {
        $insert = $this->_registry->Product->setData($_POST)->addCustomerScertificatee();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function updateCustomerScertificatee() {
        $update = $this->_registry->Product->setData($_POST)->updateCustomerScertificatee();
        die(empty($update) ? 'OK' : 'error');
    }
    public function CustomersCertificateList() {
        $cond =' 1=1 ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and end_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }

        
        $columns = array(
            array('db' => 'Customer_Name', 'dt' => 0),
            array('db' => 'start_date', 'dt' => 1),
            array('db' => 'end_date', 'dt' => 2),
            array('db' => 'certificate_info', 'dt' => 3),
            array('db' => 'id', 'dt' => 4, "formatter" => function ($d, $row) {
                $today = date('Y-m-d');
                 if ($today < $row['start_date']) {
                    return '<span class="  label future-cert " data-status="' . $d . '" >Future</span>';
                } else if ($today <= $row['start_date'] && $row['end_date'] >= $today) {
                    return '<span class="  label available-cert " data-status="' . $d . '" >Available</span>';
                }else if ( $row['end_date'] >= $today) {
                    return '<span class="  label available-cert " data-status="' . $d . '" >Available</span>';
                }   else {
                    return '<span class="  label expiry-cert " data-status="' . $d . '" >Expiry</span>';
                }
            }),
            array('db' => 'id', 'dt' => 5, "formatter" => function($d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'id';
        $table = 'customerscertificateview';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }
    public function get_customers_certificate() {
        $data = $this->_registry->Product->get_customers_certificate($_GET['id']);
        die(json_encode($data));
    }
    public function deleteCustomersCertificate() {
        $delete = $this->_registry->Product->setData($_POST)->deleteCustomersCertificate();
        die(empty($delete) ? 'OK' : 'error');
    }
    public function addCustomerContra() {
        $submit = Product::addCustomerContra($_POST);
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));

    }
    public function CustomersContraList() {
        $cond =' 1=1 ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and end_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }

        
        $columns = array(
            array('db' => 'Customer_Name', 'dt' => 0),
            array('db' => 'Product_Name', 'dt' => 1),
            array('db' => 'start_date', 'dt' => 2),
            array('db' => 'end_date', 'dt' => 3),
            array('db' => 'contra_info', 'dt' => 4),
            array('db' => 'id', 'dt' => 5, "formatter" => function ($d, $row) {
                $today = date('Y-m-d');
                 if ($today < $row['start_date']) {
                    return '<span class="  label future-cert " data-status="' . $d . '" >Future</span>';
                } else if ($today <= $row['start_date'] && $row['end_date'] >= $today) {
                    return '<span class="  label available-cert " data-status="' . $d . '" >Available</span>';
                }else if ( $row['end_date'] >= $today) {
                    return '<span class="  label available-cert " data-status="' . $d . '" >Available</span>';
                }    else {
                    return '<span class="  label expiry-cert " data-status="' . $d . '" >Expiry</span>';
                }
            }),
            array('db' => 'file_name', 'dt' => 6, "formatter" => function ($d, $row) {
                return   "<a target='_blank' style='color: black;' href='".SITE_LINK."/uploads/customer_contra/".$d."'><i class='fa fa-file fa-2x'></i></a>";
            }),
            array('db' => 'id', 'dt' => 7, "formatter" => function($d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'id';
        $table = 'customerscontraview';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function get_customers_contra() {
        $data = $this->_registry->Product->get_customers_contra($_GET['id']);
        die(json_encode($data));
    }
    
    public function updateCustomerContra() {
        $submit = Product::updateCustomerContra($_POST);
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));

    }

    public function deleteCustomersContra() {
        $delete = $this->_registry->Product->setData($_POST)->deleteCustomersContra();
        die(empty($delete) ? 'OK' : 'error');
    }
    public function last_invoice_number() {
        $data =  $this->_registry->invoice->last_invoice_number();
        die(json_encode($data));
    }
    public function daily_sales_ajax() {
        $cond = '1 = 1 ';
         if(isset($_GET['from_date']) && isset($_GET['to_date'])){
            $cond .= ' AND Invoice_Date between "' . $_GET['from_date'] . '" and"' . $_GET['to_date'] . '" ';

        }
        $cond .= ' AND current_year_id = "' . $this->year_id . '" and is_committed = 1 and (Invoice_Net_Total*current_rate) > 0';
        $columns = array(
            array('db' => 'sum(Invoice_Net_Total*current_rate)', 'dt' => 0, "formatter" => function ($d, $row) {
                return CommonFunctions::formatNumber($d).' '.smc_session()['local_currency_symbol'] ;
            }),

            array('db' => 'Invoice_Date', 'dt' => 1)
        );
        $key = 'Invoice_Date';
        $table = '(SELECT Invoice_Net_Total ,current_rate, Invoice_Date ,current_year_id , is_committed   FROM invoice_list_main) as inv_table';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond,null ,'group by Invoice_Date');
        echo json_encode($data);
    }
    public function get_total_sales_invoices2() {
        $data = $this->_registry->invoice->setData($_GET)->get_total_sales_invoices2( $_GET['from_date'], $_GET['to_date']);
        die(json_encode($data));
    }

    public function collected_points_list() {

        $cond = '1=1';
        if (isset($_GET['from_date']) && isset($_GET['to_date'])) {
            $FromDate = $_GET['from_date'];
            $ToDate = $_GET['to_date'];
            $cond .= ' and date_collected_point >= "' . $FromDate . '" AND date_collected_point <= "' . $ToDate . '"';
        }
        if (is_numeric($_GET['customer_id'])) {
            $cond .= ' AND ID = "' . $_GET['customer_id'] . '"';
        }

        $columns = array('Name','Customer_Mobile','collected_points','date_collected_point');

        $key = 'ID';
        $table = 'customer_list';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }
    
    public function description_point_list() {
        $columns = array(
            array('db' => 'first_point', 'dt' => 0),
            array('db' => 'last_point', 'dt' => 1),
            array('db' => 'description', 'dt' => 2),
            array('db' => 'id', 'dt' => 3, "formatter" => function($d, $row) {
                    $html = Forms::action_snippet(["color" => "primary", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [["title" => CommonLanguage::getMessage("delete"),
                                "class" => "Delete",
                                "icon" => "fa-trash",
                                "permission" => "delete_description_for_points"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "Edit",
                                        "icon" => "fa-pencil",
                                        "permission" => "edit_description_for_points"
                                    ]
                    ]]);
                    return $html;
                })
        );
        $key = 'id';
        $table = 'description_for_point';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }
    
    public function add_descriptoin_points() {
        $submit = Product::add_descriptoin_points($_POST);
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

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

    public function delete_description_points() {
        $delete = $this->_registry->Product->setData($_POST)->delete_description_points();
        die(empty($delete) ? 'OK' : 'error');
    }

    public function update_description_points() {
        $submit = Product::update_description_points($_POST);
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function ajax_sync_website() {
        $data = $this->_registry->Product->ajax_sync_website($_POST['empty_type']);
        die(empty($data) ? 'ok' : json_encode($data));
    }

    
}
