<?php

class POSAjax extends mainController {

    private $permissions;

    public function __construct() {

        parent::__construct();
        $this->year_id = Session::getCurrentYearID();
        $this->permissions = new Permissions(Session::getUserID());
        $this->db = DBConnectorFactory::loadDriver();
        $this->load->model('pos');
    }

    public function landing() {
        self::POSAjax();
    }

    // used function
    public function UserAccAccounts() {
        $columns = array(
            array('db' => 'User_Name', 'dt' => 0),
            array('db' => 'Sales_Name', 'dt' => 1),
            array('db' => 'Cash_Name', 'dt' => 2),
            array('db' => 'WD_Name', 'dt' => 3),
            array('db' => 'Deposit_Name', 'dt' => 4)
        );
        $key = 'User_Account_ID';
        $table = 'user_accounting_accounts_name';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function getTotalDelivery() {
        $RET = $this->_registry->Invoice->setData($_GET)->getTotalDelivery();
        die($RET);
    }

    public function getSalesRetreiveList() {
        $cond = ' 1=1 ';
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '" ';
        $cond .= ' and Invoice_Status = 3  and Is_Closed <> 1 and table_id = 0 ';
        $columns = array('ID',
                         array(
                             'db' => 'date_created',
                             'dt' => 1,
                             'formatter' => function( $d, $row) {
                                 if ($row['invoice_type'] == 0)
                                     return $d;
                                 else {
                                     $current_delivery_time = strtotime($row['Delivery_Time']);
                                     return date('Y-m-d', $current_delivery_time) == date('Y-m-d') ? date('g:i a', $current_delivery_time) : date("Y-m-d g:i a", $current_delivery_time);
                                 }
                             }
                         ), 'Name', 'pos_customer_address', 'customer_mobile', 'Invoice_Description');
        $pos_fields_hide = smc_session()['default_setting']['pos_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['pos_fields_to_hide']) : [];

        if (!in_array(5, $pos_fields_hide)) {
            $columns[] = 'driver_name';
        }
        $columns[] = array(
            'db' => 'invoice_type',
            'formatter' => function( $d, $row) {
                if ($row['is_app'] == 0) {
                    $Statuses = ['0' => '', '1' => CommonLanguage::getMessage('Invoice') . "#label-info", '3' => CommonLanguage::getMessage('park') . "#label-important",
                                 '2' => CommonLanguage::getMessage('delivery') . "#label-info",
                                 '6' => CommonLanguage::getMessage('take_away') . "#label-warning"];
                    return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
                } else {
                    return '<span class="label label-success" data-status="' . $d . '">' . CommonLanguage::getMessage('online') . '</span>';
                }
            }
        );
        $columns[] = array(
            'db' => 'ID_Auto',
            'formatter' => function( $d, $row) {
                $remaining_actions = [];
                $main_actions = [
                    ["title" => CommonLanguage::getMessage('print_kitchen'),
                     "class" => "print_delivery_order",
                     "icon" => "fa-print",
                     "permission" => "print_kitchen"
                    ],
                    ["title" => CommonLanguage::getMessage('cash'),
                     "class" => "cash_cash_no_print_invoice",
                     "icon" => "fa-money",
                     "attr" => "data-print='1'",
                     "permission" => "cash_generate_invoice"
                    ],
                    ["title" => CommonLanguage::getMessage('cash_without_print'),
                     "class" => "cash_cash_no_print_invoice",
                     "icon" => "fa-money",
                     "attr" => "data-print='0'",
                     "permission" => "cash_generate_invoice"
                    ],
                    ["title" => CommonLanguage::getMessage('view'),
                     "class" => "view_order openFrame",
                     "icon" => "fa-eye",
                     "attr" => "data-src='POSAjax/viewInvoicePOS?Invoice_ID_Auto={$d}'"
                    ]
                ];
                if ($row['is_app'] == 1) {
                    $remaining_actions = [
                        ["title" => CommonLanguage::getMessage('generate_invoice'),
                         "class" => "generate_invoice",
                         "icon" => "fa-dollar"
                        ]];
                } else {
                    $remaining_actions = [
                        ["title" => CommonLanguage::getMessage('print'),
                         "class" => "PrintInvoice",
                         "icon" => "fa-print",
                        ]];
                    if ($row['is_branch_transfer'] == 0 && $row['invoice_app_id'] == 0 &&
                        (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || $row['is_main_transfer'] == 0) && empty($row['reason_id'])) {
                        $remaining_actions[] = ["title" => CommonLanguage::getMessage('delete'),
                                                "class" => "DeleteInvoice",
                                                "permission" => "DeleteInvoice",
                                                "icon" => "fa-trash",
                                               ];
                        $remaining_actions[] = ["title" => CommonLanguage::getMessage('retreive'),
                                                "class" => "get_retrieved_data",
                                                "permission" => "get_retrieved_data",
                                                "icon" => "fa-download",
                                               ];
                    }
                }
                if (empty($row['reason_id'])) {
                    $remaining_actions[] = ["title" => CommonLanguage::getMessage('void'),
                                            "class" => "void_current_invoice",
                                            "permission" => "void_invoice",
                                            "attr" => "data-origin='list' data-invoice-id='{$d}'",
                                            "data-target" => "#VoidReasonModal",
                                            "icon" => "fa-retweet"
                                           ];
                }

                $actions = array_merge($main_actions, $remaining_actions);

                $html = Forms::action_snippet(["color" => " btn-info",
                                               "data_id" => $d,
                                               "isDropDown" => true,
                                               "ActionOption" => $actions
                                              ]);
                return $html;
            }
        );
        $columns = array_merge($columns, array('Delivery_Time', 'is_app', 'is_branch_transfer', 'invoice_app_id', 'is_main_transfer', 'invoice_type', 'reason_id'));

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

        echo json_encode($data);
    }

    // used function
    public function assignUserAccounts() {
        $insert = $this->_registry->user->setData($_POST)->setAccountsToUser();
        die(empty($insert) ? 'OK' : 'error');
    }

    //    // used function 
    //    public function ReturnProductUOMCon() {
    //        $data = $this->_registry->material->getUOMByProductID($_GET['pid'], $_GET['uid']);
    //        die(json_encode($data));
    //    }
    //used function
    public function ajaxCustomer() {
        if (!isset($_GET["term"]))
            die();
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $class = isset($_GET["ClassID"]) ? $_GET["ClassID"] : smc_session()['pricing_class_id'];

        $RET = array();
        if ($cmd == "") {
            $customer = new Customer();
            //            $Balance = new AccountingDashboard();

            $ALL = $customer->view(null, ' AND c.Customer_Name like "%' . smc_escape($_GET["term"]) . '%" ');
            //            for ($x = 0; $x < count($ALL); $x++) {
            //                if (strpos(strtolower($ALL[$x]["Customer_Name"]), strtolower($_GET["term"])) !== false || strpos(strtolower($ALL[$x]["Customer_Mobile"]), strtolower($_GET["term"])) !== false) {
            //                    $bal = $Balance->returnBalance('Customer', $ALL[$x]["Account_Code"]);
            //                    if (count($bal) == 0)
            //                        $val = 0;
            //                    else
            //                        $val = $bal[0]['Balance'];
            //                    $ALL[$x]["balance"] = $val;
            //                    array_push($RET, $ALL[$x]);
            //                    $val = 0;
            //                    $bal = array();
            //                }
            //            }
        }
        //        else if ($cmd == 1 || $cmd == 2) {
        //
        //            $Products = new Product();
        //            $currency = new Currency();
        //            $ALL = $Products->getProductsForCustomer($class);
        //
        //            for ($x = 0; $x < count($ALL); $x++) {
        //                if (strpos(strtolower($ALL[$x]["Code"]), strtolower($_GET["term"])) !== false && $cmd == 1) {
        //                    $last_cost = $Products->viewLastProductCost($ALL[$x]["ID"]);
        //                    $ALL[$x]['LAST_COST'] = $last_cost;
        //                    array_push($RET, $ALL[$x]);
        //                } else if (strpos(strtolower($ALL[$x]["Name"]), strtolower($_GET["term"])) !== false && $cmd == 2) {
        //                    array_push($RET, $ALL[$x]);
        //                }
        //            }
        //            //                print_r($RET);
        //            for ($x = 0; $x < count($RET); $x++) {
        //                $CurrencyID = $RET[$x]["Currency_ID"];
        //                $CurrencyCode = $currency->getCurrencyCodeByID($CurrencyID);
        //                $CurrencySymbol = $currency->viewCurrencySymbol($CurrencyID);
        //                $PrimaryCurrency = array($CurrencyID, $CurrencySymbol, $CurrencyCode);
        //                $RET[$x]["Currency_ID"] = $PrimaryCurrency;
        //            }
        //        }

        echo json_encode($ALL);
    }

    //used function
    public function getCategory() {

        $ID = isset($_GET["id"]) ? floatval($_GET["id"]) : 0;
        $Customer_ID = isset($_GET["Customerid"]) ? floatval($_GET["Customerid"]) : 0;
        $class_id = isset($_GET["class_id"]) ? floatval($_GET["class_id"]) : smc_session()['pricing_class_id'];
        $type = isset($_GET["type"]) ? $_GET["type"] : null;
        $categories = $this->_registry->product->getProductsCat($ID, 1);
        if ($categories) {
            for ($x = 0; $x < count($categories); $x++) {
                $Cat = $categories[$x];
                if (!isset($Cat[3]) || $Cat[3] != 'Product') {  //check if cat
                    $SubC = ((count($this->_registry->product->getProductsCat($Cat[0], 1)) > 0) || (count($this->_registry->product->getProduct($Cat[0], 1)) > 0));
                    $categories[$x][2] = $SubC;
                }
            }
        }
        $Products = $this->_registry->product->getProductsForCustomerByClass($ID, $Customer_ID, $class_id, $type);
        //                              echo"<pre>";die(print_r($Products));
        if (count($Products) > 0) {
            if (!$categories)
                $categories = Array();
            for ($x = 0; $x < count($Products); $x++) {
                if ($Products[$x]['product_view'] == 'Product') {
                    $CurrencyID = $Products[$x]['Currency_ID'];
                    $CurrencyCode = $this->_registry->currency->getCurrencyCodeByID($CurrencyID);
                    $CurrencySymbol = $this->_registry->currency->viewCurrencySymbol($CurrencyID);
                    $Thumb = file_exists(upload_path . 'products_photos/' . $Products[$x]['ID'] . '.jpg');
                    //echo 'uploads/products_photos/' . $Products[$x]['ID'] . '.jpg';exit;
                    /**
                                     * @added: producted quantity at the end of the array: $Products[$x][3])
                                     * @reason: for valiation
                                     *
                                     * the array below holds the data for each product within categories as mentioned below:
                                     * Product ID, Product Name, Product, Product Price, 0, Thumb dir,
                                     * array[Currency ID, Currency Symbol], Product Code, Product Stock Quantity
                                     */
                    //                        $Products[$x]['Product_UOM'] = str_replace(",","/",$Products[$x]['Product_UOM']);
                    //                        echo $Products[$x]['Product_UOM'];

                    array_push($categories, Array($Products[$x]['ID'],
                                                  $Products[$x]['Name'],
                                                  $Products[$x]['Code'],
                                                  $Products[$x]['product_view'],
                                                  $Products[$x]['Price'],
                                                  $Products[$x]['disc'],
                                                  $Thumb,
                                                  array($CurrencyID, $CurrencySymbol),
                                                  $Products[$x]['Code'],
                                                  $Products[$x]['Quantity'],
                                                  $Products[$x]['VAT'],
                                                  $Products[$x]['UOM_ID'],
                                                  $Products[$x]['Product_UOM'],
                                                  $Products[$x]['vat_percent'],
                                                  $Products[$x]['last_cost'],
                                                  $Products[$x]['Bar_Code'],
                                                  $Products[$x]['Product_Limit_Discount'],
                                                  $Products[$x]['is_tax'],
                                                  $Products[$x]['product_color'],
                                                  $Products[$x]['last_price'],
                                                  $Products[$x]['ttc_price'],
                                                  $Products[$x]['is_expiry'],
                                                  $Products[$x]['force_change_price'],
                                                  $Products[$x]['Category_ID'],
                                                  $Products[$x]['duration_reservation'],
                                                  $Products[$x]['tax_amount'],
                                                  $Products[$x]['is_lot'],
                                                  $Products[$x]['is_serial'],
                                                  $Products[$x]['uom_conv'],
                                                  $Products[$x]['is_service'],
                                                  'vat2_percent' => $Products[$x]['vat2_percent'],
                                                  'has_optional' => $Products[$x]['has_optional'],
                                                  'recipe_qty' => $Products[$x]['recipe_qty'],
                                                  'is_pos_disabled' => $Products[$x]['is_pos_disabled'],
                                                 ));
                } else {
                    array_push($categories, array('', '', '', $Products[$x]['product_view']));
                }
            }
        }
        $J = json_encode($categories);
        echo "GotoCateg($ID," . ($J ? $J : "null") . ")";
    }

    public function getProduct() {

        $ID = isset($_GET["id"]) ? floatval($_GET["id"]) : 0;

        $class_id = isset($_GET["class_id"]) ? floatval($_GET["class_id"]) : smc_session()['pricing_class_id'];
        $Products = $this->_registry->product->getProductsForCustomers($ID, $class_id, $_GET['customer_id'], $_GET['uom_id']);
        //        echo"<pre>";die(print_r($Products));
        $categories = $this->_registry->product->getProductsCat($Products[0]['Category_ID'], 1);
        if (count($Products) > 0) {
            if (!$categories)
                $categories = Array();
            for ($x = 0; $x < count($Products); $x++) {
                $CurrencyID = $Products[$x]['Currency_ID'];
                $CurrencyCode = $this->_registry->currency->getCurrencyCodeByID($CurrencyID);
                $CurrencySymbol = $this->_registry->currency->viewCurrencySymbol($CurrencyID);
                $Thumb = file_exists(upload_path . 'products_photos/' . $Products[$x]['ID'] . '.jpg');
                /**
                                 * @edited by: Assaad
                                 * @added: producted quantity at the end of the array: $Products[$x][3])
                                 * @reason: for valiation
                                 *
                                 * the array below holds the data for each product within categories as mentioned below:
                                 * Product ID, Product Name, Product, Product Price, 0, Thumb dir,
                                 * array[Currency ID, Currency Symbol], Product Code, Product Stock Quantity
                                 */
                //                        $Products[$x]['Product_UOM'] = str_replace(",","/",$Products[$x]['Product_UOM']);
                //                        echo $Products[$x]['Product_UOM'];
                array_push($categories, Array($Products[$x]['ID'],
                                              $Products[$x]['Name'],
                                              $Products[$x]['Code'],
                                              "Product",
                                              $Products[$x]['Price'],
                                              $Products[$x]['disc'],
                                              $Thumb,
                                              array($CurrencyID, $CurrencySymbol),
                                              $Products[$x]['Code'],
                                              $Products[$x]['Quantity'],
                                              $Products[$x]['VAT'],
                                              $Products[$x]['UOM_ID'],
                                              $Products[$x]['Product_UOM'],
                                              $Products[$x]['vat_percent'],
                                              $Products[$x]['last_cost'],
                                              $Products[$x]['Bar_Code'],
                                              $Products[$x]['Product_Limit_Discount'],
                                              $Products[$x]['is_tax'],
                                              $Products[$x]['product_color'],
                                              $Products[$x]['last_price'],
                                              $Products[$x]['ttc_price'],
                                              $Products[$x]['is_expiry'],
                                              $Products[$x]['force_change_price'],
                                              $Products[$x]['Category_ID'],
                                              $Products[$x]['duration_reservation'],
                                              $Products[$x]['tax_amount'],
                                              $Products[$x]['is_lot'],
                                              $Products[$x]['is_serial'],
                                              $Products[$x]['uom_conv'],
                                              $Products[$x]['is_service'],
                                              'vat2_percent' => $Products[$x]['vat2_percent'],
                                              'has_optional' => $Products[$x]['has_optional'],
                                              'recipe_qty' => $Products[$x]['recipe_qty'],
                                              'is_pos_disabled' => $Products[$x]['is_pos_disabled']
                                             ));
            }
        }
        for ($x = 0; $x < count($categories); $x++) {
            $Cat = $categories[$x];
            if (count($Cat) == 2) {//check if cat
                $SubC = ((count($this->_registry->product->getProductsCat($Cat[0], 1)) > 0) || (count($this->_registry->product->getProduct($Cat[0], 1)) > 0));
                $Cat = array($Cat[0], $Cat[1], $SubC);
                $categories[$x] = $Cat;
            }
        }
        $J = json_encode($categories);
        echo "GotoCateg($ID," . ($J ? $J : "null") . ")";
    }

    //used function
    public function ajaxInvoice() {
        $type_id = $_POST['type_id'];
        $new_table_id = $_POST['new_table_id'];
        $print_flag = 0;
        $time_now = date('Y-m-d H:i');

        if ($_POST['is_transfer'] == 1) {
            $_POST['is_confirmed'] = 1;
            $_POST['Delivery_Date'] = $_POST['Request_Date'] = date('Y-m-d');
            $_POST[0] = smc_session()['user_logged_id'];
            $_POST['Products'] = $_POST['products'];
            $insert = $this->_registry->depot->setdata($_POST)->createRequest();
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $print_flag, $time_now] : ['error',$insert] ));
        }
        if ($_POST['is_order'] == 1) {
            $_POST['Depot_ID'] = (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']);
            //            $_POST['is_actual'] = 
            $_POST['is_quotation'] = 0;
            $_POST['IsSales'] = 1;
            $_POST['Invoice_Date'] = $_POST['Invoice_Due_Date'] = date('Y-m-d');
            $_POST['discount_amount'] = $_POST['Discount_Amount'];
            $_POST['Products'] = $_POST['products'];
            $insert = $this->_registry->purchase->setdata($_POST)->addPurchaseOrder();
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0], $insert[1]] : ['error',$insert] ));
        }
        if ($new_table_id == 0) {
            if ($_POST['is_return'] == 1) { //sales invoice
                if (date('Y-m-d H:i') >= ($_POST['Delivery_Date'] . ' ' . $_POST['Delivery_Time']) && smc_session()['default_setting']['autoprint_past_delivery'] && ($_POST['is_delivery'] == 1 || $_POST['is_takeaway'] == 1) && smc_session()['default_setting']['autoprint_past_delivery_with_invoice'])
                    $print_flag = 1;
                if ($_POST['is_edited_invoice'] == 1) {
                    if ($type_id == 4) {
                        $RET = $this->_registry->restaurantpos->setdata($_POST)->splitInvoice();
                        die(json_encode(is_array($RET) ? ['error'] : ['OK', $RET]));
                    }
                    $RET = $this->_registry->Invoice->setdata($_POST)->editInvoice();
                } else {
                    $RET = $this->_registry->Invoice->setdata($_POST)->createPOS(false);
                }
                die(json_encode(is_array($RET) ? ['error', $RET] : ['OK', $RET, $print_flag, $time_now]));
            } else if ($_POST['is_return'] == 2) {  //return invoice
                
                if ($_POST['is_edited_invoice'] == 1) {
                    $_POST['Currency_ID'] = $_POST['Invoice_Currency'];
                    $_POST['Is_Customer_Invoice'] = 1;
                    $_POST['Return_ID'] = $_POST['Invoice_ID_Auto'];
                    $_POST['Is_Actual'] = $_POST['is_actual'];
                    $_POST['Depot_ID'] = smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'];
                    $_POST['Card_Amount'] = 0;
                    $_POST['Card_Account'] = '';
                    $_POST['Cash_Amount'] = $_POST['cash_amount'] + $_POST['other_amount'];
                    $_POST['Cash_Account'] = smc_session()['user_accounts']['cash_account_id'];
                    $_POST['Check_Amount'] = 0;
                    $_POST['Check_Account'] = '';
                    $_POST['Return_Invice_Total'] = $_POST['Invoice_Net_Total'];
                    $_POST['discount_amount'] = $_POST['Discount_Amount'];
                    $_POST['discount_percent'] = $_POST['Invoice_Discount'];
                    $_POST['Return_Invoice_Note'] = $_POST['Invoice_Description'];
                    $_POST['Return_Invoice_Total'] = $_POST['Invoice_Sub_Total'];
                    $_POST['Person_ID'] = $_POST['Customer_ID'];
                    $_POST['Account_Code'] = smc_session()['user_accounts']['sales_account_id'];
                    $_POST['job_id'] = 0;
                    $_POST['Old_Depot_ID'] = smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'];
                    $_POST['Products'] = $_POST['products'];
                    $customer_account = $this->_registry->Invoice->getCustomerAccount($_POST['Customer_ID']);
                    $_POST['Person_Account'] = $customer_account['Account_ID'];
                    $RET = $this->_registry->return->setData($_POST)->editReturnNoInvoice();
                } else {
                    $RET = $this->_registry->Invoice->setdata($_POST)->posReturn();
                }
                die(json_encode(is_array($RET) ? ['error',$RET] : ['OK', $RET, $print_flag, $time_now]));
            } else {    //exchange
                if ($_POST['is_edited_invoice'] == 1) {
                    $update = $this->_registry->Invoice->setdata($_POST)->edit_exchange($_POST);
                    die(json_encode(!is_numeric($update[0]) ? ['error',$update] : ['OK', $update, $print_flag, $time_now]));
                } else {
                    $exchange = $this->_registry->Invoice->setdata($_POST)->add_exchange($_POST);
                    die(json_encode(!is_numeric($exchange[0]) ? ['error',$exchange] : ['OK', $exchange, $print_flag, $time_now]));
                }
            }
        } else {
            if ($type_id == 1) {
                $RET = $this->_registry->restaurantpos->setdata($_POST)->transferTable();
            } else if ($type_id == 2) {
                $RET = $this->_registry->restaurantpos->setdata($_POST)->transferItems();
            } else if ($type_id == 3) {
                $RET = $this->_registry->restaurantpos->setdata($_POST)->mergeTables();
            }
            die(json_encode(empty($RET) ? ['OK'] : ['error',$RET]));
        }
    }

    //used function
    public function printInvoiceNoSave() {
        $data_arr = array('main' => array(), 'Details' => array(), 'DetailsLinked' => array());
        $inv_sub_ttl_ttc = 0;
        $inv_disc_percentage = $_POST['Invoice_Discount'];
        if (!empty($_POST['products'])) {
            foreach ($_POST['products'] as $item_row) {
                $item_row['link_product_class'] = 'hidden';
                $item_row['Product_Net_Price_TTC'] = $item_row['Net_Price'] * (1 + ($item_row['vat_percent'] / 100)) * (1 + ($item_row['vat2_percent'] / 100));
                $item_row['Product_Net_Price_After_Disc'] = $item_row['Net_Price'] * (1 - ($item_row['Product_Disc'] / 100));
                $item_row['Product_Net_Price_After_Disc_TTC'] = $item_row['Product_Net_Price_After_Disc'] * (1 + ($item_row['vat_percent'] / 100)) * (1 + ($item_row['vat2_percent'] / 100));
                //                echo $item_row['Product_Net_Price_After_Disc'].'==='.;
                $item_row['Product_Total_Price_After_Disc_TTC'] = $item_row['Product_Net_Price_After_Disc_TTC'] * $item_row['Product_Quantity'];
                $data_arr['Details'][] = ['link_product_class' => $item_row['link_product_class'],
                                          'Product_Name' => $item_row['product_name'],
                                          'product_description' => !empty($item_row['product_description']) ? $item_row['product_description'] : '',
                                          'Item_Quantity_Current' => $item_row['Product_Quantity'],
                                          'Product_Net_Price_TTC' => $item_row['Product_Net_Price_TTC'],
                                          'Product_Discount' => $item_row['Product_Disc'],
                                          'Product_Total_Price_After_Disc_TTC' => $item_row['Product_Total_Price_After_Disc_TTC'],
                                          'tags' => !empty($item_row['tags']) ? $item_row['tags'] : '',
                                         ];
                $inv_sub_ttl_ttc += $item_row['Product_Total_Price_After_Disc_TTC'];
            }
        }
        $net_total = $_POST['Invoice_Net_Total'];
        $shipping_amount = $_POST['Invoice_Shipping'];
        $grand_total = $net_total + $shipping_amount;
        $data_arr['main'] = ['Invoice_Sub_Total_ttc' => CommonFunctions::formatNumber($inv_sub_ttl_ttc, 2),
                             'discount_amount_ttc' => CommonFunctions::formatNumber(($inv_sub_ttl_ttc * ($inv_disc_percentage / 100)), 2),
                             'Invoice_VAT' => CommonFunctions::formatNumber($_POST['Invoice_VAT']),
                             'vat1_total' => CommonFunctions::formatNumber($_POST['vat1_total']),
                             'vat2_total' => CommonFunctions::formatNumber($_POST['vat2_total']),
                             'grand_total' => CommonFunctions::formatNumber($grand_total)
                            ];
        $data_arr['main']['Currency_Symbol'] = CurrencyFactory::getCurrencySymbol($_POST['Invoice_Currency']);
        
        $print_template = 'pos_quotation';
        $template_row = Forms::build_print_template($print_template, $data_arr['main'], array('inv_detail' => $data_arr['Details'], 'inv_detail_linked' => $data_arr['DetailsLinked']));
        //$this->load->view_html($html, $vars);
        //        echo"<pre>";die(print_r($data_arr));
        if (smc_session()['default_setting']['sumatra_print'] == 1) {
            $print_w_h = Forms::get_print_width_height('pos');
            $filename = Forms::html2pdf($template_row['html'], $print_w_h);
            Forms::real_print(null, $filename, ['repeat' => $template_row['copies']]);
        } else {
            echo $template_row['html'];
        }
        exit;
    }

    public function reprintOrder() {
        $inv_id = $_GET['Invoice_ID_Auto'];
        $inv_type = $_GET['invoice_type'];
        $_GET['open_cash_table'] = 0;
        $_GET['reprint_order'] = 1;
        $RET = $this->_registry->Invoice->setdata($_GET)->printPOSInvoice($inv_id, $inv_type);
        die(json_encode(empty($RET) ? ['OK'] : $RET[0]));
    }

    public function print_fire() {
        $inv_id = $_GET['Invoice_ID_Auto'];
        $inv_type = $_GET['invoice_type'];
        $_GET['open_cash_table'] = 0;
        $_GET['reprint_order'] = 1;

        $RET = $this->_registry->Invoice->setdata($_GET)->printPOSInvoice($inv_id, $inv_type);
        die(json_encode(empty($RET) ? ['OK'] : $RET[0]));
    }

    public function ChangeDeliveryStatus() {
        $inv_id = $_GET['Invoice_ID'];
        $inv_type = $_GET['Invoice_Status'];
        $_GET['open_cash_table'] = 0;
        $submit = $this->_registry->Invoice->setdata($_GET)->updateDeliveryStatus();
        if (empty($submit)) {
            $_GET['reprint_order'] = 1;
            $RET = $this->_registry->Invoice->setdata($_GET)->printPOSInvoice($inv_id, $inv_type);
            die(json_encode(empty($RET) ? ['OK'] : $RET[0]));
        }
    }

    public function generateInvoice() {
        $inv_id = $_GET['Invoice_ID_Auto'];
        $RET = $this->_registry->Invoice->generateInvoice($inv_id);
        //        die(print_r($RET));
        die(json_encode(!is_array($RET) ? ['OK'] : $RET[0]));
    }

    public function generateCashInvoice() {
        $inv_id = $_GET['Invoice_ID_Auto'];
        $RET = $this->_registry->Invoice->setData($_GET)->generateCashInvoice($inv_id);
        die(json_encode(!is_array($RET) ? ['OK'] : $RET[0]));
    }

    public function viewInvoicePOS() {
        $invoice_id = $_GET['Invoice_ID_Auto'];
        $RET = $this->_registry->Invoice->setData($_GET)->viewInvoicePOS($invoice_id);
        die($RET);
    }

    public function ajaxOnlineOrders() {
        $RET = $this->_registry->Invoice->setdata($_POST)->submitOnlineOrders();
        die(json_encode(empty($RET) ? ['OK'] : $RET[0]));
    }

    //used function
    public function ajaxPOS() {
        $condition = '';
        $db = DBConnectorFactory::loadDriver();
       
        //show_products_from_all_branches
        if(smc_session()['default_setting']['show_products_from_all_branches'] == 0){
            $depot_id = smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'];
            $branch_id = CommonBusiness::getBranchByDepot($depot_id);
           // $condition .= ' and (p.branch_id is null or p.branch_id LIKE  "%' . $branch_id . '%" or p.branch_id LIKE  "%,' . $branch_id . '%" or p.branch_id LIKE  "%' . $branch_id . ',%")';
            if($this->permissions->hasPermission('Branches')){
                $condition .= '';
            }else{
                $condition .= ' and p.multi_branch_id in (' . (smc_session()['user_accounts']['branch_id']) . ') OR p.multi_branch_id LIKE "' . (smc_session()['user_accounts']['branch_id']) . ',%" OR p.multi_branch_id LIKE "%,' . (smc_session()['user_accounts']['branch_id']) . ',%" OR p.multi_branch_id like "%,' . (smc_session()['user_accounts']['branch_id']) . '"  ' ;
            }
        }
        
        $return_arr = array();
        $query = $db->query('SELECT Cat_ID, Cat_Name FROM tbl_product_cat WHERE Cat_Name LIKE "%' . smc_escape(str_replace(" ", "%", trim($_GET['term']))) . '%" ');
        while ($row = $db->fetch($query)) {
            $row_array['id'] = $row['Cat_ID'];
            $row_array['value'] = $row['Cat_Name'];
            array_push($return_arr, $row_array);
        }
        $query = $db->query('SELECT p.*,u.* 
            FROM tbl_stock_products p
            inner join tbl_uom_conversions u on u.Product_ID = p.Product_ID and u.uom_to = p.UOM_ID
            WHERE (p.Product_Name LIKE "%' . smc_escape(str_replace(" ", "%", trim($_GET['term']))) . '%" 
                or p.Product_Code LIKE "%' . smc_escape(str_replace(" ", "%", trim($_GET['term']))) . '%"
                or u.Bar_Code LIKE "%' . smc_escape(str_replace(" ", "%", trim($_GET['term']))) . '%"  ) and Product_Type in (0,1) and p.Status_ID = 1 ' . $condition . '
                limit 60');
        while ($row = $db->fetch($query)) {
            $Thumb = file_exists(upload_path . 'products_photos/' . $row['Product_ID'] . '.jpg');
            $row_array['id'] = $row['Product_ID'];
            $row_array['uom'] = $row['uom_from'];
            $row_array['value'] = ($row['Bar_Code'] ? $row['Bar_Code'] . ' - ' : '') . $row['Product_Name'];
            $row_array['category'] = $row['Category_ID'];
            $row_array['thumb'] = $Thumb;
            array_push($return_arr, $row_array);
        }
        echo json_encode($return_arr);
    }

    //used function
    public function ajaxPOSCustomer() {
        if (!isset($_GET["term"]))
            die();
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";

        $RET = array();
        if ($cmd == "") {
            $customer = new Customer();

            $ALL = $customer->getPOSCustomers();
            for ($x = 0; $x < count($ALL); $x++) {
                if (strpos(strtolower($ALL[$x]["customer_name"]), strtolower($_GET["term"])) !== false || strpos(strtolower($ALL[$x]["customer_phone"]), strtolower($_GET["term"])) !== false || strpos(strtolower($ALL[$x]["customer_address"]), strtolower($_GET["term"])) !== false) {

                    array_push($RET, $ALL[$x]);
                }
            }
        }


        echo json_encode($RET);
    }

    // used
    public function addDepositeCash() {
        $type = $_POST['dep_type'];
        $today = Date::getToday();
        if ($type == 1 || $type == 2) {
            $_POST['Deposit_WithDrawal_Date'] = $today;
            $_POST['Is_Actual'] = $_POST['is_actual'];
            $_POST['Deposit_WithDrawal_Description'] = ($type == 1 ? "Deposit To " : "Withdrawal From " ) . smc_session()['user_logged_username'] . ' pos cash.';
            $_POST['To_Account'] = $type == 1 ? smc_session()['user_accounts']['cash_account_id'] : smc_session()['user_accounts']['withdrawal_account_id'];
            $_POST['From_Account'] = $type == 1 ? smc_session()['user_accounts']['deposit_account_id'] : smc_session()['user_accounts']['cash_account_id'];
            $_POST[0] = Session::getUserID();
            $return = $this->_registry->jv->setData($_POST)->addDepositWithDrawal(1);
            die(json_encode(!is_array($return) ? ['OK', $return] : ['error']));
        }


        //                        if ($type == 1) {
        //                            $return = $this->_registry->jv->setData($_POST)->addDailyDeposit();
        //                            die(json_encode(!is_array($return) ? ['OK', $return] : ['error']));
        //                        } else if ($type == 2) {
        //                            $return = $this->_registry->jv->setData($_POST)->addDailyWithDrawal();
        //                            die(json_encode(!is_array($return) ? ['OK', $return] : ['error']));
        //                        }
        else if ($type == 3) {
            if (empty($_POST['Account_Code']))
                $_POST['Account_Code'] = Customer::getCustomerAccount(0)['Account_ID'];
            //            echo  $_POST['Account_Code'] .'==';die();
            //            $_POST['Currency_ID'] = 84;
            $_POST['Payment_Date'] = $today;
            $_POST['pos_customer_id'] = $_POST['pay_pos_customers'];
            $_POST['payment'][0]['Payment_Type_ID'] = smc_session()['user_accounts']['cash_account_id'];
            $_POST['payment'][0]['Check_Number'] = 0;
            $_POST['payment'][0]['Payment_Note'] = $_POST['Payment_Note'];
            $_POST['payment'][0]['Payment_Amount'] = $_POST['Payment_Amount'];
            //            $_POST['payment'][0]['pos_customer_id'] = $_POST['pay_pos_customers'];
            $_POST['payment'][0]['Check_Date'] = '';
            $_POST['IsReceipt'] = $_POST['is_receipt'];
            ;
            $_POST[0] = Session::getUserID();
            $_POST['Status_ID'] = $_POST['is_actual'];
            $_POST['is_pos'] = 1;
            $_POST['is_return'] = 0;
            $_POST['branch_id'] = empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id'];
            if (empty($_POST['pay_id'])) {
                $insert = $this->_registry->payment->setData($_POST)->create(true);
            } else {
                $insert = $this->_registry->payment->setData($_POST)->editPayment(true);
            }
             //                            if (empty($insert)) {
            //                if (smc_session()['default_setting']['sumatra_print'] == 1) {
            //                    $paymentdetails = $this->_registry->payment->getPaymentToPrint($maxpayment['Payment_Auto_ID']);
            //                    $print_payment = $this->_registry->Invoice->printPosPayment($paymentdetails);
            //                }
            //                            }
            die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[2]] : ['error']));
        }

        //        die(empty($insert) ? ['OK', $maxpayment] : ['error']);
    }

    // used
    public function getDepositCash() {
        $type = $_GET['dep_type'];
        $Org_Type = $_GET['Org_Type'];
        $cash_deposit = $type == 1 ? $this->_registry->jv->viewDailyDepositByUser($_GET['is_actual']) : ($Org_Type == 1 ? $this->_registry->jv->getDailyCashPOS($_GET['is_actual']) : $this->_registry->jv->viewBalanceDailyCash());
        $cash_deposit_second_currency = $this->_registry->jv->getSecondCurrencyDailyCashPOS($_GET['is_actual']);
        $total_sales = 0;
        if (isset($_GET['with_sales'])) {
            $total_sales = $this->_registry->Invoice->setData($_GET)->get_total_sales();
        }
        $last_end_of_day = $this->_registry->Invoice->get_open_shift_time(null, 1);
        die(json_encode(['cash' => $cash_deposit,'second_cash' => $cash_deposit_second_currency, 'sales' => $total_sales, 'last_end_of_day' => '('.CommonLanguage::getMessage('last_end_of_day').': ' . $last_end_of_day . ' )']));
    }

    // used
    public function addTag() {
        $insert = $this->_registry->product->setData($_POST)->addTag();
        die(json_encode(is_array($insert) ? (empty($insert) ? 'OK' : 'error') : $insert));
    }

    // used
    public function assignTag() {
        $insert = $this->_registry->product->setData($_POST)->addTagTypes();
        die(empty($insert) ? 'OK' : 'error');
    }

    // used
    public function addCustomerInfo() {
        if ($_POST['is_edit'] == 1) {
            $insert = $this->_registry->customer->setData($_POST)->updateCustomerPOS();
            if (!empty($insert))
                die(json_encode(['error', $insert[0]]));
            $cust_id = $_POST['customer_id'];
        } else {
            $insert = $this->_registry->customer->setData($_POST)->addCustomerPOS();
            if (is_array($insert))
                die(json_encode(['error', $insert[0]]));
            $cust_id = $insert;
        }
        $cust_data = $this->_registry->customer->setData(array('customer_id' => $cust_id))->searchRoadCustomer();
        die(json_encode(['OK', $cust_id, $cust_data]));
    }

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

    //used
    public function ReturnFullInvoice() {
        $return = $this->_registry->return->returnFullInvoice($_GET['Invoice_ID']);
        die(empty($return) ? 'OK' : 'error');
    }

    //used 
    public function ChangeInvoiceStatus() {
        if (isset($_GET["Invoice_Status"]) && isset($_GET["Invoice_ID"])) { // to update Status
            $StatusUpdate = $this->_registry->Invoice->updateInvoiceStatus(intval($_GET["Invoice_Status"]), intval($_GET["Invoice_ID"]));
            die(empty($StatusUpdate) ? "OK" : "error");
        }
    }

    // used function
    //    public function getRemindersInv() {
    //
    //        $time = '20';
    //
    //        $current_time = date("h:i a");
    //        $today = Date::getToday();
    //        $compared_time = date("h:i a", strtotime('+' . $time . ' minutes', strtotime($current_time)));
    //        $cond = 'STR_TO_DATE(CONCAT("' . $today . '"," ",Delivery_Time), "%Y-%m-%d %h:%i %p") <= STR_TO_DATE(CONCAT("' . $today . '"," ","' . $compared_time . '"), "%Y-%m-%d %h:%i %p") AND Invoice_Status = 3 AND Invoice_Date="' . $today . '" ORDER BY Delivery_Time ASC';
    //        $columns = array(
    //            array('db' => 'Invoice_ID', 'dt' => 0),
    //            array('db' => 'Customer_Name', 'dt' => 1),
    //            array('db' => 'Delivery_Time', 'dt' => 2, 'formatter' => function($d, $row) {
    //
    //                    $current_time = date("h:i A");
    //                    if (round((strtotime($d) - strtotime($current_time)) / 60, 2) > 0)
    //                        return '<span data-id = "1" class="label label-important checkSpan">' . round((strtotime($d) - strtotime($current_time)) / 60, 2) . '&nbsp' . CommonLanguage::getMessage('min_left') . ' </span>';
    //                    else
    //                        return '<span data-id = "0" class="label label-master checkSpan">' . round((strtotime($current_time) - strtotime($d)) / 60, 2) . '&nbsp' . CommonLanguage::getMessage('min_passed') . ' </span>';
    //                }),
    //            array(
    //                'db' => 'Invoice_ID_Auto',
    //                'dt' => 3,
    //                'formatter' => function( $d, $row) {
    //                    return '<a class="btn print bg-danger-dark" data-id = "' . $d . '" data-value = "' . $row[4] . '"><i class="fa fa-print"></i>' . CommonLanguage::getMessage("print") . '</a>';
    //                    //                                                    $html = Forms::action_snippet(["color" => "info", "isDropDown" => false, "data_id" => $d,
    //                    //                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("print"),
    //                    //                                                                "class" => "print bg-danger-dark",
    //                    //                                                                "icon" => "fa-print"
    //                    //                                                                    ]
    //                    //                                                    ]]);
    //                    //                                                    return $html;
    //                }
    //            ), 'Invoice_Net_Total'
    //        );
    //        $key = 'Invoice_ID_Auto';
    //        $table = 'pos_invoices';
    //        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
    //
    //        echo json_encode($data);
    //    }
    // used
    public function POSCustomerListRequest() {
        $columns = array(
            array('db' => 'customer_name', 'dt' => 0),
            array('db' => 'customer_address', 'dt' => 1),
            array('db' => 'customer_phone', 'dt' => 2),
            array(
                'db' => 'customer_id',
                'dt' => 3,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "info", "isDropDown" => false, "data_id" => $d,
                                                   "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                       "class" => "editCust bg-info",
                                                                       "icon" => "fa-pencil"
                                                                      ]
                                                                     ]]);
                    return $html;
                }
            )
        );
        $key = 'customer_id';
        $table = 'tbl_pos_customers';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    // used
    public function POSInvoiceListRequests() {
        $cond = ' AND Invoice_Date = "' . $_GET['Date'] . '" ';
        $columns = array(
            array('db' => 'Bon_Number', 'dt' => 0),
            array('db' => 'Customer_Name', 'dt' => 1, "formatter" => function($d) {
                return $d == '' ? '-- --' : $d;
            }),
            array('db' => 'Invoice_Date', 'dt' => 2),
            array('db' => 'Delivery_Time', 'dt' => 3, "formatter" => function($d) {
                return $d == '' ? '-- --' : $d;
            }),
            array('db' => 'Invoice_Sub_Total', 'dt' => 4),
            array('db' => 'Invoice_Status', 'dt' => 5,
                  'formatter' => function($d) {
                      $Statuses = [$this->_registry->expenses->getStatusName(12) . "#label-important",
                                   $this->_registry->expenses->getStatusName(13) . "#label-warning",
                                   $this->_registry->expenses->getStatusName(6) . "#label-master",
                                   $this->_registry->expenses->getStatusName(32) . "#label-info",
                                   $this->_registry->expenses->getStatusName(33) . "#label-inverse",
                                   $this->_registry->expenses->getStatusName(34) . "#label-inverse",
                                   $this->_registry->expenses->getStatusName(24) . "#label-inverse"];
                      return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
                  }),
            array(
                'db' => 'Invoice_ID_Auto',
                'dt' => 6,
                'formatter' => function( $d, $row) {
                    $Statuses = [$this->_registry->expenses->getStatusName(12) . "#label-important",
                                 $this->_registry->expenses->getStatusName(13) . "#label-warning",
                                 $this->_registry->expenses->getStatusName(6) . "#label-master",
                                 $this->_registry->expenses->getStatusName(32) . "#label-info",
                                 $this->_registry->expenses->getStatusName(33) . "#label-inverse",
                                 $this->_registry->expenses->getStatusName(34) . "#label-inverse",
                                 $this->_registry->expenses->getStatusName(24) . "#label-inverse"];
                    $html = "<div class='btn-group' >
                <button type='button' " . (($row[5] == 4 || $row[5] == 6) ? 'disabled' : '') . " class='btn btn-default  dropdown-toggle' data-toggle='dropdown' aria-expanded='false'  >
                    <i class='fa fa-pencil'> <span class='caret'></span></i>
                </button><ul class='dropdown-menu Invoice_Status' data-id='{$d}' role='menu' style='cursor:pointer' name='Invoice_Status' >";
                    $ignore_status = [4, 1, 6, 3];
                    for ($x = 0; $x < count($Statuses); $x++) {
                        if ($row[5] != $x && !in_array($x, $ignore_status))
                            $html .= "<li value='" . ($x ) . "'><a href='javascript:void()'>" . explode("#", $Statuses[$x])[0] . "</a></li>";
                    }
                    $html .= "</ul></div>";
                    return $html;
                }
            ),
            array(
                'db' => 'Invoice_ID_Auto',
                'dt' => 7,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "info", "isDropDown" => true, "data_id" => $d,
                                                   "ActionOption" => [["title" => CommonLanguage::getMessage("return"),
                                                                       "class" => "full-return",
                                                                       "icon" => "fa-retweet"
                                                                      ]
                                                                     ]]);
                    return $html;
                }
            ),
        );

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

        echo json_encode($data);
    }

    // used function
    public function createRoleModalRequest() {
        $logged_id = Session::getUserID();
        array_push($_POST, $logged_id);
        $RET = $this->_registry->role->setData($_POST)->submit_role();
        die(json_encode(empty($RET) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [CommonLanguage::getMessage('role_exist'), 'danger']));
    }

    public function getInvoiceDetails() {
        $data = $this->_registry->MainInvoice->getInvoiceByID($_GET['invoice_id_auto'], true);
        die(json_encode($data));
    }

    public function getExchangeDetails() {
        $data = $this->_registry->Invoice->retreive_exchange_by_id($_GET['id'], true);
        die(json_encode($data));
    }

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

    public function getCustomerAddresses() {
        $RET = $this->_registry->restaurantpos->setdata($_GET)->getCustomerAddresses();
        echo json_encode($RET);
    }

    public function searchBarcodeforPOS() {
        //        $data = $this->_registry->product->searchBarcodeforPOS('12300001060005');
        $class_id = !empty($_GET["class_id"]) ? $_GET["class_id"] : smc_session()['pricing_class_id'];
        $customer_id = isset($_GET["customer_id"]) ? $_GET["customer_id"] : NULL;
        $depot_id = !empty($_GET["depot_id"]) ? $_GET["depot_id"] : null;
        $type = !empty($_GET["type"]) ? $_GET["type"] : null;
        $data = $this->_registry->product->searchBarcodeforPOS($_GET['barcode'], $class_id, $depot_id, $type, $customer_id);
        die(json_encode($data));
    }

    public function searchProductforPOS() {
        $ID = isset($_GET["id"]) ? floatval($_GET["id"]) : 0;
        $customer_id = isset($_GET["customer_id"]) ? $_GET["customer_id"] : NULL;
        $class_id = !empty($_GET["class_id"]) ? $_GET["class_id"] : smc_session()['pricing_class_id'];
        $depot_id = !empty($_GET["depot_id"]) ? $_GET["depot_id"] : smc_session()['default_depot_id'];
        $data = $this->_registry->product->searchProductforPOS($ID, $class_id, $depot_id, $customer_id);
        die(json_encode($data));
    }

    public function deleteParkedInvoice() {
        //        $delete = $this->_registry->Invoice->deleteParkedInvoice([$_GET['invoice_id']]);
        $delete = $this->_registry->MainInvoice->deleteSalesInvoice([$_GET['invoice_id']]);
        die(empty($delete) ? 'OK' : 'error');
    }

    public function ReturnClassCurrency() {
        $data = $this->_registry->customer->ReturnClassCurrency($_GET['class_id']);
        die(json_encode($data));
    }

    public function addExpensePOS() {
        //                                                                $logged_id = Session::getUserID();
        //                                                                array_push($_POST, $logged_id);
        $_POST['branch_id'] = (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']);
        $result = $this->_registry->expenses->setData($_POST)->add_expense();

        die(json_encode(is_numeric($result[0]) ? ["OK", $result[0]] : [$result[0]]));
    }

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

    public function get_postponed_report() {
        $data = $this->_registry->Invoice->setData($_GET)->get_postponed_report();
        $html = Forms::build_postponed_report($data);
        die($html);
    }

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

    public function get_cash_btns_by_cur() {
        $data = $this->_registry->jv->getCashCategoriesByCurrency($_GET['currency_id']);
        die(json_encode($data));
    }

    public function InvoiceListByLoggedUser() {

        //$cond = ' 1=1  and table_id = 0';
        $cond = ' isnull(exchange_id) ';
        if (isset($_GET['customer_supplier_id']) && $_GET['customer_supplier_id'] != '') {
            $cond .= ' and Person_ID = "' . $_GET['customer_supplier_id'] . '"';
        }
        if (isset($_GET['pos_customer']) && $_GET['pos_customer'] != '') {
            $cond .= ' and pos_customer_id = "' . $_GET['pos_customer'] . '"';
        }
        if (isset($_GET['invoice_status']) && $_GET['invoice_status'] !== '') {
            $cond .= ' and Invoice_Status in (' . implode(',', $_GET['invoice_status']) . ')';
        }
        if (isset($_GET['is_delivery']) && $_GET['is_delivery'] !== 'all') {
            $cond .= ' and Is_Delivery = "' . $_GET['is_delivery'] . '"';
        }
        if (!empty($_GET['is_delivery_list']))
            $cond .= ' and Is_Delivery = "1"';
        if (!empty($_GET['delivery_user']))
            $cond .= ' and Logged_ID = "' . $_GET['delivery_user'] . '"';
        if (!empty($_GET['inv_list_nb'])) {
            $cond .= ' and ID = "' . $_GET['inv_list_nb'] . '"';
        }

        if (!empty($_GET['due_date_from']) && !empty($_GET['due_date_to'])) {
            $cond .= ' and Due_Date between  "' . $_GET['due_date_from'] . '"  and  "' . $_GET['due_date_to'] . '"';
        }
        if (!empty($_GET['smart_status'])) {
            if ($_GET['smart_status'] == 1) {
                $cond .= ' and Is_Delivery = 1 ';
            } else if ($_GET['smart_status'] == 2) {
                $cond .= ' and Inv_Type = 2 and table_id = 0 ';
            } else if ($_GET['smart_status'] == 3) {
                $cond .= ' and table_id <> 0 ';
            }
        }
        if($this->permissions->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id_for_invoices']) ? ' and branch_id ="' . ($_GET['search_branch_id_for_invoices']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        //echo json_encode($this->permissions->hasPermission('view_all_pos_invoices'));
        //die('ok');
        if (!$this->permissions->hasPermission('view_all_pos_invoices')) {
            $cond .= ' and Logged_ID = "' . smc_session()['user_logged_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and Date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }

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

        $cond .= ' AND current_year_id = "' . $this->year_id . '" ';

        //
        $actions_col = array(
            'db' => 'ID_Auto',
            'formatter' => function( $d, $row) {
                if (empty($row['reason_id'])) {
                    $option_arr = [["title" => CommonLanguage::getMessage("print_invoice"),
                                    "class" => "printInv ",
                                    "icon" => "fa-print"],
                                   ["title" => CommonLanguage::getMessage("print_order"),
                                    "class" => "printOrder ",
                                    "icon" => "fa-print"],
                                   ["title" => CommonLanguage::getMessage("view_invoice"),
                                    "class" => "view_invoice openFrame",
                                    "icon" => "fa-eye",
                                    "attr" => "data-src='Inventory/pos_view_invoice/{$row['ID_Auto']}?is_pop=1&type_preview=1'"
                                   ],
                                   ["title" => CommonLanguage::getMessage("transfer"),
                                    "class" => "transfer_inv ",
                                    "icon" => "fa-exchange",
                                   ]
                                  ];
                    if (($row['table_id'] == 0 || ($row['Is_Closed'] == 1 && $row['table_id'] != 0 && $this->permissions->hasPermission('edit_closed_table'))) &&
                        $row['is_branch_transfer'] == 0 && $row['invoice_app_id'] == 0 &&
                        (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || $row['is_main_transfer'] == 0) && empty($row['reason_id']) /* && $row['Payment_Paid_Amount'] == 0 */) {
                        $option_arr[] = ["title" => CommonLanguage::getMessage('delete'),
                                         "class" => "delete_inv",
                                         'permission' => 'delete_pos_inv',
                                         "icon" => "fa-trash",
                                        ];
                        $option_arr[] = ["title" => CommonLanguage::getMessage('retreive'),
                                         "class" => "get_retrieved_data",
                                         "permission" => "get_retrieved_data",
                                         "icon" => "fa-download",
                                        ];
                    }
                    if (empty($row['reason_id'])) {
                        $option_arr[] = ["title" => CommonLanguage::getMessage('void'),
                                         "class" => "void_current_invoice",
                                         "permission" => "void_invoice",
                                         "data-target" => "#VoidReasonModal",
                                         "attr" => "data-origin='list' data-invoice-id='{$d}'",
                                         "icon" => "fa-retweet",
                                        ];
                    }
                    $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                   "ActionOption" => $option_arr]);
                    return $html;
                } else {
                    return CommonLanguage::getMessage('void');
                }
            }
        );
        //invoice list case
        if (empty($_GET['is_delivery_list'])) {
            $columns = array(
                array('db' => 'ID', "formatter" => function($d) {
                    return '<input type="checkbox" class="inv_del_td pull-left multi_delete"/>' . $d;
                }));
            if (smc_session()['default_setting']['activate_smart_diner'] == 1) {
                $columns[] = 'table_name';
            }
            $columns = array_merge($columns, array(
                array('db' => 'Name', "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
                'date_created',
                'Due_Date',
                array('db' => 'net_with_ship', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
                array('db' => 'total_paid_amount', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
                array('db' => 'net_with_ship', "formatter" => function($d, $row) {
                    return (CommonFunctions::formatNumber($d - $row['total_paid_amount']) . ' ' . $row['Currency_Symbol']);
                }),
            ));
        }
        //delivery list
        else {
            $columns = array(
                array('db' => 'ID', "formatter" => function($d) {
                    return '<input type="checkbox" class="inv_del_td pull-left multi_delete"/>' . $d;
                }),
                array('db' => 'Name', "formatter" => function($d) {
                    return $d == '' ? '-- --' : $d;
                }),
                'Delivery_Time',
                'pos_customer_address',
                array('db' => 'net_with_ship', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
                array('db' => 'Invoice_Shipping', "formatter" => function($d, $row) {
                    return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                }),
                array('db' => 'total_paid_amount', "formatter" => function($d, $row) {
                    return (CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol']);
                }),
            );
        }
        //
        $columns = array_merge($columns, array($actions_col, 'ID_Auto', 'Currency_Symbol', 'table_id', 'posponted_type', 'is_branch_transfer', 'invoice_app_id', 'is_main_transfer', 'Is_Closed', 'reason_id', 'Invoice_Paid_Amount', 'Payment_Paid_Amount'));
        //
        $key = 'ID_Auto';
        $table = 'invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function PostponedListByLoggedUser() {
        //                                                        $cond = ' 1=1  and table_id = 0';
        $cond = ' 1=1';
        if (isset($_GET['customer_supplier_id']) && $_GET['customer_supplier_id'] != '') {
            $cond .= ' and Person_ID = "' . $_GET['customer_supplier_id'] . '"';
        }
        if (isset($_GET['pos_customer']) && $_GET['pos_customer'] != '') {
            $cond .= ' and pos_customer_id = "' . $_GET['pos_customer'] . '"';
        }
        if (isset($_GET['invoice_status']) && $_GET['invoice_status'] !== '') {
            $cond .= ' and Invoice_Status in (' . implode(',', $_GET['invoice_status']) . ')';
        }
        if (isset($_GET['is_delivery']) && $_GET['is_delivery'] !== 'all') {
            $cond .= ' and Is_Delivery = "' . $_GET['is_delivery'] . '"';
        }
        if (!empty($_GET['inv_list_nb'])) {
            $cond .= ' and ID = "' . $_GET['inv_list_nb'] . '"';
        }
        if (!empty($_GET['posponted_status'])) {
            $cond .= ' and posponted_type = "' . $_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'] . '"';
        }
        if (isset($_GET['is_committed']) && $_GET['is_committed'] !== 'all') {
            $cond .= ' and is_committed = "' . $_GET['is_committed'] . '" ';
        }
        $cond .= ' and is_actual="' . $_GET['is_actual'] . '" ';

        $cond .= '  and invoice_type=5 ';
        //        echo json_encode($this->permissions->hasPermission('view_all_pos_invoices'));
        //                         die('ok');
        if (!$this->permissions->hasPermission('view_all_pos_invoices')) {
            $cond .= ' and Logged_ID = "' . smc_session()['user_logged_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and Date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }
        $cond .= ' AND current_year_id = "' . $this->year_id . '" and  posponted_type <> 0';

        $columns = array('ID',
                         array('db' => 'Name', 'dt' => 1, "formatter" => function($d) {
                             return $d == '' ? '-- --' : $d;
                         }),
                         array('db' => 'date_created', 'dt' => 2),
                         array('db' => 'postponed_date_time', 'dt' => 3),
                         array('db' => 'postponed_note', 'dt' => 4),
                         array('db' => 'net_with_ship', 'dt' => 5, "formatter" => function($d, $row) {
                             return CommonFunctions::formatNumber($d) . ' ' . $row[11];
                         }),
                         array('db' => 'Invoice_Paid_Amount', 'dt' => 6, "formatter" => function($d, $row) {
                             return CommonFunctions::formatNumber($d + $row['Payment_Paid_Amount']) . ' ' . $row[11];
                         }),
                         array('db' => 'net_with_ship', 'dt' => 7, "formatter" => function($d, $row) {
                             return CommonFunctions::formatNumber($d - $row[6] - $row['Payment_Paid_Amount']) . ' ' . $row[11];
                         }),
                         array('db' => 'posponted_type', 'dt' => 8, "formatter" => function($d, $row) {
                             $label_name = CommonLanguage::getMessage($d == 1 ? 'Request' : ($d == 2 ? 'production_line' : ($d == 3 ? 'production_done' : ($d == 4 ? 'delivered' : ($d==5?'on_request':'canceled')))));
                             $label_color = $d == 1 ? 'important' : ($d == 2 ? 'master' : ($d == 3 ? 'warning' :  ($d == 4 ? 'info':($d==5?'yellow':'success'))));
                             return '<span class="label label-' . $label_color . '" data-status="' . $d . '">' . $label_name . '</span>';
                             return;
                         }),
                         array(
                             'db' => 'ID_Auto',
                             'dt' => 9,
                             'formatter' => function( $d, $row) {
                                 $option_arr = [
                                     ["title" => CommonLanguage::getMessage('posponted_status'),
                                      "class" => "change_postpone_status",
                                      'permission' => 'change_postpone_status',
                                      "attr" => "data-status='" . $row[13] . "' data-origin='inv'",
                                      "icon" => "fa-retweet",
                                     ],
                                     ["title" => CommonLanguage::getMessage('view'),
                                      "class" => "view_postponed_details openFrame",
                                      'permission' => 'view_postponed_details',
                                      'attr' => "data-src='POSAjax/viewInvoicePOS?Invoice_ID_Auto={$d}&is_posponed=1'",
                                      "icon" => "fa-eye",
                                     ],
                                     ["title" => CommonLanguage::getMessage('print'),
                                      "class" => "printInv",
                                      'permission' => 'print_postponed_invoice',
                                      "icon" => "fa-print",
                                     ],
                                     ["title" => CommonLanguage::getMessage('return'),
                                      "class" => "return_postponed",
                                      'permission' => 'pos_return_postponed',
                                      "icon" => "fa-retweet",
                                     ],
                                     ["title" => CommonLanguage::getMessage("transfer"),
                                            "class" => "transfer_inv openFrame",
                                             "attr" => !empty($_GET['from_inventory']) ? "href='".SITE_LINK."Stock/RequestOrder/transfer/invoice/" . $row['ID_Auto']."'" : "",
                                            "permission" =>!empty($_GET['from_inventory']) ? "inv_postponed_transfer_invoice" : "pos_transfer_postponed",
                                            "icon" => "fa-exchange"]
                                 ];
//                                      if($_GET['from_inventory']==1){
//                                           $option_arr[] = ["title" => CommonLanguage::getMessage("transfer"),
//                                            "class" => "transfer_inv openFrame",
//                                             "href" => $_GET['from_inventory']==1 ? "Stock/RequestOrder/transfer/invoice/" . $row['ID_Auto'] : "",
//                                            "permission" =>$_GET['from_inventory']==1 ? "inv_postponed_transfer_invoice" : "pos_transfer_postponed",
//                                            "icon" => "fa-exchange"];
//                                      }else{
//                                       $option_arr[] =   ["title" => CommonLanguage::getMessage("transfer"),
//                                            "class" => "transfer_inv ",
//                                            "permission"=>"pos_transfer_postponed",
//                                            "icon" => "fa-exchange",
//                                            ];
//                                      }
                                 if ($row[12] == 0 && $row[14] == 0 && $row[15] == 0 && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || $row['is_main_transfer'] == 0) && empty($_GET['from_inventory'])) {
                                     $option_arr[] = ["title" => CommonLanguage::getMessage('retreive'),
                                                      "class" => "get_retrieved_data",
                                                      "icon" => "fa-download",
                                                     ];
                                 }
                                 $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                                "ActionOption" => $option_arr]);
                                 return $html;
                             }
                         ), 'ID_Auto', 'Currency_Symbol', 'table_id', 'posponted_type', 'is_branch_transfer', 'invoice_app_id', 'is_main_transfer', 'Payment_Paid_Amount'
                        );
        $key = 'ID_Auto';
        $table = 'invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function end_of_shift() {
        $insert = $this->_registry->Invoice->end_of_shift();
        die(json_encode(is_numeric($insert[0]) ? ['OK', $insert[0]] : ['error', $insert[1][0]]));
    }

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

    public function getProductColor() {
        $data = CommonFunctions::SpecificAttribute('tbl_stock_products', ['Product_ID'], [$_GET['product_id']], 'product_color');
        die(json_encode($data));
    }

    public function get_customer_invoices() {
        $created_user = empty($_GET['created_user']) ? null : $_GET['created_user'];
        $data = $this->_registry->Invoice->get_customer_invoices($_GET['customer_id'], $_GET['from_date'], $_GET['to_date'], 0, $_GET['pos_customer'], $_GET['is_actual'], $created_user, $_GET['search_branch_id_for_inv_cus']);
        //        echo"<pre>";die(print_r($data));
        $html = Forms::build_table_html($data['details']);
        die(json_encode([$html, $data]));
    }

    public function get_customer_ledger() {
        $data = $this->_registry->Invoice->customer_ledger($_GET['customer_id'], $_GET['from_date'], $_GET['to_date'], 0, $_GET['ignore_zero'], $_GET['is_actual'], $_GET['road_customer_id'], $_GET['search_branch_id_for_ledger']);
        //        echo"<pre>";die(print_r($data));
        $html = Forms::build_table_html($data['details']);
        die(json_encode([$html, $data]));
    }

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

    public function openDrawerReasonPrint() {
        $is_printed = false;    //we use this flag so if first case failed to be able to open cash drawer by print
        if (!empty(smc_session()['default_setting']['pos_open_cash_drawer_without_print'])) {
            try {
                //note that printer must be shared to be able to connect to it
                $prntr_name = Forms::getDefaultprinterName();
                if (strpos($prntr_name, '\\') === false && strpos($prntr_name, '/') === false)
                    $prntr_name = "\\\\{$_SERVER['REMOTE_ADDR']}\\{$prntr_name}";
                $handle = fopen($prntr_name, "w");
                if ($handle !== false) {
                    fwrite($handle, chr(27) . chr(112) . chr(0) . chr(100) . chr(250));
                    fclose($handle);
                    $is_printed = true;
                }
            } catch (Exception $e) {
                $is_printed = false;
            }
        }
        //
        if (!$is_printed) {
            $template_row['html'] = '<html><body onload="window.print();">&nbsp;</body></html>';
            if (smc_session()['default_setting']['sumatra_print'] == 1) {
                $print_w_h = Forms::get_print_width_height('pos');
                $filename = Forms::html2pdf($template_row['html'], $print_w_h);
                Forms::real_print(null, $filename, ['repeat' => 1]);
            } else
                echo $template_row['html'];
        }
        //
        exit;
    }
    public function manual_openDrawerReasonPrint() {
        
            $template_row['html'] = '<html><body onload="window.print();">&nbsp;</body></html>';
            if (smc_session()['default_setting']['sumatra_print'] == 1) {
                $print_w_h = Forms::get_print_width_height('pos');
                $filename = Forms::html2pdf($template_row['html'], $print_w_h);
                Forms::real_print(null, $filename, ['repeat' => 1]);
            } else
                echo $template_row['html'];
        
        //
        exit;
    }


    public function insertOpenDrawerReason() {
        $insert = $this->_registry->Invoice->insertOpenDrawerReason($_GET['open_reason']);
        die(empty($insert) ? 'OK' : 'error');
    }

    public function open_reason_list() {
        $cond = ' 1=1 ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and date(date_time) between "' . $_GET['from_date'] . '"  and "' . $_GET['to_date'] . '"';
        }
        if (!empty($_GET['reason_user'])) {
            $cond .= ' and user_id = "' . $_GET['reason_user'] . '"';
        }
        $columns = array(
            array('db' => 'User_Name', 'dt' => 0),
            array('db' => 'open_reason', 'dt' => 1),
            array('db' => 'date_time', 'dt' => 2)
        );
        $key = 'open_drawer_id';
        $table = '(select tbl_open_drawer.*,u.User_Name from tbl_open_drawer join tbl_common_users u  on (u.User_ID =tbl_open_drawer.user_id ))as dummy_table';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

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

    public function exchange_list_ajax() {

        $cond = ' 1=1 ';
        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '" ';

        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and exchange_date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }

        $cond .= ' AND current_year_id = "' . $this->year_id . '"  order by exchange_id desc';

        $columns = array(
            array('db' => 'exchange_nb', "formatter" => function($d, $row) {
                return $row['exchange_prefix'] . $d;
            }), 'Customer_Name', 'exchange_date',
            array(
                'db' => 'exchange_id',
                'formatter' => function( $d, $row) {
                    $option_arr = [["title" => CommonLanguage::getMessage("print"),
                                    "class" => "printEx ",
                                    "icon" => "fa-print"],
                                   ["title" => CommonLanguage::getMessage('retreive'),
                                    "class" => "get_ex_data",
                                    "icon" => "fa-download",
                                   ],
                                   ["title" => CommonLanguage::getMessage('delete'),
                                    "class" => "delete_exchange",
                                    'permission' => 'delete_pos_exchange',
                                    "icon" => "fa-trash",
                                   ]
                                  ];
                    $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                   "ActionOption" => $option_arr]);
                    return $html;
                }
            ), 'exchange_prefix'
        );
        $key = 'exchange_id';
        $table = 'exchange_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

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

    public function road_customer_list_ajax() {


        $columns = array('customer_name', 'customer_phone', 'customer_address',
                         array(
                             'db' => 'customer_id',
                             'dt' => 3,
                             'formatter' => function( $d, $row) {
                                 $option_arr = [["title" => CommonLanguage::getMessage("Edit"),
                                                 "class" => "edit_road_customer ",
                                                 "icon" => "fa-pencil"],
                                               ];
                                 $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => false, "data_id" => $d,
                                                                "ActionOption" => $option_arr]);
                                 return $html;
                             }
                         )
                        );
        $key = 'customer_id';
        $table = 'tbl_pos_customers';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

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

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

    public function getRemindersInv() {
        $time = smc_session()['default_setting']['minutes_before_delivery_notification'];
        $current_time = date("H:i:s");
        $today = Date::getToday();
        $compared_time = date("Y-m-d H:i:s", strtotime('+' . $time . ' minutes', strtotime($current_time)));
        $cond = ' Delivery_Time <= "' . $compared_time . '" AND Invoice_Status = 3 and (Is_Delivery =1 || invoice_type=6)and is_delivery_notified = 0 AND Invoice_Date="' . $today . '" ORDER BY Delivery_Time ASC';

        $columns = array(
            array('db' => 'ID', 'dt' => 0),
            array('db' => 'customer_name_mobile', 'dt' => 1),
            array('db' => 'Delivery_Time', 'dt' => 2, 'formatter' => function($d, $row) {
                $current_time = date("Y-m-d H:i:s");
                $current_delivery_date = strtotime($d);
                if (round((strtotime($d) - strtotime($current_time)) / 60, 2) > 0)
                    return '<span data-id = "1" class="label label-important checkSpan">' . round((strtotime($d) - strtotime($current_time)) / 60, 2) . '&nbsp' . CommonLanguage::getMessage('min_left') . '</span><br><span>' . date('h:i', $current_delivery_date) . '</span>';
                else
                    return '<span data-id = "1" class="label label-master checkSpan">' . round((strtotime($current_time) - strtotime($d)) / 60, 2) . '&nbsp' . CommonLanguage::getMessage('min_passed') . ' </span><br><span>' . date('h:i', $current_delivery_date) . '</span>';
            }),
            array(
                'db' => 'ID_Auto',
                'dt' => 3,
                'formatter' => function( $d, $row) {
                    $html = Forms::action_snippet(["color" => "info", "isDropDown" => false, "data_id" => $d,
                                                   "ActionOption" => [["title" => CommonLanguage::getMessage("print"),
                                                                       "class" => "print bg-danger-dark",
                                                                       "icon" => "fa-print"
                                                                      ]
                                                                     ]]);
                    return $html;
                }
            )
        );
        $key = 'ID_Auto';
        $table = 'invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function ReturnListByLoggedUser() {

        //$cond = ' 1=1  and table_id = 0';
        $cond = ' isnull(exchange_id) ';
        if (isset($_GET['customer_id']) && $_GET['customer_id'] != '') {
            $cond .= ' and Person_ID = "' . $_GET['customer_id'] . '"';
        }

        if (!empty($_GET['ret_list_nb'])) {
            $cond .= ' and return_nb = "' . $_GET['ret_list_nb'] . '"';
        }

        if (isset($_GET['is_actual']))
            $cond .= ' and Is_Actual = "' . $_GET['is_actual'] . '" ';
        //echo json_encode($this->permissions->hasPermission('view_all_pos_invoices'));
        //die('ok');
        if (!$this->permissions->hasPermission('view_all_pos_returns')) {
            $cond .= ' and Logged_ID = "' . smc_session()['user_logged_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and Date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }

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

        $cond .= ' AND current_year_id = "' . $this->year_id . '" ';

        $columns = array('return_nb',
                         array('db' => 'Name', 'dt' => 1, "formatter" => function($d) {
                             return $d == '' ? '-- --' : $d;
                         }), 'date_created', 
                         array('db' => 'NetTotal', "formatter" => function($d) {
                             return CommonFunctions::public_round_number($d) ;
                         }), 
                         array('db' => 'Return_Paid_Total', "formatter" => function($d) {
                             return CommonFunctions::public_round_number($d) ;
                         }),
                         array(
                             'db' => 'Return_Invoice_ID',
                             'dt' => 5,
                             'formatter' => function( $d, $row) {
                                   $option_arr = [["title" => CommonLanguage::getMessage("print"),
                                                 "class" => "printRet",
                                                 "icon" => "fa-print"]
                                                 ,["title" => CommonLanguage::getMessage("view"),
                                                 "class" => "View openFrame",
                                                 "permission" => (smc_escape($_GET['Is_Vendor']) === "1" ? ($_GET['is_actual'] ? "ViewReturnDebitActual" : ($row['disable_qty'] ==1 ? "view_ret_supp_noqty": "ViewReturnDebit")) : ($_GET['is_actual'] ? "ViewReturnCreditActual" : ($row['disable_qty'] ==1 ? "view_ret_cust_noqty": "ViewReturnCredit")) ),
                                                 "attr" => "data-src='Inventory/pos_view_return/{$d}'",
                                                 "icon" => "fa-eye"]];
                                 if (empty($row['invoice_app_id']) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {

                                     $option_arr[] = ["title" => CommonLanguage::getMessage('delete'),
                                                      "class" => "delete_ret",
                                                      'permission' => 'pos_delete_return',
                                                      "icon" => "fa-trash",
                                                     ];
                                     $option_arr[] = ["title" => CommonLanguage::getMessage('retreive'),
                                                      "class" => "get_retrieved_ret_data",
                                                      "icon" => "fa-download",
                                                     ];
                                 }

                                 $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                                "ActionOption" => $option_arr]);
                                 return $html;
                             }
                         ), 'is_main_transfer', 'invoice_app_id'
                        );
        $key = 'Return_Invoice_ID';
        $table = 'customer_return_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

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

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

    public function get_scanned_customer() {
        $data = $this->_registry->customer->getCustomerForAutoComplete(null, false, null, $_GET['customer_code']);
        die(json_encode(['item' => !empty($data) ? $data[0] : '']));
    }

    public function get_customer_by_id() {
        $data = $this->_registry->customer->getCustomerForAutoComplete(null, false, $_GET['id'], $_GET['id']);
        die(json_encode(['item' => !empty($data) ? $data[0] : '']));
    }

    public function received_delivery_ajax() {

        //$cond = ' 1=1  and table_id = 0';
        $cond = ' isnull(exchange_id) ';
        if (isset($_GET['customer_supplier_id']) && $_GET['customer_supplier_id'] != '') {
            $cond .= ' and Person_ID = "' . $_GET['customer_supplier_id'] . '"';
        }
        if (isset($_GET['pos_customer']) && $_GET['pos_customer'] != '') {
            $cond .= ' and pos_customer_id = "' . $_GET['pos_customer'] . '"';
        }
        if (!empty($_GET['rec_driver_filter'])) {
            $cond .= ' and driver_id = "' . $_GET['rec_driver_filter'] . '"';
        }
        if (!empty($_GET['rec_region_filter'])) {
            $cond .= ' and region_id = "' . $_GET['rec_region_filter'] . '"';
        }
        if (isset($_GET['received_status']) && $_GET['received_status'] != '') {
            if ($_GET['received_status'] == 0)
                $cond .= ' and received_date is null';
            else if ($_GET['received_status'] == 1)
                $cond .= ' and !isnull(received_date) ';
        }
        //        if (isset($_GET['invoice_status']) && $_GET['invoice_status'] !== '') {
        //            $cond .= ' and Invoice_Status in (' . implode(',', $_GET['invoice_status']) . ')';
        //        }
        //      echo $cond.'===';
        $cond .= ' and Is_Delivery = "1"';
        if (!empty($_GET['delivery_user']))
            $cond .= ' and Logged_ID = "' . $_GET['delivery_user'] . '"';
        if (!empty($_GET['inv_list_nb'])) {
            $cond .= ' and ID = "' . $_GET['inv_list_nb'] . '"';
        }
        //echo $cond.'===';


        if (isset($_GET['is_actual']))
            $cond .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        if (!$this->permissions->hasPermission('view_all_pos_invoices')) {
            $cond .= ' and Logged_ID = "' . smc_session()['user_logged_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and Date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }
        $cond .= ' AND current_year_id = "' . $this->year_id . '" ';
        //
        $actions_col = array(
            'db' => 'ID_Auto',
            'formatter' => function( $d, $row) {
                if (empty($row['reason_id'])) {
                    $option_arr = [
                        ["title" => CommonLanguage::getMessage("view_invoice"),
                         "class" => "view_invoice openFrame",
                         "icon" => "fa-eye",
                         "attr" => "data-src='Inventory/pos_view_invoice/{$row['ID_Auto']}?is_pop=1&type_preview=1'"
                        ],
                        ["title" => CommonLanguage::getMessage("Note"),
                         "class" => "change_rec_note",
                         "icon" => "fa-file-o",
                         "permission" => "change_inv_rec_note",
                         "data-target" => "#rec_note_modal"
                        ]
                    ];
                    if (empty($row['received_date'])) {
                        $option_arr[] = ["title" => CommonLanguage::getMessage("received"),
                                         "class" => "change_inv_received change_rec",
                                         "icon" => "fa-retweet",
                                         "attr" => " data-status='1' ",
                                         "permission" => "change_inv_received"
                                        ];
                    }
                    if (!empty($row['received_date'])) {
                        $option_arr[] = ["title" => CommonLanguage::getMessage("not_received"),
                                         "class" => "change_inv_not_received change_rec",
                                         "icon" => "fa-retweet",
                                         "attr" => " data-status='0' ",
                                         "permission" => "change_inv_not_received"
                                        ];
                    }


                    $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                   "ActionOption" => $option_arr]);
                    return $html;
                } else {
                    return CommonLanguage::getMessage('void');
                }
            }
        );

        $columns = array(
            array('db' => 'ID', "formatter" => function($d) {
                return $d;
                //                    return '<input type="checkbox" class=" pull-left multi_rec"/>' . $d;
            }),
            array('db' => 'Name', "formatter" => function($d) {
                return $d == '' ? '-- --' : $d;
            }), 'customer_mobile',
            'Delivery_Time', 'driver_name', 'region_name',
            'pos_customer_address',
            array('db' => 'net_with_ship', "formatter" => function($d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            }),
            array('db' => 'Invoice_Shipping', "formatter" => function($d, $row) {
                return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
            }),
            array('db' => 'Invoice_Paid_Amount', "formatter" => function($d, $row) {
                return (CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol']);
            }),
            array('db' => 'received_date', 'formatter' => function($d) {
                return '<span class="label ' . (empty($d) ? "label-warning" : "label-info") . '" >' . CommonLanguage::getMessage(empty($d) ? 'no' : 'yes') . '</span>';
            }), 'received_note'
        );

        $columns = array_merge($columns, array($actions_col, 'ID_Auto', 'Currency_Symbol', 'table_id', 'posponted_type', 'is_branch_transfer', 'invoice_app_id', 'is_main_transfer', 'Is_Closed', 'reason_id'));
        //
        $key = 'ID_Auto';
        $table = 'invoice_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function change_inv_rec() {
        $update = $this->_registry->Invoice->change_inv_rec_date($_POST['inv_id'], $_POST['status']);
        die(empty($update) ? 'OK' : 'error');
    }

    public function change_inv_rec_note() {
        $update = $this->_registry->Invoice->change_inv_rec_note($_POST['inv_id'], $_POST['note']);
        die(empty($update) ? 'OK' : 'error');
    }

    public function getTotalOrders() {
        $total_orders = $this->_registry->purchase->get_pending_order_count();
        die($total_orders['official']);
    }

    public function pay_rec_list_ajax() {
        $_GET['tmp__all_ids'] = array();
        $cond = ' is_pos=1 and is_return=0 ';
        if (isset($_GET['is_actual']))
            $cond .= ' and status_ID = "' . $_GET['is_actual'] . '" ';
        //echo json_encode($this->permissions->hasPermission('view_all_pos_invoices'));
        //die('ok');
        if (($_GET['is_receipt'] == 0 && !$this->permissions->hasPermission('pos_view_all_payments')) || ($_GET['is_receipt'] == 1 && !$this->permissions->hasPermission('pos_view_all_receipts'))) {
            $cond .= ' and Logged_ID = "' . smc_session()['user_logged_id'] . '"';
        }
        if (!empty($_GET['Date_From']) && !empty($_GET['Date_To'])) {
            $cond .= ' and payment_date between  "' . $_GET['Date_From'] . '"  and  "' . $_GET['Date_To'] . '" ';
        }
        if (isset($_GET['is_receipt']))
            $cond .= ' and IsReceipt = "' . $_GET['is_receipt'] . '" ';


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

        $columns = array('ID',
                         array('db' => 'Account_Name', 'formatter' => function($d, $row) {
                             return !empty($row['pos_customer_name']) ? $row['pos_customer_name'] : $d;
                         }), 'Payment_Date', 'Payment_Note',
                         array('db' => 'Payment_Amount', 'formatter' => function($d, $row) {
                             return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                         }),
                         array(
                             'db' => 'Payment_Auto_ID',
                             'formatter' => function( $d, $row) {
                                 $option_arr = [];
                                 if (empty($row['payment_app_id']) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {
                                     $option_arr[] = ["title" => CommonLanguage::getMessage('print'),
                                                      "class" => "print_receipt_payment",
                                                      "attr" => " data-id='" .$d. "' data-type='".$_GET['is_receipt']."' ",
                                                      'permission' => ($_GET['is_receipt'] == 1 ? 'pos_print_receipt' : 'pos_print_payment'),
                                                      "icon" => "fa-print",
                                                     ];
                                     $option_arr[] = ["title" => CommonLanguage::getMessage('delete'),
                                                      "class" => ($_GET['is_receipt'] == 1 ? "delete_rec" : "delete_pay"),
                                                      "attr" => " data-inv-linked='" . (!empty($_GET['tmp__all_ids'][$row['Payment_Auto_ID']]) ? 1 : 0) . "' ",
                                                      'permission' => ($_GET['is_receipt'] == 1 ? 'pos_delete_receipt' : 'pos_delete_payment'),
                                                      "icon" => "fa-trash",
                                                     ];
                                     $option_arr[] = ["title" => CommonLanguage::getMessage('Edit'),
                                                      "class" => "edit_pay_rec",
                                                      "permission" => ($_GET['is_receipt'] == 1 ? 'pos_delete_receipt' : 'pos_delete_payment'),
                                                      "icon" => "fa-pencil",
                                                     ];
                                 }

                                 $html = Forms::action_snippet(["color" => " btn-info", "isDropDown" => true, "data_id" => $d,
                                                                "ActionOption" => $option_arr]);
                                 return $html;
                             }
                         ), 'Currency_Symbol', 'pos_customer_name'
                        );
        $key = 'Payment_Auto_ID';
        $table = 'payment_list';
        $row_cb = array();
        //                                                                                                                        if ($_GET['is_receipt'] == 1) {
        $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'pay_rec_list_ftch_row']]
                   , 'fetch_all_callback' => ['ft' => [$this, 'pay_rec_list_ftch_all']]];
        //                                                                                                                        }
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, $row_cb);
        echo json_encode($data);
    }

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

    public function pay_rec_list_ftch_all(&$data) {
        if (empty($_GET['tmp__all_ids']))
            return true;
        $query = $this->db->query('SELECT record_id FROM tbl_invoice_payments
                                                                                                                                where record_id in (' . implode(',', array_keys($_GET['tmp__all_ids'])) . ') and type in ("rec","pay")');
        while ($row = $this->db->assoc($query)) {
            $_GET['tmp__all_ids'][$row['record_id']] = true;
        }
    }

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

    public function get_prod_options() {
        $data = $this->_registry->product->get_prod_options($_GET['product_id']);
        die(json_encode($data));
    }
    public function OpenCashDrawer() {
        $insert = $this->_registry->Invoice->OpenCashDrawer();
        die(empty($insert) ? 'OK' : 'error');
    }

}
