<?php

//insert invoices and return the success invoice ids
function insert_db_frm_arr__invoices($branch_id, $invoices, $onlin_oflin_cstmr_ids) {
    global $db, $__data_type;
    $succ_ids = array();
    if (!empty($invoices)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $invoice = new Invoice;
        if ($__data_type == 'upld' && !empty($onlin_oflin_cstmr_ids)) {
            $query_customers = $db->query_execute('select offline_customer_id, online_customer_id from tbl_pos_customers_sync where branch_id = ?
                and offline_customer_id in (' . implode(',', array_keys($onlin_oflin_cstmr_ids)) . ') ', array($branch_id));
            while ($cust_row = $db->query_fetch($query_customers))
                $onlin_oflin_cstmr_ids[$cust_row['offline_customer_id']] = $cust_row['online_customer_id'];
        }
        //start transaction
        foreach ($invoices as $inv_id => $inv_row) {
            $inv_row['Invoice_Currency_Rate'] = $inv_row['current_rate'];
            $inv_row['shipping'] = $inv_row['Invoice_Shipping'];
            $inv_row['shipping_account'] = $inv_row['shipping_Account'];
            //$inv_row['Account_Code'] = $inv_row['sales_Account'];
            $inv_row['Invoice_Number'] = $inv_row['Invoice_ID'];
            $inv_row['is_data_collector'] = 0;
            $inv_row['pending_status'] = $inv_row['Invoice_Status'];    //4
            $inv_row['pos_customer_id'] = empty($onlin_oflin_cstmr_ids[$inv_row['pos_customer_id']]) ? 0 : $onlin_oflin_cstmr_ids[$inv_row['pos_customer_id']];
            $cond_inv = '';
            $cond_inv_arr = array($inv_id, $inv_row['created_logged_id'], $branch_id);
            if ($__data_type == 'rstr') {
                $inv_id = $inv_row['Invoice_ID_Auto'] = $inv_row['fill_auto_id'] = $inv_row['invoice_app_id'];
                unset($inv_row['app_user_id']);
                unset($inv_row['invoice_app_id']);
                unset($inv_row['app_branch_id']);
                unset($inv_row['online_invoice_id']);
            } else {
                $inv_row['app_user_id'] = $inv_row['created_logged_id'];
                $inv_row['invoice_app_id'] = $inv_row['Invoice_ID_Auto'];
                $inv_row['app_branch_id'] = $branch_id;
                $cond_inv.=' or Invoice_ID_Auto = ?  ';
                $cond_inv_arr[] = $inv_row['online_invoice_id'];
            }

            $check_invoice = $db->query_execute('select Invoice_ID_Auto, date_time, is_actual from tbl_invoices 
                        where (invoice_app_id = ? and app_user_id = ? and app_branch_id = ?) ' . $cond_inv
                    , $cond_inv_arr);

            if ($db->query_result_count($check_invoice) == 0) {
                $insert = $invoice->setdata($inv_row)->insertSalesInvoice();
                if (is_numeric($insert[0])) {
                    $succ_ids[] = $inv_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Invoice [{$inv_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_inv_row = $db->query_fetch($check_invoice);
                $inv_row['Invoice_ID_Auto'] = $check_inv_row['Invoice_ID_Auto'];
                //here we check if for any reason invoice inserted or updated before we check the last modify time if
                //it is the same as the new one then we just return success without any change to the invoice
                if (!empty($inv_row['date_time']) && $check_inv_row['date_time'] == $inv_row['date_time'] && $check_inv_row['is_actual'] == $inv_row['is_actual'])
                    $update = array(0 => 1);    //just return success update
                else
                    $update = $invoice->setdata($inv_row)->editInvoice();
                if (is_numeric($update[0])) {
                    $succ_ids[] = $inv_id;
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update Invoice [{$inv_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
        }
        //
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_invoices set is_main_transfer = 1 where Invoice_ID_Auto in (" . implode(',', $succ_ids) . ") ");
        //
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Invoices</h2>All Count: " . count($invoices);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
        //end transaction
    }
    return $succ_ids;
}

//insert return invoices and return the success return invoice ids
function insert_db_frm_arr__return_invoices($branch_id, $return_invoices) {
    global $db, $__data_type;
    $succ_ids = array();
    if (!empty($return_invoices)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $return = new ReturnInvoice;
        //start transaction
        foreach ($return_invoices as $ret_id => $ret_row) {
            $ret_row['Invoice_Currency_Rate'] = $ret_row['current_rate'];
//            $ret_row['shipping'] = $ret_row['Invoice_Shipping'];
//            $ret_row['shipping_account'] = $ret_row['shipping_Account'];
            $ret_row['Account_Code'] = $ret_row['sales_Account'];
            $ret_row['Invoice_Net_Total'] = $ret_row['Return_Net_Total'];
            $ret_row['is_data_collector'] = 0;
//            $ret_row['pending_status'] = 4;
            if ($__data_type == 'rstr') {
                $ret_id = $ret_row['Return_Invoice_ID'] = $ret_row['fill_auto_id'] = $ret_row['invoice_app_id'];
                unset($ret_row['app_user_id']);
                unset($ret_row['invoice_app_id']);
                unset($ret_row['app_branch_id']);
            } else {
                $ret_row['app_user_id'] = $ret_row['created_logged_id'];
                $ret_row['invoice_app_id'] = $ret_row['Return_Invoice_ID'];
                $ret_row['app_branch_id'] = $branch_id;
            }
            $check_return = $db->query_execute('select Return_Invoice_ID, date_time from tbl_accounting_return_invoices
                where invoice_app_id = ? and app_user_id = ? and app_branch_id = ?', array($ret_row['Return_Invoice_ID'], $ret_row['created_logged_id'], $branch_id));
            if ($db->query_result_count($check_return) == 0) {
                $insert = $return->setdata($ret_row)->ReturnNoInvoice();
                if (is_numeric($insert)) {
                    $succ_ids[] = $ret_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Return Invoice [{$ret_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_ret_row = $db->query_fetch($check_return);
                $ret_row['Return_ID'] = $check_ret_row['Return_Invoice_ID'];
                //here we check if for any reason invoice inserted or updated before we check the last modify time if
                //it is the same as the new one then we just return success without any change to the invoice
                if (!empty($ret_row['date_time']) && $check_ret_row['date_time'] == $ret_row['date_time'])
                    $update = array(0 => 1);    //just return success update
                else
                    $update = $return->setdata($ret_row)->editReturnNoInvoice();
                if (is_numeric($update[0])) {
                    $succ_ids[] = $ret_id;
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update Return Invoice [{$ret_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_accounting_return_invoices set is_main_transfer = 1 where Return_Invoice_ID in (" . implode(',', $succ_ids) . ") ");
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Return Invoices</h2>All Count: " . count($return_invoices);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//insert transfers and return the success transfer ids
function insert_db_frm_arr__transfers($branch_id, $depot_id, $transfers) {
    global $db, $__data_type;
    $succ_ids = array();
    if (!empty($transfers)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $warehouseDepot = new WarehouseDepot;
        //start transaction
        foreach ($transfers as $trnsfr_id => $trnsfr_row) {
            if ($__data_type == 'rstr') {
                $trnsfr_id = $trnsfr_row['Request_ID'] = $trnsfr_row['fill_auto_id'] = $trnsfr_row['app_request_id'];
                unset($trnsfr_row['app_user_id']);
                unset($trnsfr_row['app_request_id']);
                unset($trnsfr_row['app_branch_id']);
            } else {
                $trnsfr_row['app_request_id'] = $trnsfr_row['Request_ID'];
                $trnsfr_row['app_user_id'] = $trnsfr_row['created_logged_id'];
                $trnsfr_row['app_branch_id'] = $branch_id;
            }
            $trnsfr_row['request_prefix'] = $trnsfr_row['serial_prefix'];
            $trnsfr_row['is_confirmed'] = 1;
            $trnsfr_row['is_data_collector'] = 0;
            if ($__data_type == 'rstr') //for restore  always set main transfer to 1
                $trnsfr_row['is_main_transfer'] = 1;
            else {
                //2 [means already moved to transfer_from] since we already get it from there
                $trnsfr_row['is_main_transfer'] = 2;
                //but if also transfer to is for same branch then we must put it directly 1 to don't download it again 
                //to same branch and a duplicate data occur
                if (strpos("," . get_depot_by_branch($branch_id) . ",", ",{$trnsfr_row['Request_From']},") !== false)
                    $trnsfr_row['is_main_transfer'] = 1;
            }
            $trnsfr_row[0] = $trnsfr_row['created_logged_id'];
            $check_request = $db->query_execute('select Request_ID from tbl_stock_request
                        where app_request_id = ? and app_user_id = ? and app_branch_id = ?'
                    , array($trnsfr_row['app_request_id'], $trnsfr_row['app_user_id'], $branch_id));
            if ($db->query_result_count($check_request) == 0) {
                $insert = $warehouseDepot->setdata($trnsfr_row)->createRequest();
                if (!empty($insert) && is_numeric($insert[0])) {
                    $succ_ids[] = $trnsfr_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Transfer [{$trnsfr_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_trnsfr_row = $db->query_fetch($check_request);
                $trnsfr_row['Request_ID'] = $check_trnsfr_row['Request_ID'];
                $update = $warehouseDepot->setdata($trnsfr_row)->editRequest();
                if (!empty($update) && is_numeric($update[0])) {
                    $succ_ids[] = $trnsfr_id;
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update Transfer [{$trnsfr_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_stock_request set is_main_transfer = 1 where Request_ID in (" . implode(',', $succ_ids) . ") ");
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Transfers</h2>All Count: " . count($transfers);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//insert payments/receipt and return the success ids
function insert_db_frm_arr__payments_receipts($branch_id, $pay_rec_records, $onlin_oflin_cstmr_ids) {
    global $db, $__data_type;
    $succ_ids = array();
    //
    if (!empty($pay_rec_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $pay_rec_obj = new Payment;
        if ($__data_type == 'upld' && !empty($onlin_oflin_cstmr_ids)) {
            $query_customers = $db->query_execute('select offline_customer_id, online_customer_id from tbl_pos_customers_sync where branch_id = ?
                and offline_customer_id in (' . implode(',', array_keys($onlin_oflin_cstmr_ids)) . ') ', array($branch_id));
            while ($cust_row = $db->query_fetch($query_customers))
                $onlin_oflin_cstmr_ids[$cust_row['offline_customer_id']] = $cust_row['online_customer_id'];
        }
        //start transaction
        foreach ($pay_rec_records as $pay_id => $pay_row) {
            if ($__data_type == 'rstr') {
                $pay_id = $pay_row['pay_rec_id'] = $pay_row['fill_auto_id'] = $pay_row['payment_app_id'];
                unset($pay_row['app_user_id']);
                unset($pay_row['payment_app_id']);
                unset($pay_row['app_branch_id']);
            } else {
                $pay_row['app_user_id'] = $pay_row['created_logged_id'];
                $pay_row['payment_app_id'] = $pay_row['pay_rec_id'];
                $pay_row['app_branch_id'] = $branch_id;
            }
            $pay_row['pos_customer_id'] = empty($onlin_oflin_cstmr_ids[$pay_row['pos_customer_id']]) ? 0 : $onlin_oflin_cstmr_ids[$pay_row['pos_customer_id']];
//            $pay_row['current_rate'] = $pay_row['current_rate'];
            $pay_row['Payment_Number'] = $pay_row['pay_rec_nb'];
            $pay_row['Account_Code'] = $pay_row['Account_ID'];
            $pay_row[0] = $pay_row['Logged_ID'];
//            for
//            $pay_row['payment'][] = array('is_cheque' => $pay_row['is_cheque'],
//                'Payment_Type_ID' => $pay_row['Payment_Type_ID'],
//                'Payment_Amount' => $pay_row['Payment_Amount'],
//                'Payment_Amount' => $pay_row['Payment_Amount'],
//                'Payment_Note' => $pay_row['Payment_Note'],
//                'Check_Numebr' => $pay_row['Cheque_Number'],
//                'Check_Date' => $pay_row['Payment_Due_Date'],
//            );
            //to get invoice auto id on server based on invoice app id
            if (!empty($pay_row['close_arr']) && $__data_type == 'upld') {
                foreach ($pay_row['close_arr'] as &$item) {
                    $query = $db->query_execute('select Invoice_ID_Auto from tbl_invoices 
                            where invoice_app_id = "' . $item['inv_id'] . '" and branch_id = "' . $pay_row['branch_id'] . '"');
                    $item['inv_id'] = $db->query_fetch($query)['Invoice_ID_Auto'];
                }
            }
            $check_pay = $db->query_execute('select pay_rec_id as Payment_Auto_ID, date_time from tbl_payment_receipt 
                where payment_app_id = ? and app_user_id = ? and app_branch_id = ?', array($pay_id, $pay_row['created_logged_id'], $branch_id));
            if ($db->query_result_count($check_pay) == 0) {
                $insert = $pay_rec_obj->setdata($pay_row)->create();
                if (empty($insert)) {
                    $succ_ids[] = $pay_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Payment/Receipt [{$pay_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_pay_row = $db->query_fetch($check_pay);
                $pay_row['pay_id'] = $check_pay_row['Payment_Auto_ID'];
                //here we check if for any reason pay/rec inserted or updated before we check the last modify time if
                //it is the same as the new one then we just return success without any change to the pay/rec
                if (!empty($pay_row['date_time']) && $check_pay_row['date_time'] == $pay_row['date_time'])
                    $update = array(0 => 1);    //just return success update
                else
                    $update = $pay_rec_obj->setdata($pay_row)->editPayment();
                if (empty($update)) {
                    $succ_ids[] = $pay_id;
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update Payment/Receipt [{$pay_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_payment_receipt set is_main_transfer = 1 where pay_rec_id in (" . implode(',', $succ_ids) . ") ");
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Payment/Receipt</h2>All Count: " . count($pay_rec_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//insert deposite/withdrawals and return the success ids
function insert_db_frm_arr__deposit_withdrawal($branch_id, $dep_with_records) {
    global $db, $__data_type;
    $succ_ids = array();
    //
    if (!empty($dep_with_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $jv_obj = new JV;
        //start transaction
        foreach ($dep_with_records as $dep_id => $dep_row) {
            if ($__data_type == 'rstr') {
                $dep_id = $dep_row['Deposit_WithDrawal_ID'] = $dep_row['fill_auto_id'] = $dep_row['app_dep_id'];
                unset($dep_row['app_user_id']);
                unset($dep_row['app_dep_id']);
                unset($dep_row['app_branch_id']);
            } else {
                $dep_row['app_user_id'] = $dep_row['created_logged_id'];
                $dep_row['app_dep_id'] = $dep_row['Deposit_WithDrawal_ID'];
                $dep_row['app_branch_id'] = $branch_id;
            }
            $dep_row['Is_Actual'] = $dep_row['Is_Hidden'];
            $dep_row['rate_from'] = $dep_row['current_rate_from'];
            $dep_row['rate_to'] = $dep_row['current_rate_to'];
            $dep_row['From_Account'] = $dep_row['From_Account_ID'];
            $dep_row['To_Account'] = $dep_row['To_Account_ID'];
            $dep_row[0] = $dep_row['Logged_ID'];
            $check_pay = $db->query_execute('select Deposit_WithDrawal_ID from tbl_accounting_bank_deposit_withdrawal 
                where app_dep_id = ? and app_user_id = ? and app_branch_id = ?', array($dep_id, $dep_row['created_logged_id'], $branch_id));
            if ($db->query_result_count($check_pay) == 0) {
                $insert = $jv_obj->setdata($dep_row)->addDepositWithDrawal();
                if (empty($insert)) {
                    $succ_ids[] = $dep_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Deposit/Withdrawal [{$dep_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_dep_row = $db->query_fetch($check_pay);
                $dep_row['dw_id'] = $check_dep_row['Deposit_WithDrawal_ID'];
                //here we check if for any reason deposit/withdrawal inserted or updated before we check the last modify time if
                //it is the same as the new one then we just return success without any change to the deposit/withdrawal
                if (!empty($dep_row['date_time']) && $check_dep_row['date_time'] == $dep_row['date_time'])
                    $update = array(0 => 1);    //just return success update
                else
                    $update = $jv_obj->setdata($dep_row)->editDepositWithDrawal();
                if (empty($update)) {
                    $succ_ids[] = $dep_id;
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update Deposit/Withdrawal [{$dep_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_accounting_bank_deposit_withdrawal set is_main_transfer = 1 where Deposit_WithDrawal_ID in (" . implode(',', $succ_ids) . ") ");
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Deposit/Withdrawal</h2>All Count: " . count($dep_with_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

function insert_db_frm_arr__cashdrawer($branch_id, $cash_drawer_records) {
    global $db, $__data_type;
    $succ_ids = array('login_only' => array(), 'full' => array());
    //
    if (!empty($cash_drawer_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $acc_obj = new CommonACC;
        //start transaction
        foreach ($cash_drawer_records as $drawer_id => $drawer_row) {
            if ($__data_type == 'rstr') {
                $drawer_id = $drawer_row['Deposit_WithDrawal_ID'] = $drawer_row['fill_auto_id'] = $drawer_row['drawer_app_id'];
                unset($drawer_row['app_user_id']);
                unset($drawer_row['drawer_app_id']);
                unset($drawer_row['app_branch_id']);
            } else {
                $drawer_row['app_user_id'] = $drawer_row['user_id'];
                $drawer_row['app_branch_id'] = $branch_id;
                $drawer_row['drawer_app_id'] = $drawer_id;
            }
            $check_drawer = $db->query_execute('select cash_drawer_amount_id from tbl_cash_drawer_amount 
                where drawer_app_id = ? and app_user_id = ? and app_branch_id = ?', array($drawer_id, $drawer_row['user_id'], $branch_id));
            $succ_indx = empty($drawer_row['logout_date_time']) ? 'login_only' : 'full';
            if ($db->query_result_count($check_drawer) == 0) {
//                $drawer_row['system_amount'] = $drawer_row['login_system_amount'];
//                $drawer_row['cash_drawer_id_ref'] = $drawer_row['cash_drawer_id'];
                $insert = $acc_obj->setdata($drawer_row)->insert_cash_drawer_sync();
                if (empty($insert)) {
                    $succ_ids[$succ_indx][] = $drawer_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert Cash Drawer [{$drawer_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                if ($drawer_row['is_main_transfer'] == 1) {
//                    $drawer_row['app_user_id'] = $drawer_row['user_id'];
//                    $drawer_row['drawer_app_id'] = $drawer_id;
//                    $drawer_row['app_branch_id'] = $branch_id;
//                    $drawer_row['system_amount'] = $drawer_row['logout_system_amount'];
//                	$drawer_row['cash_drawer_id_ref'] = $drawer_row['cash_drawer_id'];
                    $check_drawer_row = $db->query_fetch($check_drawer);
                    $drawer_row['cash_drawer_amount_id_exist'] = $check_drawer_row['cash_drawer_amount_id'];
                    $update = $acc_obj->setdata($drawer_row)->update_cash_drawer_sync();
                    if (empty($update)) {
                        $succ_ids[$succ_indx][] = $drawer_id;
                        $update_count++;
                    } else {
                        $err_message .= "<br/>Update Cash Drawer [{$drawer_id}] Error: " . implode(',', $update);
                        $update_err_count++;
                    }
                } else
                    $succ_ids[$succ_indx][] = $drawer_id;
            }
        }
        if ($__data_type == 'rstr') {
            foreach ($succ_ids as $drwr_indx => $drwr_ids) {
                if (!empty($drwr_ids))
                    $db->query_execute("update tbl_cash_drawer_amount set is_main_transfer = '" . ($drwr_indx == 'full' ? '2' : '1') . "'
                        where cash_drawer_amount_id in (" . implode(',', $drwr_ids) . ") ");
            }
        }
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Cash Drawer</h2>All Count: " . count($cash_drawer_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//insert pos customers and return the success pos customer ids
function insert_db_frm_arr__pos_customers($branch_id, $customers) {
    global $db, $__data_type;
    $succ_ids = array();
    if (!empty($customers)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        $customer = new Customer;
        $customer_db = $customer->get_db();
        //start transaction
        $customer_db->query('START TRANSACTION');
        foreach ($customers as $customer_id => $cust_row) {
            $online_customer_id = 0;
            if ($__data_type == 'rstr') {
                $customer_id = $cust_row['customer_id'] = $cust_row['fill_auto_id'] = $cust_row['offline_customer_id'];
                $check_customer = $db->query_execute('select customer_id from tbl_pos_customers
                    where customer_id = ? ', array($cust_row['customer_id']));
            } else {
                $check_customer = $db->query_execute('select offline_customer_id,online_customer_id from tbl_pos_customers_sync 
                    where offline_customer_id = ? and branch_id = ?', array($customer_id, $branch_id));
            }
            if ($db->query_result_count($check_customer) == 0) {    //insert
                $insert = $customer->setdata($cust_row)->addCustomerPOS();
                if (is_numeric($insert)) {
                    if ($__data_type == 'upld')
                        $online_customer_id = $insert;
                    $succ_ids[$customer_id] = $insert;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert pos customer [{$insert}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $check_cust_row = $db->query_fetch($check_customer);
                if ($__data_type == 'upld') {
                    $online_customer_id = $check_cust_row['online_customer_id'];
                    $cust_row['customer_id'] = $check_cust_row['online_customer_id'];
                }
                $update = $customer->setdata($cust_row)->updateCustomerPOS();
                if (empty($update)) {
                    $succ_ids[$customer_id] = $cust_row['customer_id'];
                    $update_count++;
                } else {
                    $err_message .= "<br/>Update pos customer [{$customer_id}] Error: " . implode(',', $update);
                    $update_err_count++;
                }
            }
            if ($__data_type == 'upld') {
                $customer_db->prepare_Stmt('insert into tbl_pos_customers_sync (offline_customer_id,online_customer_id,branch_id,is_sync) 
                    values(?,?,?,1) on duplicate key update is_sync = 1 ', [&$customer_id, &$online_customer_id, &$branch_id]);
                $customer_db->prepare_Stmt('update tbl_pos_customers_sync set is_sync = 0 where branch_id <> ? and online_customer_id = ?
                    ', [&$branch_id, &$online_customer_id]);
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $customer_db->prepare_Stmt("update tbl_pos_customers set is_main_transfer = 1 where customer_id in (" . implode(',', $succ_ids) . ") ");
        $error = $customer_db->error();
        if (empty($error))
            $customer_db->query('COMMIT');
        else
            $customer_db->query('ROLLBACK');
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>pos customers</h2>All Count: " . count($customers);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }

    return $succ_ids;
}

//delete (inv,pay,..) that are deleted on branch
function insert_db_frm_arr__delete_log($branch_id, $delete_log_records) {
    global $db, $__data_type;
    $succ_ids = array();
    if ($__data_type == 'rstr')
        return $succ_ids;
    //
    if (!empty($delete_log_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        //start transaction
        foreach ($delete_log_records as $log_id => $log_row) {
            if ($log_row['type'] == 'inv') {
                $invoice = new Invoice();
                $check_log = $db->query_execute('select Invoice_ID_Auto from tbl_invoices 
                where invoice_app_id = ?  and app_branch_id = ?', array($log_row['main_id'], $branch_id));
                if ($db->query_result_count($check_log) > 0) {
                    $row = $db->query_fetch($check_log);
                    $delete = $invoice->deleteSalesInvoice([$row['Invoice_ID_Auto']]);
                    if (empty($delete)) {
                        $succ_ids[] = $log_id;
                        $insert_count++;
                    } else {
                        $err_message .= "<br/>Delete Invoices log_id: [{$log_id}] Error: " . implode(',', $delete);
                        $insert_err_count++;
                    }
                } else {
                    $succ_ids[] = $log_id;
                }
            } else if ($log_row['type'] == 'ret') {
                $return = new ReturnInvoice();
                $check_log = $db->query_execute('select Return_Invoice_ID from tbl_accounting_return_invoices 
                where invoice_app_id = ?  and app_branch_id = ?', array($log_row['main_id'], $branch_id));
                if ($db->query_result_count($check_log) > 0) {
                    $row = $db->query_fetch($check_log);
                    $delete = $return->deleteReturn([$row['Return_Invoice_ID']]);
                    if (empty($delete)) {
                        $succ_ids[] = $log_id;
                        $insert_count++;
                    } else {
                        $err_message .= "<br/>Delete Return log_id: [{$log_id}] Error: " . implode(',', $delete);
                        $insert_err_count++;
                    }
                } else {
                    $succ_ids[] = $log_id;
                }
            }
        }
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Delete Log</h2>All Count: " . count($delete_log_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//update users that modified on branch
function insert_db_frm_arr__users($branch_id, $users_records) {
    global $db, $__data_type;
    $succ_ids = array();
    if ($__data_type == 'rstr')
        return $succ_ids;
    //
    if (!empty($users_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        //start transaction
        foreach ($users_records as $user_id => $user_row) {
            $db->query_execute("update tbl_common_users set User_Password = ? where User_ID = ? ", array($user_row['User_Password'], $user_row['User_ID']));
            $succ_ids[] = $user_id;
            $update_count++;
        }
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Users</h2>All Count: " . count($users_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}

//insert end of shift/day and return the success ids
function insert_db_frm_arr__end_shift_day($branch_id, $shift_records) {
    global $db, $__data_type;
    $succ_ids = array();
    //
    if (!empty($shift_records)) {
        $insert_count = $update_count = $insert_err_count = $update_err_count = 0;
        $err_message = "";
        //start transaction
        foreach ($shift_records as $shift_id => $shift_row) {
            if ($__data_type == 'rstr') {
                $shift_id = $shift_row['shift_id'] = $shift_row['app_shift_id'];
                $app_branch_id = $app_shift_id = $app_user_id = 0;
            } else {
                $app_user_id = $shift_row['logged_id'];
//                $app_shift_id = $shift_row['shift_id'];
                $app_branch_id = $branch_id;
            }
            $branch_id = $check_exist = $db->query_execute('select shift_id from tbl_end_of_shift 
                where app_shift_id = ? and app_user_id = ? and app_branch_id = ?', array($shift_id, $shift_row['logged_id'], $branch_id));
            if ($db->query_result_count($check_exist) == 0) {
                $data = array($shift_row['user_id'], $shift_row['open_time'], $shift_row['close_time'],
                    $shift_row['account_id'], $shift_row['total_net_invoices'], $shift_row['total_net_returns'],
                    $shift_row['total_balance'], $shift_row['Currency_ID'], $shift_row['current_rate'], $shift_row['type'],
                    $shift_row['is_actual'], $app_branch_id, $app_user_id, $app_branch_id,
                    $shift_id, $shift_row['date_time'], $shift_row['logged_id']);
                $insert = $db->query_execute('INSERT INTO `tbl_end_of_shift`( `user_id`, `open_time`, `close_time`,
                    `account_id`, `total_net_invoices`, `total_net_returns`, `total_balance`, `Currency_ID`,
                    `current_rate`, `type`, `is_actual`, `branch_id`, `app_user_id`, `app_branch_id`,
                    `app_shift_id`,  `date_time`, `logged_id`)
                    values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', $data);
                if (!$db->is_error()) {
                    $succ_ids[] = $shift_id;
                    $insert_count++;
                } else {
                    $err_message .= "<br/>Insert end of Shift/Day [{$shift_id}] Error: " . implode(',', $insert);
                    $insert_err_count++;
                }
            } else {
                $succ_ids[] = $shift_id;
                $update_count++;
            }
        }
        if ($__data_type == 'rstr' && !empty($succ_ids))
            $db->query_execute("update tbl_end_of_shift set is_main_transfer = 1 where shift_id in (" . implode(',', $succ_ids) . ") ");
        //end transaction
        echo "<div style='border:1px solid black;background:#ccc;padding:5px;margin:10px 0px;'><h2>Deposit/Withdrawal</h2>All Count: " . count($shift_records);
        echo ($insert_count > 0 ? "<br/>Inserted Count: {$insert_count}" : "") . ($update_count > 0 ? "<br/>Updated Count: {$update_count}" : "");
        echo "  <div style='background:red;padding:5px;margin:5px;'>";
        echo ($insert_err_count > 0 ? "<br/>Inserted Error Count: {$insert_err_count}" : "") . ($update_err_count > 0 ? "<br/>Updated Error Count: {$update_err_count}" : "");
        echo (check_is_debug() && !empty($err_message) ? "<br/>{$err_message}" : '');
        echo "  </div>";
        echo "</div>";
    }
    return $succ_ids;
}
