<?php

class restaurant_pos {

    protected $info = array();

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
        $this->year_id = Session::getCurrentYearID();
        $this->year_id_actual = Session::getCurrentYearIDActual();
        $this->permission = Session::getPermissionsObject();
        $this->invoice = new InvoiceposSMCCustom();
    }

    public function setData(array $data) {
        $this->info = $data;
        return $this;
    }

    public function submitVoidInvoice() {
        $id = $this->info['Invoice_ID_Auto'];
        $this->db->query('START TRANSACTION');
        $status_parameter = '';
        $q_r = $this->db->query('SELECT Related_Tables,invoice_type,Invoice_Currency FROM tbl_invoices where Invoice_ID_Auto ="' . $id . '"');
        $invoice_row = $this->db->assoc($q_r);
        if ($invoice_row['invoice_type'] != 2 || $invoice_row['invoice_type'] != 3)
            $this->invoice->setData(['Currency_ID' => $invoice_row['Invoice_Currency']])->edit_old_details_qty_cost($id, 1);
        if ($invoice_row['invoice_type'] == 4)
            $status_parameter = ',Invoice_Status =2';
        $updatedate = date("Y-m-d H:i:s");
        $logged_id = smc_session()['user_logged_id'];
        $this->db->prepare_Stmt('delete from tbl_invoice_products_details where Invoice_ID_Auto= ? ', [&$id]);
        $this->db->prepare_Stmt('update tbl_invoices set invoice_void_total = Invoice_Net_Total,Invoice_Sub_Total = 0,Invoice_Net_Total =0,
            Invoice_Paid_Amount=0,Invoice_Shipping=0,Is_Closed=1,reason_id=?,void_time= ? ,Invoice_VAT=0,vat1_total = 0,vat2_total= 0,
            Invoice_Discount = 0,discount_amount = 0,
            date_time = ?,Logged_ID = ? ,is_main_transfer = 0' . $status_parameter . '
            where Invoice_ID_Auto= ? ', [&$this->info['reason_id'], &$updatedate, &$updatedate, &$logged_id, &$id]);
        $this->db->prepare_Stmt('delete from tbl_accounting_transactions where main_id= ? and main_type= "inv" ', [&$id]);
        $related_tables = $invoice_row['Related_Tables'];
        if (!empty($related_tables)) {
            $this->db->prepare_Stmt('UPDATE tbl_invoices 
                                    SET
                                        Is_Closed = 1,date_time = ?,Logged_ID = ?
                                    WHERE 
                                        table_id in (' . $related_tables . ')
                                    and 
                                        Is_Closed = 0
                        ', [&$updatedate, &$logged_id]);
        }
        CommonBusiness::update_trans_record_current('inv', $id);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function SubmitRestaurantFloor() {
        $flag = $this->info['floor_flag'];
        if ($flag == 0) {
            $this->db->prepare_Stmt('INSERT INTO tbl_floor
                                     (floor_name,employee_id)
                                     VALUES
                                    (?,?)
                                         ', [&$this->info['floor_name'], &$this->info['employee_id']]);
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_floor
                                                 SET
                                                        floor_name =?,employee_id = ?
                                                 WHERE 
                                                        floor_id =?

                                         ', [&$this->info['floor_name'], &$this->info['employee_id'], &$this->info['floor_id']]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function submitVoidReason() {
        $flag = $this->info['reason_flag'];
        if ($flag == 0) {
            $this->db->prepare_Stmt('INSERT INTO tbl_void_reason
                                     (reason_title,reason_type)
                                     VALUES
                                    (?,?)
                                         ', [&$this->info['reason_title'], &$this->info['reason_type']]);
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_void_reason
                                                 SET
                                                        reason_title =?,
                                                        reason_type = ?
                                                 WHERE 
                                                        reason_id =?

                                         ', [&$this->info['reason_title'], &$this->info['reason_type'], &$this->info['reason_id']]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function deleteVoidReason() {
        $this->db->prepare_Stmt('Delete from tbl_void_reason WHERE reason_id =? ', [&$this->info['entry_value']]);
        $error = $this->db->error();
        return $error;
    }

    public function submitKitchenNote() {
        $note_id = $this->info['note_id'];
        if ($note_id == 0) {
            $this->db->prepare_Stmt('INSERT INTO tbl_kitchen_note
                                     (note_title,type)
                                     VALUES
                                    (?,?)
                                         ', [&$this->info['note_title'], $this->info['type']]);
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_kitchen_note
                                                 SET
                                                        note_title =?,type=?
                                                 WHERE 
                                                        note_id =?

                                         ', [&$this->info['note_title'], $this->info['type'], &$note_id]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function deleteKitchenNote() {
        $this->db->prepare_Stmt('Delete from tbl_kitchen_note WHERE note_id =? ', [&$this->info['entry_value']]);
        $error = $this->db->error();
        return $error;
    }

    public function SubmitRestaurantTable() {
        $flag = $this->info['table_flag'];
        if ($flag == 0) {

            $this->db->prepare_Stmt('INSERT INTO tbl_table
                                     (table_name,table_alias_name,floor_id,employee_id,is_radius)
                                     VALUES
                                    (?,?,?,?,?)
                                         ', [&$this->info['table_name'], &$this->info['table_alias_name'],
                &$this->info['floor_id'], &$this->info['employee_id'], &$this->info['is_radius']]);
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_table
                                                 SET
                                                        table_name =?,
                                                        employee_id =?,
                                                        table_alias_name =?,
                                                        is_radius = ?
                                                 WHERE 
                                                        table_id =?

                                         ', [&$this->info['table_name'],&$this->info['employee_id'], &$this->info['table_alias_name'], &$this->info['is_radius'],
                &$this->info['table_id']]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function updateAliasTableName() {
        $this->db->prepare_Stmt('UPDATE tbl_table
                                                 SET
                                                        table_alias_name =?
                                                 WHERE 
                                                        table_id =?

                                         ', [&$this->info['table_alias_name'],
            &$this->info['table_id']]);

        $error = $this->db->error();
        return $error;
    }

    public function available_tables() {
        $data = array();
        $employee_id =smc_session()['user_details']['Employee_ID'];
        $is_admin = '';
        if(smc_session()['default_setting']['enable_user_floors'] == 1){
            if(!$this->permission->hasPermission('all_floor')){
                $is_admin = smc_session()['user_details']['is_admin'] == 1 ? '':" and floor.employee_id LIKE '%$employee_id%' ";
                $for_table = smc_session()['user_details']['is_admin'] == 1 ? '':" and tabl.employee_id LIKE '%$employee_id%' ";
            }
        }

        $tables_query = $this->db->query('SELECT
                                            tabl.*,
                                            users.User_Name AS user_name,
                                            inv.Invoice_ID_Auto,
                                            inv.Invoice_Net_Total,
                                            floor.employee_id,
                                            SUBSTRING(inv.date_time, 11) AS cur_time
                                        FROM
                                            tbl_table tabl
                                        LEFT JOIN tbl_common_users users ON
                                            users.User_ID = tabl.user_id
                                        LEFT JOIN tbl_floor floor ON
                                            floor.floor_id = tabl.floor_id 
                                        LEFT JOIN tbl_invoices inv ON
                                            (
                                                inv.table_id = tabl.table_id AND inv.Is_Closed = 0
                                            )
                                        WHERE
                                            tabl.status_id <> 0 
                                          '.$is_admin.$for_table);
        while ($row = $this->db->assoc($tables_query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function getRelatedTables() {
        $data = array();
        $query = $this->db->query('select * from tbl_table where floor_id = "' . $this->info['floor_id'] . '" and status_id <> 0');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function get_all_tables_reserved() {
        $data = array();
        $floor_ids = array();
        $employee_id =smc_session()['user_details']['Employee_ID'];
        $is_admin = '';
        $for_table = '';
        if(smc_session()['default_setting']['enable_user_floors'] == 1){
            if(!$this->permission->hasPermission('all_floor')){
                $is_admin = smc_session()['user_details']['is_admin'] == 1 ? '':"and employee_id LIKE '%$employee_id%' ";
                $for_table = smc_session()['user_details']['is_admin'] == 1 ? '':"and tabl.employee_id LIKE '%$employee_id%' ";
            }
        }

        $floors_query = $this->db->query("SELECT floor_id,floor_name FROM tbl_floor WHERE status_id = 1 $is_admin  ");
        while ($row = $this->db->assoc($floors_query)) {
            $data[$row['floor_id']] = $row;
            $floor_ids[] = $row['floor_id'];
        }
        $floors = implode(',', $floor_ids);
        if (!empty($floors)) {
            $tables_query = $this->db->query('SELECT 
                                                tabl.*,
                                                inv.is_printed,
                                                users.User_Name AS user_name,
                                                inv.Invoice_ID_Auto,
                                                inv.Invoice_Net_Total,
                                                substring(inv.date_time,11) As cur_time
                                          FROM 
                                                tbl_table  tabl
                                          left join 
                                                tbl_common_users users
                                          on
                                                users.User_ID = tabl. user_id 
                                         left join
                                                tbl_invoices inv
                                         on (  inv.table_id = tabl.table_id
                                        and 
                                                inv.Is_Closed = 0)

                                          WHERE
                                                tabl.status_id <> 0
                                          and 
                                                floor_id IN (' . $floors . ') ' . $for_table . '
                                        order by tabl.table_id asc
                                               ');
            while ($row = $this->db->assoc($tables_query)) {
                $data[$row['floor_id']]['tables'][] = $row;
            }
        }
        return $data;
    }

    public function get_all_tables() {
        $condition = '';
        $data = array();
        $floor_ids = array();
        $table_ids = '';
        $related_query = $this->db->query('SELECT * FROM tbl_invoices where Is_Closed = 0 and Related_Tables <> "" ');
        while ($row1 = $this->db->assoc($related_query)) {
            $table_ids .= $row1['Related_Tables'] . ',';
        }
        $current_unneeded = rtrim($table_ids, ",");
        if (!empty($current_unneeded) && ($this->info['type_id'] == 3 || $this->info['type_id'] == 1)) {
            $condition .=' and table_id NOT IN (' . $current_unneeded . ')';
        }
        $floors_query = $this->db->query('SELECT floor_id,floor_name FROM tbl_floor WHERE status_id = 1');
        while ($row = $this->db->assoc($floors_query)) {
            $data[$row['floor_id']] = $row;
            $floor_ids[] = $row['floor_id'];
        }
        $floors = implode(',', $floor_ids);
        $tables_query = $this->db->query('SELECT 
                                                *
                                          FROM 
                                                tbl_table 
                                          where 
                                                floor_id IN (' . $floors . ')
                                          ' . $condition . '
                                          and table_id <> "' . $this->info['table_id'] . '"
                                          and status_id ' . (($this->info['type_id'] == 1 || $this->info['type_id'] == 2) ? ' IN (1,2)' : ' = 2' ));
        while ($row = $this->db->assoc($tables_query)) {
            if ($row['status_id'] == 1) {
                $row['is_printed'] = 0;
            } else {
                $invoice_query = $this->db->query("SELECT is_printed FROM tbl_invoices WHERE table_id = '" . $row['table_id'] . "' and Is_Closed=0 ORDER BY Invoice_Date DESC LIMIT 1");
                $row['is_printed'] = $this->db->assoc($invoice_query)['is_printed'];
            }
            $data[$row['floor_id']]['tables'][] = $row;
        }
        return $data;
    }

    public function getInvoiceByTable($id) {
        $data = array();
        //select main data for invoice for main table or related tables
        $main_query = $this->db->query('SELECT * FROM pos_invoices WHERE (table_id = "' . $id . '" or concat(",",Related_Tables,",") like "%,' . $id . ',%")  and Is_Closed = 0 ORDER BY Invoice_Date DESC');
        $count = $this->db->rowsno($main_query);
        if ($count > 1) {
            // in case of merging tables then we need to make sure of selecting data for main invoice
            //the selected table has two cases: either it is the main table or it is a table merged on another table
            // first assoc we compare if it is the main table if nt the we take the second row for the selected invoice
            $main_arr = $this->db->assoc($main_query);
            if ($id <> $main_arr['table_id'])
                $main_arr = $this->db->assoc($main_query);
        } else
            $main_arr = $this->db->assoc($main_query);
        $data['main_invoice'] = $main_arr;
        $data['invoice_details'] = array();
        $tmp_uoms_arr = array();
        $query = $this->db->query('SELECT inv.*,
                                    concat(inv.Product_ID,inv.UOM_ID) as unq,
                                    inv.Product_Net_Price*inv.conversion_amount as Product_Net_Price,
                                    detail.criteria_detail_id,
                                    detail.criteria_detail_name,
                                    detail.criteria_detail_price
                                    FROM invoice_details inv
                                    left join tbl_invoice_product_criteria criteria using (`Entery_ID`) 
                                    left join tbl_product_criteria_detail detail using (`criteria_detail_id`) 
                                  where `Invoice_ID_Auto` = "' . $data['main_invoice']['Invoice_ID_Auto'] . '"
                                  ');
        while ($row = $this->db->assoc($query)) {
            if (!isset($data['invoice_details'][$row['Entery_ID']])) {
                $data['invoice_details'][$row['Entery_ID']] = $row;
                if (!isset($tmp_uoms_arr[$row['Product_ID']])) {
                    $sub = $this->db->query("select group_concat(u.uom_from) as all_uoms, Product_ID from tbl_uom_conversions u where u.Product_ID='" . $row['Product_ID'] . "' group by u.Product_ID");
                    $uom_row = $this->db->assoc($sub);
                    $tmp_uoms_arr[$uom_row['Product_ID']] = $uom_row['all_uoms'];
                }

                $data['invoice_details'][$row['Entery_ID']]['all_uoms'] = isset($tmp_uoms_arr[$row['Product_ID']]) ? $tmp_uoms_arr[$row['Product_ID']] : '';
            }
            if (!is_null($row['criteria_detail_id'])) {
                $details = ["criteria_detail_id" => $row['criteria_detail_id'],
                    "criteria_detail_name" => $row['criteria_detail_name'],
                    "criteria_detail_price" => $row['criteria_detail_price']
                ];
                $data['invoice_details'][$row['Entery_ID']]['tag_split'] [] = $details;
            }
        }
        return $data;
    }

    public function transferTable() {
        $status = $this->info['status_id'];
        $this->db->query('START TRANSACTION');
        $mydate = date("Y-m-d H:i:s");
        $logged_id = smc_session()['user_logged_id'];
        //first we must edit invoice to make sure we included all changes made by the user
        $error = $this->invoice->setData($this->info)->editInvoice(true);
        if (!empty($error)) {
            $this->db->query('ROLLBACK');
            return array_unique($error);
        }
        $query_id = $this->db->query("SELECT * FROM tbl_invoices WHERE table_id = '" . $this->info['table_id'] . "' and Is_Closed = 0 ORDER BY Invoice_Date DESC LIMIT 1");
        $old_data = $this->db->assoc($query_id);
        $old_id = $old_data['Invoice_ID_Auto'];
        $realted_tables = $old_data['Related_Tables'];
        if (!empty($realted_tables))
            $this->db->prepare_Stmt("UPDATE tbl_invoices SET Is_Closed=1, date_time = ?,Logged_ID = ?,is_main_transfer = 0
                WHERE table_id in (" . $realted_tables . ") and Is_Closed = 0 ", [&$mydate, &$logged_id]);

        //$status if new table available or nt--->1 available;2 reserved
        if ($status == 1) {
            // in case new table available then we just update table id in main invoice
            $this->db->prepare_Stmt("UPDATE tbl_invoices SET table_id = ?, Related_Tables = '' , date_time = ?,Logged_ID = ?,is_main_transfer = 0
                WHERE Invoice_ID_Auto = ?", [&$this->info['new_table_id'], &$mydate, &$logged_id, &$old_id]);
        } else {
            // in case new table reserved then we update main invoice for new invoice with adding data invoice from old table then we update product details to new table invoice id
            $this->db->prepare_Stmt("UPDATE tbl_invoices SET Invoice_Sub_Total=0,Invoice_Discount=0,Invoice_Net_Total=0,
                Invoice_VAT=0,Payment_Paid_Amount=0,Invoice_Paid_Amount=0,Is_Closed=1, date_time = ?,Logged_ID = ? ,is_main_transfer = 0
                WHERE Invoice_ID_Auto = ?", [&$mydate, &$logged_id, &$old_id]);
            $query_id2 = $this->db->query("SELECT Invoice_ID_Auto FROM tbl_invoices WHERE table_id = '" . $this->info['new_table_id'] . "' and Is_Closed=0 ORDER BY Invoice_Date DESC LIMIT 1");
            $new_id = $this->db->assoc($query_id2)['Invoice_ID_Auto'];
            $data = [
                &$old_data['Invoice_Sub_Total'],
                &$old_data['Invoice_Discount'],
                &$old_data['Invoice_Net_Total'],
                &$old_data['Invoice_VAT'],
                &$mydate,
                &$logged_id,
                &$new_id
            ];
            $this->db->prepare_Stmt("UPDATE 
                                        tbl_invoices 
                                    SET 
                                        Invoice_Sub_Total = Invoice_Sub_Total + ?,
                                        Invoice_Discount = Invoice_Discount + ?,
                                        Invoice_Net_Total = Invoice_Net_Total + ?,
                                        Invoice_VAT = Invoice_VAT + ?,
                                        date_time = ?,
                                        Logged_ID = ?,is_main_transfer = 0
                                    WHERE 
                                        Invoice_ID_Auto = ?
                    ", $data);
            $this->db->prepare_Stmt("UPDATE tbl_invoice_products_details SET Invoice_ID_Auto=? WHERE Invoice_ID_Auto = ?", [&$new_id, &$old_id]);
        }
        $error = $this->db->error();
        //        die(print_r($error));
        if (empty($error)) {
            $data = $this->invoice->getData();
            if (!empty($data['edited_array'])) {
                $this->invoice->printRemovedDeleted($data['edited_array']);
            }
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function transferItems() {
        //transfer cases:
        //transfer items to available table---> create new invoice
        //transfer items to reserved table---> no new invoice
        //transfer part of quantity
        $this->db->query('START TRANSACTION');
        //first we must edit invoice to make sure we included all changes made by the user
        //        $invoice = new Invoicepos();
        $error = $this->invoice->setData($this->info)->editInvoice(true);
        if (!empty($error)) {
            $this->db->query('ROLLBACK');
            return array_unique($error);
        }

        $this->info = $this->invoice->getData();
        $Invoice_Discount = $this->info['Invoice_Discount'];
        $query_id = $this->db->query("SELECT Invoice_ID_Auto,Related_Tables FROM tbl_invoices WHERE table_id = '" . $this->info['table_id'] . "' and Is_Closed = 0 ORDER BY Invoice_Date DESC LIMIT 1");
        $data_old = $this->db->assoc($query_id);
        $old_id = $data_old['Invoice_ID_Auto'];
        $related_old_tables = $data_old['Related_Tables'];
        $related_tables_array = array();
        $is_actual = 0;
        $mydate = date("Y-m-d H:i:s");
        //        1->new table available, 2-> old table reserved
        if ($this->info['status_id'] == 1) {
            $sales_account = smc_session()['user_accounts']['sales_account_id'];

            //status:
            //0->unpaid
            //1->partially_paid
            //2->paid
            //3->ordered
            //4->returned
            //5->on road
            //6-> cancelled
            $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);
            //if new table is available them we must create invoice for it
            $today = Date::getToday();
            $bone_nb = $this->invoice->getBonNum($today);
            $Customer_ID = $this->info['Customer_ID'];
            $Invoice_Due_Date = $today;
            $Invoice_Sub_Total = 0;

            $Invoice_Net_Total = 0;
            $Invoice_VAT = 0;
            $Invoice_Currency = $this->info['Invoice_Currency'];

            $status = $this->info['Invoice_Status'];
            $inv_type = $this->info['invoice_type'];
            $temp_error = ["1"];
            $this->info['Invoice_Description'] = 'Transfer items from table to another';
            $Sales_ID = $this->info['Sales_ID'];
            $query_branch = $this->db->query('select branch_prefix from tbl_organization_branches where branch_id = "' . $branch_id . '"');
            $branch_prefix = $this->db->assoc($query_branch)['branch_prefix'];
            $this->info['rate'] = CurrencyFactory::getLastExRate($Invoice_Currency);
            $prefix = smc_session()['user_accounts']['serial_prefix'] ? smc_session()['user_accounts']['serial_prefix'] : $branch_prefix;
            $a = 0;
            if ($this->info['pending_status'] == 3) {
                $status = 3;
            }
            $inv_num = $this->invoice->getMaxInvoice($prefix, $is_actual);
            //            while (!empty($temp_error)) {
            $pos_customer_id = $this->info['pos_customer_id'] == 0 ? null : $this->info['pos_customer_id'];
            $Discount_Amount = $this->info['Discount_Amount'];
            $Delivery_Time = $this->info['Delivery_Time'];
            $is_delivery = $this->info['is_delivery'];
            $Invoice_Shipping = $this->info['Invoice_Shipping'];
            $inv_num = $inv_num + $a;
            $bone_nb = $bone_nb + $a;

            $data = [
                &$inv_num,
                &$bone_nb,
                &$Customer_ID,
                &$Sales_ID,
                &$today,
                &$Invoice_Currency,
                &$Invoice_VAT,
                &$Invoice_Sub_Total,
                &$Invoice_Discount,
                &$Discount_Amount,
                &$Invoice_Net_Total,
                &$Invoice_Due_Date,
                &$mydate,
                &$mydate,
                &$this->info['Logged_ID'],
                &$this->info['Logged_ID'],
                &$this->year_id,
                &$this->info['Invoice_Description'],
                &$status,
                &$Invoice_Shipping,
                &$this->info['rate'],
                &$inv_type,
                &$Delivery_Time,
                &$is_delivery,
                &$this->info['Logged_ID'],
                &$this->info['new_table_id'],
                &$this->info['Paid_Amount'],
                &$depot_id,
                &$branch_id,
                &$prefix,
                &$this->info['Class_ID'],
                &$pos_customer_id,
                &$sales_account,
                &$is_actual
            ];
            $this->db->prepare_Stmt("INSERT INTO tbl_invoices (
                                                        Invoice_ID,
                                                        Bon_Number,
                                                        Customer_ID, 
                                                        Sales_ID, 
                                                        Invoice_Date,
                                                        Invoice_Currency,
                                                        Invoice_VAT,
                                                        Invoice_Sub_Total,
                                                        Invoice_Discount, 
                                                        discount_amount, 
                                                        Invoice_Net_Total,
                                                        Invoice_Due_Date,
                                                        date_time,date_created,
                                                        Logged_ID,created_logged_id,
                                                        current_year_id,
                                                        Invoice_Description,
                                                        Invoice_Status,
                                                        Invoice_Shipping,
                                                        current_rate,
                                                        Inv_Type,
                                                        Delivery_Time,
                                                        Is_Delivery,
                                                        Close_ID,
                                                        table_id,
                                                        Invoice_Paid_Amount,
                                                        Depot_ID,
                                                        branch_id,
                                                        invoice_prefix,
                                                        Class_ID,
                                                        pos_customer_id,
                                                        Account_ID,
                                                        is_actual,
                                                        invoice_type
                                                        ) 
                                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,4)

                                ", $data);
            //            $temp_error = $this->db->error();
            //                $a++;
            //            }
            $new_id = $this->db->id();
            $Invoice_Discount_new = $this->info['Invoice_Discount'];
        } else {
            if (!empty($related_old_tables)) {
                $related_tables_array = explode(',', $related_old_tables);
                if (($key = array_search($this->info['new_table_id'], $related_tables_array)) !== false) {
                    unset($related_tables_array[$key]);
                    $related_old_tables = implode(',', $related_tables_array);
                }
            }
            $query_id2 = $this->db->query("SELECT Invoice_ID_Auto,Invoice_Discount,Depot_ID,branch_id 
                FROM tbl_invoices WHERE table_id = '" . $this->info['new_table_id'] . "' 
                    and Is_Closed = 0 ORDER BY Invoice_Date DESC LIMIT 1");
            $row2 = $this->db->assoc($query_id2);
            $new_id = $row2['Invoice_ID_Auto'];
            $Invoice_Discount_new = $row2['Invoice_Discount'];
            $depot_id = $row2['Depot_ID'];
            $branch_id = $row2['branch_id'];
        }
        $total_prod = 0.0;
        foreach ($this->info['products'] as $item) {
            if ($item['is_transfer'] == 1 && $item['transfered_quantity'] > 0) {
                if ($item['transfered_quantity'] < $item['Product_Quantity'] and $item['transfered_quantity'] > 0) {
                    //if transfered quantity less than main quantity
                    $ProductID = $item["Product_ID"];
                    $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item["transfered_quantity"], $ProductID);
                    $ProductDiscount = $item["Product_Disc"];
                    $ProductNetPrice = $item["Net_Price"];
                    $Product_Total_Price = $item["transfered_quantity"] * $ProductNetPrice;
                    $transf_disc = ($item["transfered_quantity"] * $ProductDiscount) / 100;
                    $transf_added_amount = array_key_exists("Added_Amount", $item) ? ($item["Added_Amount"] * $item["transfered_quantity"]) : 0;
                    $item_depot_id = !empty($item['depot_id']) ? $item['depot_id'] : $depot_id;
                    $prod = [
                        &$new_id,
                        &$ProductID,
                        &$ProductDiscount,
                        &$ProductNetPrice,
                        &$ProductQuantity,
                        &$Product_Total_Price,
                        &$item["transfered_quantity"],
                        &$item["UOM_ID"],
                        &$transf_disc,
                        &$transf_added_amount,
                        &$item_depot_id
                    ];
                    //insert transfered amount to new sales invoice based on new table
                    $this->db->prepare_Stmt("INSERT INTO tbl_invoice_products_details (
                                                                            Invoice_ID_Auto,
                                                                            Product_ID,
                                                                            Product_Discount, 
                                                                            Product_Net_Price,
                                                                            Product_Quantity,
                                                                            Product_Total_Price,
                                                                            Item_Quantity_Current,
                                                                            UOM_ID,
                                                                            Discount_Amount,
                                                                            Added_Amount,depot_id
                                                                            ) 
                                                                        VALUES (
                                                                            ?,?,?,?,?,?,?,?,?,?,?
                                                                            )
                        ", $prod);

                    if (array_key_exists('criteria_details', $item)) {
                        $detail_id = $this->db->id();
                        $item['criteria_details']['id'] = $detail_id;
                        Invoicepos::addInvDetailTags($item['criteria_details']);
                    }
                    $prod_update = [
                        &$ProductDiscount,
                        &$ProductQuantity,
                        &$Product_Total_Price,
                        &$item["transfered_quantity"],
                        &$item["UOM_ID"],
                        &$transf_disc,
                        &$transf_added_amount,
                        &$item['Entery_ID']
                    ];
                    //update quantities in old invoice
                    $this->db->prepare_Stmt("UPDATE 
                                                tbl_invoice_products_details
                                            SET
                                                Product_Discount = Product_Discount - ?, 
                                                Product_Quantity = Product_Quantity -?,
                                                Product_Total_Price = Product_Total_Price -?,
                                                Item_Quantity_Current = Item_Quantity_Current - ?,
                                                UOM_ID = ?,
                                                Discount_Amount = Discount_Amount - ?,
                                                Added_Amount = Added_Amount - ?
                                            WHERE
                                                Entery_ID = ?

                        ", $prod_update);
                } elseif ($item['transfered_quantity'] == $item['Product_Quantity']) {
                    //if transfered quantity equal to main quantity then we just update product details to new invoice id
                    //$Product_Total_Price = $item["Total_Price"];
                    $ProductNetPrice = $item["Net_Price"];
                    $Product_Total_Price = $item["transfered_quantity"] * $ProductNetPrice;

                    $prod_update = [

                        &$new_id,
                        &$item['Entery_ID']
                    ];
                    $this->db->prepare_Stmt("UPDATE 
                                                tbl_invoice_products_details
                                            SET
                                                Invoice_ID_Auto = ?
                                            WHERE
                                                Entery_ID = ?

                        ", $prod_update);
                }
                $total_prod += $Product_Total_Price;
            }
        }
        $Invoice_Net_old = $total_prod - ($total_prod * $Invoice_Discount);
        $Invoice_Net_new = $total_prod - ($total_prod * $Invoice_Discount_new);

        //old order
        $data = [
            &$total_prod,
            &$Invoice_Net_old,
            &$related_old_tables, &$mydate, &$this->info['Logged_ID'],
            &$old_id
        ];
        $this->db->prepare_Stmt("UPDATE tbl_invoices 
                                        SET

                                                Invoice_Sub_Total = Invoice_Sub_Total - ?,
                                                Invoice_Net_Total = Invoice_Net_Total - ?,
                                                Related_Tables=?,date_time=?,Logged_ID = ?,is_main_transfer = 0
                                        WHERE 
                                                Invoice_ID_Auto = ?

                        ", $data);

        //new order
        $data2 = [
            &$total_prod,
            &$Invoice_Net_new, &$mydate, &$this->info['Logged_ID'],
            &$new_id
        ];
        $this->db->prepare_Stmt("UPDATE tbl_invoices 
                                        SET

                                                Invoice_Sub_Total = Invoice_Sub_Total + ?,
                                                Invoice_Net_Total = Invoice_Net_Total + ?,date_time=?,Logged_ID = ?,is_main_transfer = 0
                                        WHERE 
                                            Invoice_ID_Auto = ?

                        ", $data2);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
            $data = $this->invoice->getData();
            if (!empty($data['edited_array'])) {
                $this->invoice->printRemovedDeleted($data['edited_array']);
            }
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function mergeTables() {
        //get related tables from selecting merge table
        $query_id = $this->db->query("SELECT Invoice_ID_Auto,Related_Tables FROM tbl_invoices WHERE table_id = '" . $this->info['table_id'] . "' and Is_Closed = 0 ORDER BY Invoice_Date DESC LIMIT 1");
        $old_row = $this->db->assoc($query_id);
        $old_id = $old_row['Invoice_ID_Auto'];
        $old_related_tables = $old_row['Related_Tables'];
        $mydate = date("Y-m-d H:i:s");
        $logged_id = smc_session()['user_logged_id'];
        //include current table to related tables to be set in main merged on table
        if (!empty($old_related_tables))
            $old_related_tables .= ',' . $this->info['table_id'];
        else
            $old_related_tables = $this->info['table_id'];
        $query = $this->db->query("SELECT * FROM tbl_invoices WHERE Invoice_ID_Auto = '" . $old_id . "' ");
        $old_data = $this->db->assoc($query);
        //set zero values to old invoices related to tables old
        $this->db->prepare_Stmt("UPDATE tbl_invoices SET Invoice_Sub_Total=0,Invoice_Discount=0,Invoice_Net_Total=0,"
                . "Invoice_VAT=0,Related_Tables='',Invoice_Paid_Amount=0,date_time = ?,Logged_ID = ?,is_main_transfer = 0
                    WHERE Invoice_ID_Auto = ?", [&$mydate, &$logged_id, &$old_id]);
        $query_id2 = $this->db->query("SELECT Invoice_ID_Auto,Related_Tables FROM tbl_invoices WHERE table_id = '" . $this->info['new_table_id'] . "' and Is_Closed = 0 ORDER BY Invoice_Date DESC LIMIT 1");
        $new_row = $this->db->assoc($query_id2);
        $new_id = $new_row['Invoice_ID_Auto'];
        $new_related_tables = $new_row['Related_Tables'];
        //concat old related tables to related tables in new invoice
        if (!empty($new_related_tables))
            $new_related_tables .= ',' . $old_related_tables;
        else
            $new_related_tables = $old_related_tables;
        $data = [
            &$old_data['Invoice_Sub_Total'],
            &$old_data['Invoice_Discount'],
            &$old_data['Invoice_Net_Total'],
            &$old_data['Invoice_VAT'],
            &$new_related_tables, &$mydate, &$logged_id,
            &$new_id
        ];
        //add total from old table to new table and set all related tables in new table
        $this->db->prepare_Stmt("UPDATE 
                                    tbl_invoices 
                                SET 
                                    Invoice_Sub_Total = Invoice_Sub_Total + ?,
                                    Invoice_Discount = Invoice_Discount + ?,
                                    Invoice_Net_Total = Invoice_Net_Total + ?,
                                    Invoice_VAT = Invoice_VAT + ?,
                                    Related_Tables = ?,date_time = ?,Logged_ID = ?,is_main_transfer = 0
                                WHERE 
                                    Invoice_ID_Auto = ?
                ", $data);
        //update product details from old invoice to new one
        $this->db->prepare_Stmt("UPDATE tbl_invoice_products_details SET Invoice_ID_Auto=? WHERE Invoice_ID_Auto = ?", [&$new_id, &$old_id]);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function getMainTable($table_id) {
        $query = $this->db->query('SELECT table_id FROM pos_invoices  WHERE concat(",",Related_Tables,",") like "%,' . $table_id . ',%" and Is_Closed = 0 '/* and Invoice_Sub_Total > 0' */);
        $row = $this->db->assoc($query);
        if (!empty($row))
            $table_id = $row['table_id'];
        return $table_id;
    }

    public function splitInvoice() {

        $this->db->query('START TRANSACTION');
        //        $invoice = new Invoicepos();
        //first we must edit data to keep all changes done by user
        $error = $this->invoice->setData($this->info)->editInvoice(true);
        if (!empty($error)) {
            $this->db->query('ROLLBACK');
            return array_unique($error);
        }

        $this->info = $this->invoice->getData();
        $query_id = $this->db->query("SELECT Invoice_ID_Auto FROM tbl_invoices WHERE table_id = '" . $this->info['table_id'] . "' AND Is_Closed = '0' ORDER BY Invoice_Date DESC LIMIT 1");
        $old_id = $this->db->assoc($query_id)['Invoice_ID_Auto'];

        $sales_account = smc_session()['user_accounts']['sales_account_id'];

        //status:
        //0->unpaid
        //1->partially_paid
        //2->paid
        //3->ordered
        //4->returned
        //5->on road
        //6-> cancelled
        $is_actual = 0;
        $depot_id = !empty(smc_session()['user_accounts']['depot_id']) ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'];
        $branch_id = CommonBusiness::getBranchByDepot($depot_id);
        //if new table is available them we must create invoice for it
        $today = Date::getToday();
        $bone_nb = $this->invoice->getBonNum($today);
        $Customer_ID = $this->info['Customer_ID'];
        $Invoice_Discount = $this->info['Invoice_Discount'];
        $Invoice_Due_Date = $today;
        $Invoice_Sub_Total = 0;
        $Invoice_Net_Total = 0;
        $Invoice_VAT = 0;
        $Invoice_Currency = $this->info['Invoice_Currency'];
        $mydate = date("Y-m-d H:i:s");
        $status = $this->info['Invoice_Status'];
        $inv_type = $this->info['invoice_type'];
        $this->info['Invoice_Description'] = 'Split items to another invoice';
        $Sales_ID = $this->info['Sales_ID'];
        $query_branch = $this->db->query('select branch_prefix from tbl_organization_branches where branch_id = "' . $branch_id . '"');
        $branch_prefix = $this->db->assoc($query_branch)['branch_prefix'];
        $this->info['rate'] = CurrencyFactory::getLastExRate($Invoice_Currency);
        $prefix = smc_session()['user_accounts']['serial_prefix'] ? smc_session()['user_accounts']['serial_prefix'] : $branch_prefix;
        //        $a = 0;
        if ($this->info['pending_status'] == 3) {
            $status = 3;
        }
        $inv_num = $this->invoice->getMaxInvoice($prefix, $is_actual);
        //            while (!empty($temp_error)) {
        $pos_customer_id = $this->info['pos_customer_id'] == 0 ? null : $this->info['pos_customer_id'];
        $new_discount_amount = 0;   //$this->info['Discount_Amount'];
        $Delivery_Time = $this->info['Delivery_Time'];
        $is_delivery = $this->info['is_delivery'];
        $Invoice_Shipping = 0;
        //        $inv_num = $inv_num ;
        //        $bone_nb = $bone_nb ;
        $this->info['main_nb'] = $inv_num;
        $second_rate = CurrencyFactory::getSecondCurrencyLastExRate($Invoice_Currency);

        $data = [
            &$inv_num,
            &$bone_nb,
            &$Customer_ID,
            &$Sales_ID,
            &$today,
            &$Invoice_Currency,
            &$Invoice_VAT,
            &$Invoice_Sub_Total,
            &$Invoice_Discount,
            &$new_discount_amount,
            &$Invoice_Net_Total,
            &$Invoice_Due_Date,
            &$mydate,
            &$mydate,
            &$this->info['Logged_ID'],
            &$this->info['Logged_ID'],
            &$this->year_id,
            &$this->info['Invoice_Description'],
            &$status,
            &$Invoice_Shipping,
            &$this->info['rate'],
            $second_rate,
            &$inv_type,
            &$Delivery_Time,
            &$is_delivery,
            &$this->info['Logged_ID'],
            &$this->info['new_table_id'],
            &$this->info['Paid_Amount'],
            &$depot_id,
            &$branch_id,
            &$prefix,
            &$this->info['Class_ID'],
            &$pos_customer_id,
            &$sales_account,
            &$is_actual
        ];
        $this->db->prepare_Stmt("INSERT INTO tbl_invoices (
                                                        Invoice_ID,
                                                        Bon_Number,
                                                        Customer_ID, 
                                                        Sales_ID, 
                                                        Invoice_Date,
                                                        Invoice_Currency,
                                                        Invoice_VAT,
                                                        Invoice_Sub_Total,
                                                        Invoice_Discount, 
                                                        discount_amount, 
                                                        Invoice_Net_Total,
                                                        Invoice_Due_Date,
                                                        date_time,date_created,
                                                        Logged_ID,created_logged_id,
                                                        current_year_id,
                                                        Invoice_Description,
                                                        Invoice_Status,
                                                        Invoice_Shipping,
                                                        current_rate,second_currency_rate,
                                                        Inv_Type,
                                                        Delivery_Time,
                                                        Is_Delivery,
                                                        Close_ID,
                                                        table_id,
                                                        Invoice_Paid_Amount,
                                                        Depot_ID,
                                                        branch_id,
                                                        invoice_prefix,
                                                        Class_ID,
                                                        pos_customer_id,
                                                        Account_ID,
                                                        is_actual,
                                                        invoice_type,is_pos
                                                        ) 
                                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,1)

                                ", $data);
        //            $temp_error = $this->db->error();
        //                $a++;
        //            }
        $new_id = $this->db->id();
        $Invoice_Discount_new = $this->info['Invoice_Discount'];
        $prod_arr = array();
        $prod_ids_arr = array();


        $subtotal_prod = 0.0;
        $total_prod = 0.0;
        foreach ($this->info['products'] as $item) {
            if ($item['is_transfer'] == 1 && $item['transfered_quantity'] > 0) {
                //split part of row
                if ($item['transfered_quantity'] < $item['Product_Quantity']) {
                    //insert splitted items to the enw invoice
                    $ProductID = $item["Product_ID"];
                    $prod_ids_arr[] = $ProductID;
                    $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item["transfered_quantity"], $ProductID);
                    $ProductDiscount = $item["Product_Disc"];
                    $ProductNetPrice = $item["Net_Price"];
                    $Product_SubTotal_Price = $item["transfered_quantity"] * $ProductNetPrice;
                    $transf_disc = ($Product_SubTotal_Price * $ProductDiscount) / 100;
                    $Product_Total_Price = $Product_SubTotal_Price - $transf_disc;
                    $tmp_inv_disc = ($Product_Total_Price * $Invoice_Discount) / 100;
                    $new_discount_amount+=$tmp_inv_disc;
                    $Product_Total_Price-= $tmp_inv_disc;
                    $transf_added_amount = array_key_exists("Added_Amount", $item) ? ($item["Added_Amount"] * $item["transfered_quantity"]) : 0;
                    $prod = [
                        &$new_id,
                        &$ProductID,
                        &$ProductDiscount,
                        &$ProductNetPrice,
                        &$ProductQuantity,
                        &$Product_Total_Price,
                        &$item["transfered_quantity"],
                        &$item["UOM_ID"],
                        &$transf_disc,
                        &$transf_added_amount,
                        $mydate
                    ];
                    $this->db->prepare_Stmt("INSERT INTO tbl_invoice_products_details (
                                                                        Invoice_ID_Auto,
                                                                        Product_ID,
                                                                        Product_Discount, 
                                                                        Product_Net_Price,
                                                                        Product_Quantity,
                                                                        Product_Total_Price,
                                                                        Item_Quantity_Current,
                                                                        UOM_ID,
                                                                        Discount_Amount,
                                                                        Added_Amount,date_created
                                                                        ) 
                                                                    VALUES (
                                                                        ?,?,?,?,?,?,?,?,?,?,?
                                                                        )
                    ", $prod);


                    if (array_key_exists('criteria_details', $item)) {
                        $detail_id = $this->db->id();
                        $item['criteria_details']['id'] = $detail_id;
                        Invoicepos::addInvDetailTags($item['criteria_details']);
                    }
                    $prod_update = [
                        &$ProductQuantity,
                        &$Product_Total_Price,
                        &$item["transfered_quantity"],
                        &$item["UOM_ID"],
                        &$transf_disc,
                        &$transf_added_amount,
                        &$item['Entery_ID']
                    ];
                    //remove splitted quantities from old invoice
                    $this->db->prepare_Stmt("UPDATE 
                                            tbl_invoice_products_details
                                        SET
                                            Product_Quantity = Product_Quantity -?,
                                            Product_Total_Price = Product_Total_Price -?,
                                            Item_Quantity_Current = Item_Quantity_Current - ?,
                                            UOM_ID = ?,
                                            Discount_Amount = Discount_Amount - ?,
                                            Added_Amount = Added_Amount - ?
                                        WHERE
                                            Entery_ID = ?

                    ", $prod_update);
                }
                //if all quantity is splitted then update product details to new invoice
                elseif ($item['transfered_quantity'] == $item['Product_Quantity']) {
                    $prod_ids_arr[] = $item["Product_ID"];
                    $Product_SubTotal_Price = $item["transfered_quantity"] * $item["Net_Price"];
                    //$Product_Total_Price = $item["Total_Price"];
                    $ProductDiscount = $item["Product_Disc"];
                    $transf_disc = ($Product_SubTotal_Price * $ProductDiscount) / 100;
                    $Product_Total_Price = $Product_SubTotal_Price - $transf_disc;
                    $tmp_inv_disc = ($Product_Total_Price * $Invoice_Discount) / 100;
                    $new_discount_amount+=$tmp_inv_disc;
                    $Product_Total_Price-= $tmp_inv_disc;
                    $prod_update = [
                        &$new_id,
                        &$item['Entery_ID']
                    ];
                    $this->db->prepare_Stmt("UPDATE 
                                            tbl_invoice_products_details
                                        SET
                                            Invoice_ID_Auto = ?
                                        WHERE
                                            Entery_ID = ?

                    ", $prod_update);
                }
                $subtotal_prod += $Product_SubTotal_Price;
                $total_prod += $Product_Total_Price;
                $prod_arr[] = array("product_id" => $item['Product_ID'],
                    "total_amount" => ($Product_Total_Price),
                    "description" => '', "vat_amount" => $item['vat_amount']);
            }
        }

        //        $Invoice_Net_old = $total_prod - ($total_prod * $Invoice_Discount);
        //        $Invoice_Net_new = $total_prod - ($total_prod * $Invoice_Discount_new);
        //        $new_discount_amount = $total_prod * $Invoice_Discount_new / 100;
        $data = [
            &$subtotal_prod,
            &$total_prod, &$new_discount_amount, &$mydate, &$this->info['Logged_ID'],
            &$old_id
        ];
        // update totals in old invoice (remove sum of amounts of splitted items)
        $this->db->prepare_Stmt("UPDATE tbl_invoices 
                                        SET     Invoice_Sub_Total = Invoice_Sub_Total - ?,
                                                Invoice_Net_Total = Invoice_Net_Total - ?,
                                                discount_amount = discount_amount - ?,
                                                date_time = ?,Logged_ID = ?,is_main_transfer = 0
                                        WHERE   Invoice_ID_Auto = ? ", $data);
        $data2 = [
            &$subtotal_prod,
            &$total_prod, &$new_discount_amount, &$mydate, &$this->info['Logged_ID'],
            &$new_id
        ];
        // update totals in new invoice (add sum of amounts of splitted items)
        $this->db->prepare_Stmt("UPDATE tbl_invoices 
                                        SET Invoice_Sub_Total =  ?, Invoice_Net_Total = ?,discount_amount =?,
                                        date_time = ?,Logged_ID = ?,is_main_transfer = 0
                                        WHERE    Invoice_ID_Auto = ?  ", $data2);
        $prod_str =implode( ',',$prod_ids_arr);
        $this->info['Invoice_ID_Auto'] = $new_id;
        $this->info['is_splited_invoice'] = 1;
        //        echo '<pre>';
        //        echo $prod_str;
        //        print_r($prod_ids_arr);
        //                print_r($prod_arr);
        //                print($prod_str);
        //        die();

        $prod_trans_arr = CommonBusiness::get_item_acc_transactions($prod_arr, $prod_str, 'inv', $sales_account, $Invoice_Discount_new);

        return $this->invoice->setData($this->info)->payInvoice($prod_trans_arr);

        //        $error = $this->db->error();
        //        if (empty($error)) {
        //            //                        $this->invoice->printPOSInvoice( $this->info['Invoice_ID_Auto'] ,$this->info['invoice_type']);
        //            $this->db->query('COMMIT');
        //        } else {
        //            $this->db->query('ROLLBACK');
        //        }
        //
        //        return array_unique($error);
    }

    public function changeUser() {
        $condition = '';
        $related_tables_query = $this->db->query('select Related_Tables from tbl_invoices where Invoice_ID_Auto ="' . $this->info['Invoice_ID_Auto'] . '"');
        $tables = $this->db->assoc($related_tables_query)['Related_Tables'];
        $all_tables = $this->info['table_id'];
        if (!empty($tables)) {
            $all_tables .= ',' . $tables;
            $condition .= " AND table_id IN ({$all_tables},{$this->info['table_id']})";
        } else {
            $condition .= " and table_id = '{$this->info['table_id']}' ";
        }
        $this->db->prepare_Stmt("UPDATE tbl_invoices 
                                        SET
                                            Close_ID = ?,
                                            Logged_ID= ?,is_main_transfer = 0
                                        WHERE
                                            Is_Closed = 0
                                         " . $condition . "   
                                ", [&$this->info['user_id'], &$this->info['user_id']]);
        $error = $this->db->error();
        return $error;
    }

    //   public function getTotalCash($user_id, $start_date = null, $end_date = null) {
    //        $data = array();
    //        $condition = $user_id == '0' ? '' : ' and Close_ID = "' . $user_id . '" ';
    //        $query = $this->db->query('select sum(Invoice_Net_Total) as total_amount,
    //                                          sum(Invoice_Paid_Amount) as total_paid 
    //                                    from
    //                                           tbl_invoices
    //                                    where 
    //                                            date_time >= "' . (!is_null($start_date) ? $start_date : date('Y-m-d 12:00:00 a')) . '" 
    //                                    and 
    //                                            date_time <= "' . (!is_null($end_date) ? $end_date : date('Y-m-d 11:59:59 a')) . '"
    //                ' . $condition);
    //        while ($row = $this->db->assoc($query)) {
    //            $data [] = $row;
    //        }
    //        return $data;
    //    }

    public function SubmitCriteria() {
        $this->db->query('START TRANSACTION');
        $max_count = $this->info['criteria_type'] == 1 ? $this->info['criteria_max_count'] : 1;
        $criteria = [&$this->info['criteria_name'], &$this->info['criteria_type'], &$max_count, &$this->info['is_required'], &$this->info['Product_ID']];
        $this->db->prepare_Stmt("INSERT INTO tbl_product_criteria (criteria_name,criteria_type,criteria_max_count,is_required,Product_ID) 
                                                            VALUES(?,?,?,?,?)
                    ", $criteria);
        $criteria_id = $this->db->id();
        $criteria_data = 'INSERT INTO tbl_meal_criteria (
                                                    criteria_name,
                                                    criteria_type,
                                                    criteria_max_count,
                                                    is_required,
                                                    meal_id,
                                                    criteria_id_offline,
                                                    branch_id) 
                                            VALUES(?,?,?,?,(select meal_id from tbl_meal where meal_id_offline = ? and branch_id =?),?,?)';
        $this->db->is_logged_data($criteria_data, [$this->info['criteria_name'], $this->info['criteria_type'], $max_count, $this->info['is_required'], $this->info['Product_ID'], SMARTDINER_BRANCH_ID, $criteria_id, SMARTDINER_BRANCH_ID]);

        foreach ($this->info['criteria_details'] as $details):
            $this->db->prepare_Stmt("INSERT INTO  tbl_product_criteria_detail (criteria_detail_name,criteria_id) 
                                                            VALUES(?,?)
                    ", [&$details['criteria_detail_name'], &$criteria_id]);
            $criteria_detail_id_offline = $this->db->id();
            $criteria_detail_data = 'INSERT INTO tbl_meal_criteria_detail (
                                                            criteria_detail_name,
                                                            criteria_detail_price,
                                                            criteria_id,
                                                            criteria_detail_id_offline,
                                                            branch_id) 
                                                    VALUES(?,?,(select criteria_id from tbl_meal_criteria where criteria_id_offline=?  and branch_id =?),?,?)';
            $this->db->is_logged_data($criteria_detail_data, [$details['criteria_detail_name'], NULL, $criteria_id, SMARTDINER_BRANCH_ID, $criteria_detail_id_offline, SMARTDINER_BRANCH_ID]);
        endforeach;
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function submitAddress() {
        $this->db->prepare_Stmt("INSERT INTO tbl_customer_address (customer_id,address_name) 
                                                            VALUES(?,?)
                    ", [&$this->info['customer_id'], &$this->info['customer_address']]);
        $error = $this->db->error();
        return $error;
    }

    public function getCustomerAddresses() {
        $data = array();
        $query = $this->db->query('select 
                                          customer.Customer_ID,
                                          customer.Customer_Name,
                                          customer.Customer_Mobile,
                                          address.address_id,
                                          address.address_name,
                                          address.is_main
                                   from tbl_customers customer
                                   inner join tbl_customer_address address
                                   on customer.Customer_ID = address.customer_id
                       ');
        while ($row = $this->db->assoc($query)) {
            if (!isset($data[$row['Customer_ID']])) {
                $customerDetails = ["Customer_ID" => $row['Customer_ID'],
                    "Customer_Name" => $row['Customer_Name'],
                    "Customer_Mobile" => $row['Customer_Mobile'],
                    "addresses" => []
                ];
                $data[$row['Customer_ID']] = $customerDetails;
            }
            $details = ["address_id" => $row['address_id'],
                "address_name" => $row['address_name'],
                "is_main" => $row['is_main']
            ];
            $data[$row['Customer_ID']]['addresses'][] = $details;
        }
        return array_values($data);
    }

    public function getProductCriteria() {
        //        die('heree');
        $data = array();
        $query = $this->db->query('select
                        *
                  from
                        product_criteria_detail
                  where
                         ' . (!empty($this->info['is_all']) ? ('( Product_ID ="' . $this->info['Product_ID'] . '" or Product_ID = 0 )' . (!empty($this->info['category_id']) ? ' and( category_id = "' . $this->info['category_id'] . '" or category_id is null or category_id= 0)' : '')) : '  Product_ID ="' . $this->info['Product_ID'] . '"') . '
                        ' . (!empty($this->info['criteria_id']) ? ' and criteria_id = "' . $this->info['criteria_id'] . '" ' : '') . '
        ');
        while ($row = $this->db->assoc($query)) {
            if (!isset($data[$row['criteria_id']])) {
                $data[$row['criteria_id']] = ["criteria_id" => $row['criteria_id'],
                    "criteria_name" => $row['criteria_name'],
                    "criteria_type" => $row['criteria_type'],
                    "criteria_max_count" => $row['criteria_max_count'],
                    "is_required" => $row['is_required'],
                    "details_id" => $row['details_id'],
                    "product_id" => $row['Product_ID'],
                    "category_id" => $row['category_id'],
                    "category_name" => $row['category_name'],
                    "detail" => []
                ];
                //                 = $criterias;
            }
            //            echo $currency_id.'==';
            $price = (!empty($this->info['currency_id']) ? CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $this->info['currency_id'], $row['criteria_detail_price']) : $row['criteria_detail_price']);
            //            echo $price.'==';
            $data[$row['criteria_id']]['detail'][] = ["criteria_detail_id" => $row['criteria_detail_id'],
                "criteria_detail_name" => $row['criteria_detail_name'],
                "details_id" => $row['details_id'],
                "criteria_detail_price" => $price,
            ];
            //            $data[$row['criteria_id']]['detail'][] = $details;
        }
        //        if(array_key_exists('criteria',$data)){
        //            $data_new = array_values($data ['criteria']);
        //            $data['criteria'] = $data_new;
        //        }
        return !empty($this->info['criteria_id']) ? array_values($data) : $data;
    }

    public function submitService() {
        $this->db->prepare_Stmt('UPDATE tbl_default_settings
                                                 SET
                                                        setting_value =?
                                                 WHERE 
                                                        setting_id = 43

                                         ', [&$this->info['setting_value']]);

        $error = $this->db->error();
        return $error;
    }
    public function submitProductRate() {
        $this->db->prepare_Stmt('UPDATE tbl_default_settings
                                                 SET
                                                        setting_value =?
                                                 WHERE 
                                                        setting_name = "product_rate"

                                         ', [&$this->info['setting_value2']]);

        $error = $this->db->error();
        return $error;
    }
    public function submitProductRateTypeOne() {
        $this->db->prepare_Stmt('UPDATE tbl_default_settings
                                                 SET
                                                        setting_value =?
                                                 WHERE 
                                                        setting_name = "rate_type_one"

                                         ', [&$this->info['setting_value3']]);

        $error = $this->db->error();
        return $error;
    }
    public function submitProductRateTypeTwo() {
        $this->db->prepare_Stmt('UPDATE tbl_default_settings
                                                 SET
                                                        setting_value =?
                                                 WHERE 
                                                        setting_name = "rate_type_two"

                                         ', [&$this->info['setting_value4']]);

        $error = $this->db->error();
        return $error;
    }
    public function submitLebanonVat() {
        $this->db->prepare_Stmt('UPDATE tbl_default_settings
                                                 SET
                                                        setting_value =?
                                                 WHERE 
                                                        setting_name = "lebanon_vat_amount"

                                         ', [&$this->info['setting_value5']]);

        $error = $this->db->error();
        return $error;
    }

    
    public function submitAddOns() {
        $this->db->query('START TRANSACTION');
        $flag = $this->info['add_ons_flag'];
        $sync_query = '';
        if ($flag == 0) {
            $this->db->prepare_Stmt('INSERT INTO tbl_add_ons
                                     (add_ons_title)
                                     VALUES
                                    (?)
                                         ', [&$this->info['add_ons_title']]);
            $this->info['add_ons_id'] = $this->db->id();
            $add_ons = 'INSERT INTO tbl_add_ons
                                     (add_ons_title,add_ons_id_offline,branch_id)
                                     VALUES
                                    (?,?,?)';

            $sync_query = $this->db->is_logged_query($add_ons, [$this->info['add_ons_title'], $this->info['add_ons_id'], SMARTDINER_BRANCH_ID]);
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_add_ons
                                                 SET
                                                        add_ons_title =?
                                                 WHERE 
                                                        add_ons_id =?

                                         ', [&$this->info['add_ons_title'], &$this->info['add_ons_id']]);
            $add_ons = 'UPDATE tbl_add_ons
                                                 SET
                                                        add_ons_title =?
                                                 WHERE 
                                                        add_ons_id_offline =?
                                                        and branch_id = ? ';
            $sync_query = $this->db->is_logged_query($add_ons, [$this->info['add_ons_title'], $this->info['add_ons_id'], SMARTDINER_BRANCH_ID]);
        }
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->is_logged_file($sync_query);
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function deleteAddOns() {
        $this->db->prepare_Stmt('Delete from tbl_add_ons where add_ons_id = ?
                                         ', [&$this->info['entry_value']]);
        $error = $this->db->error();
        if (empty($error)) {
            $add_ons = 'Delete from tbl_add_ons where add_ons_id_offline = ?  and branch_id = ?';
            $this->db->is_logged_data($add_ons, [$this->info['entry_value'], SMARTDINER_BRANCH_ID]);
        }
        return $error;
    }

    public function submitAddOnsDetails() {
        $this->db->query('START TRANSACTION');
        $flag = $this->info['add_ons_details_flag'];
        $sync_query = '';
        $add_ons_details = json_decode($this->info['add_ons_details'], true);
        if ($flag == 0) {
            foreach ($add_ons_details as $val) {
                $this->db->prepare_Stmt('INSERT INTO tbl_add_ons_details
                                     (add_ons_id,add_ons_details_title)
                                     VALUES
                                    (?,?)
                                         ', [&$this->info['add_ons_id'], &$val]);
                $add_ons_details_id = $this->db->id();
                $add_ons_details = 'INSERT INTO tbl_add_ons_details
                                     (add_ons_id,add_ons_details_title,add_ons_details_id_offline,branch_id)
                                     VALUES
                                    ((select add_ons_id from tbl_add_ons where add_ons_id_offline = ?),?,?,?) ';
                $sync_query .= $this->db->is_logged_query($add_ons_details, [$this->info['add_ons_id'], $val,
                    $add_ons_details_id, SMARTDINER_BRANCH_ID]);
            }
        } else {
            $this->db->prepare_Stmt('UPDATE tbl_add_ons_details
                                                 SET
                                                        add_ons_details_title =?,
                                                        add_ons_id =?
                                                 WHERE 
                                                        add_ons_details_id =?

                                         ', [&$this->info['add_ons_details_title'], &$this->info['add_ons_id'], &$this->info['add_ons_details_id']]);
            $add_ons_details = 'UPDATE tbl_add_ons_details
                                                 SET
                                                        add_ons_details_title =?,
                                                        add_ons_id = (select add_ons_id from tbl_add_ons where add_ons_id_offline = ?)
                                                 WHERE 
                                                        add_ons_details_id_offline =?
                                                        and branch_id = ? ';
            $sync_query = $this->db->is_logged_query($add_ons_details, [$this->info['add_ons_details_title'], $this->info['add_ons_id'],
                $this->info['add_ons_details_id'], SMARTDINER_BRANCH_ID]);
        }
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->is_logged_file($sync_query);
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function deleteAddOnsDetails() {
        $this->db->prepare_Stmt('Delete from tbl_add_ons_details where add_ons_details_id = ?
                                         ', [&$this->info['entry_value']]);
        if (empty($error)) {
            $add_ons_details = 'Delete from tbl_add_ons_details where add_ons_details_id_offline = ?  and branch_id = ?';
            $this->db->is_logged_data($add_ons_details, [$this->info['entry_value'], SMARTDINER_BRANCH_ID]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function submitDeliveryData() {
        $this->db->query('START TRANSACTION');
        $mydate = date("Y-m-d H:i:s");
        $logged_id = smc_session()['user_logged_id'];
        $this->invoice->setData($this->info)->printPOSInvoice($this->info['Invoice_ID_Auto'], 1);
        $invoice_details = CommonFunctions::CommonView('tbl_invoices', ['Invoice_ID_Auto'], [$this->info['Invoice_ID_Auto']])[0];
        //
        //        self::payDeliveryInvoice($invoice_details,$this->info['shipping_fees']);
        $this->db->prepare_Stmt("UPDATE tbl_invoices SET app_status = 1,date_time = ?,Logged_ID = ?,is_main_transfer = 0
            WHERE Invoice_ID_Auto = ?", [&$mydate, &$logged_id, &$this->info['Invoice_ID_Auto']]);
        $error = $this->db->error();
        if (empty($error)) {
            $data = 'Update tbl_order set order_status_id = 1 where  order_id =?';
            $this->db->is_logged_data($data, [$invoice_details['order_id_online']]);
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function getOfflineIds() {
        $account_query = $this->db->query('select max(account_id_online) as account_id_online from tbl_pos_customers');
        $last_account = $this->db->assoc($account_query);
        $last_account_id = $last_account['account_id_online'] ? $last_account['account_id_online'] : 0;

        $address_query = $this->db->query('select max(address_id_online) as address_id_online  from tbl_customer_address');
        $last_address = $this->db->assoc($address_query);
        $last_address_id = $last_address['address_id_online'] ? $last_address['address_id_online'] : 0;

        $order_query = $this->db->query('select max(order_id_online) as order_id_online from tbl_invoices');
        $last_order = $this->db->assoc($order_query);
        $last_order_id = $last_order['order_id_online'] ? $last_order['order_id_online'] : 0;

        return ['account_id' => $last_account_id, 'address_id' => $last_address_id, 'order_id' => $last_order_id];
    }

    public function get_invoice_id_by_table($id) {
        $query = $this->db->query('SELECT * FROM pos_invoices 
            WHERE (table_id = "' . $id . '" or concat(",",Related_Tables,",") like "%,' . $id . ',%")  
                and Is_Closed = 0 ORDER BY Invoice_Date DESC');
        $row = $this->db->assoc($query);
        if (is_null($row))
            return 0;
        $inv_id = $row['Invoice_ID_Auto'];
        return $inv_id;
    }

    public function update_invoice_printed($id) {
        $this->db->prepare_Stmt("UPDATE tbl_invoices SET is_printed = 1
            WHERE Invoice_ID_Auto = ?", [&$id]);
        $error = $this->db->error();
        return $error;
    }

    public function get_takeaway_pos() {
        $data = array();
        

        $takeaway_query = $this->db->query('SELECT  *  FROM   tbl_invoices inv  WHERE  inv.is_done <> 1   ');
        while ($row = $this->db->assoc($takeaway_query)) {
            $data[$row['Invoice_ID_Auto']] = $row;
            $takeaway_details_query = $this->db->query('SELECT * FROM tbl_invoice_products_details det LEFT JOIN tbl_stock_products as pro on pro.Product_ID = det.Product_ID WHERE det.Invoice_ID_Auto = '.$row['Invoice_ID_Auto'].' ORDER BY det.Entery_ID   ');
            while ($row_det = $this->db->assoc($takeaway_details_query)) {
                $data[$row['Invoice_ID_Auto']]['details'][$row_det['Entery_ID']]=$row_det;
            }
        }
         return $data;
    }
    public function update_states() {
        $this->db->prepare_Stmt('UPDATE tbl_invoices   SET  is_done = 1  WHERE  Invoice_ID_Auto =? ', [&$this->info['id']]);
        $error = $this->db->error();
        return [$this->info['id'],'error'];
    }

}
