<?php

class Purchase {

    protected $info = array();
    public $db;
    private $year_id;
    private $year_id_actual;
    public $stop_transaction_start_end = false;
    public $permissions;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
        $this->year_id = Session::getCurrentYearID();
        $this->year_id_actual = Session::getCurrentYearIDActual();
        $this->permissions = new Permissions(smc_session()['user_logged_id']);
    }

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

    public function createInvoicePurchase($return_inv_num = false) {
        $error = token_unique::is_valid_token();
        if (!empty($error))
            return $error;
//        if (!empty($this->info['unique_id'])) {
//            if (!isset(smc_session()['duplicate_check'][$this->info['unique_id']])) {
//                $error = array();
//                $error[0] = CommonLanguage::getMessage('duplicate_record');
//                return $error;
//            } else {
//                unset(smc_session()['duplicate_check'][$this->info['unique_id']]);
//            }
//        }
        //        die('here');
        $is_actual = !empty($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'purchase', 'start_date' => $this->info['Purchase_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Purchase_Date'], $this->info['Purchase_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        //send from view supplier account and name, send currency symbol,cash ,chequ and credit card accounts
        $this->info['Other_Amount'] = !empty($this->info['Other_Amount']) ? $this->info['Other_Amount'] : 0;
        $paid = $this->info['Card_Amount'] + $this->info['Cash_Amount'] + $this->info['Check_Amount'] + $this->info['Other_Amount'];
        $rem = $this->info['Purchase_Net_Total'] - $paid;
        if (smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 1) {
            $paid = 0;
            $rem = $this->info['Purchase_Net_Total'];
        }
        /* @var $suppAccount type */
        $suppAccount = $this->info['Supplier_Account'];
        //        if ($rem > 0) {
        //            $from_date = substr($this->info['Purchase_Date'], 0, 4) . "-01-01";
        //            $advance_payment = self::returnExactBalance($suppAccount, $this->info['Currency_ID'], $from_date, $this->info['Purchase_Date']);
        //            if ($advance_payment < $rem) {
        //                $paid += $advance_payment;
        //            } else {
        //                $paid += $rem;
        //            }
        //        }
        $this->info['currency_round'] = !empty($this->info['currency_round']) ? $this->info['currency_round'] : 0;

        $depot_id = $this->info['Depot_ID'];
        $branch_id = CommonBusiness::getBranchByDepot($depot_id);
        $purchase_account = $this->info['Account_Code'];
        $mydate = date("Y-m-d H:i:s");
        $purch_num = self::getMaxPurchase($is_actual);
        $rate = !empty($this->info['Invoice_Currency_Rate']) ? $this->info['Invoice_Currency_Rate'] : CurrencyFactory::getLastExRate($this->info['Currency_ID']);
        $second_rate = !empty($this->info['second_currency_rate']) ? $this->info['second_currency_rate'] : CurrencyFactory::getSecondCurrencyLastExRate($this->info['Currency_ID']);

        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';
        $driver_id = !empty($this->info['driver_id']) ? $this->info['driver_id'] : 0;

        //        $rate = CurrencyFactory::getLastExRate($this->info['Currency_ID']);
        $order_id = !empty($this->info['order_id']) ? $this->info['order_id'] : 0;
        $this->info['vat1_total'] = !empty($this->info['vat1_total']) ? $this->info['vat1_total'] : $this->info['Invoice_VAT'];
        $this->info['vat2_total'] = !empty($this->info['vat2_total']) ? $this->info['vat2_total'] : 0;
        $this->info['is_noqty'] = !empty($this->info['is_noqty']) ? $this->info['is_noqty'] : 0;
        $this->info['job_id'] = isset($this->info['job_id']) ? $this->info['job_id'] : 0;
        $job_trans_type = smc_session()['default_setting']['job_transaction_type'];
        $person_job = ($job_trans_type == 0 || $job_trans_type == 1 ? $this->info['job_id'] : 0);
        $opposite_job = ($job_trans_type == 0 || $job_trans_type == 2 ? $this->info['job_id'] : 0);
        $this->info['current_invoice_type'] = !empty($this->info['current_invoice_type']) ? $this->info['current_invoice_type'] : null;
        $this->info['ship_bill_nb'] = !empty($this->info['ship_bill_nb']) ? $this->info['ship_bill_nb'] : '';
        $this->info['ship_date'] = !empty($this->info['ship_date']) ? $this->info['ship_date'] : '';
        $this->info['container_nb'] = !empty($this->info['container_nb']) ? $this->info['container_nb'] : '';
        $this->info['container_size'] = !empty($this->info['container_size']) ? $this->info['container_size'] : '';
        $this->info['ctn_nb'] = !empty($this->info['ctn_nb']) ? $this->info['ctn_nb'] : '';
        $this->info['ctn_date'] = !empty($this->info['ctn_date']) ? $this->info['ctn_date'] : '';

        $main = [
            &$purch_num,
            &$this->info['Purchase_Date'],
            &$this->info['Purchase_Due_Date'],
            &$mydate,
            &$mydate,
            &$this->info['Currency_ID'],
            &$this->info['Supplier_ID'],
            &$this->info['Purchase_Sub_Total'],
            &$this->info['Purchase_Net_Total'],
            &$this->info['Purchase_Discount'],
            &$this->info['discount_amount'],
            &$depot_id,
            &$this->info['Supplier_Invoice_ID'],
            &$this->info['Invoice_Description'],
            &$paid,
            &$this->info['Invoice_VAT'],
            &$this->info['vat1_total'],
            &$this->info['vat2_total'],
            &$this->info['shipping'],
            &$rate, &$second_rate,
            &$this->info[0],
            &$this->info[0],
            &$this->year_id,
            &$branch_id,
            &$purchase_account,
            &$is_actual,
            &$this->info['extra_cost'],
            &$this->info['cost_dist_method'],
            &$this->info['job_id'],
            &$this->info['project_id'],
            &$this->info['Class_ID'],
            &$order_id,
            &$this->info['currency_round'],
            &$this->info['is_noqty'],
            &$this->info['current_invoice_type'],
            $this->info['ship_bill_nb'], $this->info['ship_date'], $this->info['container_nb'],
            $this->info['container_size'], $this->info['ctn_nb'], $this->info['ctn_date']
            ,$driver_id
            , $this->info['from_place']
            , $this->info['to_place']

        ];
        $this->db->prepare_Stmt("INSERT INTO tbl_inventory_purchases
         (Purchase_ID,Purchase_Date,Purchase_Due_Date,date_time,date_created,Currency_ID,Supplier_ID,
          Purchase_Sub_Total,Purchase_Net_Total,Purchase_Discount,discount_amount,Depot_ID,
          Supplier_Invoice_ID,Invoice_Description,Purchase_Paid_Amount,Purchase_VAT,vat1_total,vat2_total,
          Purchase_Shipping,current_rate,second_currency_rate,Logged_ID,created_logged_id,
          current_year_id,branch_id,Account_ID,is_actual,extra_cost,cost_dist_method,job_id,project_id,
          Class_ID,order_id,currency_round,disable_qty,invoice_type_id,ship_bill_nb,ship_date,container_nb,
          container_size,ctn_nb,ctn_date,driver_id,from_place,to_place)
          VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $main);

        $purchase_id = $this->db->id();
        $arr_purchase = ['type' => 'pur', 'main_id' => $purchase_id, 'action' => 0, 'date_time' => $mydate,
            'user_id' => $this->info[0]];
        CommonFunctions::add_user_log($arr_purchase);
        $jv = JV::returnJV($is_actual);
        if (!empty($this->info['extra_cost_arr'])) {
            foreach ($this->info['extra_cost_arr'] as $ex) {
                $deb_acc = !empty($ex['debit_acc_id']) ? $ex['debit_acc_id'] : null;
                $cre_acc = !empty($ex['credit_acc_id']) ? $ex['credit_acc_id'] : null;
                $ex_second_rate = CurrencyFactory::getSecondCurrencyLastExRate($ex['currency_id']);
                $data_extra = [$purchase_id, $ex['amount'], $ex['currency_id'], $ex['current_rate'], $ex_second_rate,
                    $ex['type'], $deb_acc, $cre_acc, $ex['note']];
                $this->db->prepare_Stmt('INSERT INTO `tbl_purchase_extra_cost`( `purchase_id`, `amount`,
                `currency_id`, `current_rate`, `second_currency_rate`,type,debit_acc_id,credit_acc_id,note)
                values(?,?,?,?,?,?,?,?,?)', $data_extra);
                if (!empty($deb_acc) && !empty($cre_acc)) {
                    $data_trans = ["JV_ID" => $jv,
                        "Transaction_Reference" => 'extra cost',
                        "Transaction_Account" => $deb_acc,
                        "Transaction_Type" => "Debit",
                        "Transaction_Amount" => $ex['amount'],
                        "Transaction_Date" => $this->info['Purchase_Date'],
                        "Currency_ID" => $ex['currency_id'],
                        "Logged_ID" => $this->info[0],
                        "Transaction_Description" => $ex['note'],
                        "Current_Ex_Rate" => $ex['current_rate'],
                        "second_currency_rate" => $ex_second_rate,
                        "main_id" => $purchase_id,
                        "main_type" => "pur",
                        "branch_id" => $branch_id,
                        "due_date" => $this->info['Purchase_Due_Date'],
                        "main_nb" => $purch_num,
                        "job_id" => $opposite_job,
                        "project_id" => $this->info['project_id'],
                        "user_ref" => $this->info['Supplier_Invoice_ID']
                    ];
                    JV::addTransaction($data_trans, $is_actual);
                    $data_trans = ["JV_ID" => $jv,
                        "Transaction_Reference" => 'extra cost',
                        "Transaction_Account" => $cre_acc,
                        "Transaction_Type" => "Credit",
                        "Transaction_Amount" => $ex['amount'],
                        "Transaction_Date" => $this->info['Purchase_Date'],
                        "Currency_ID" => $ex['currency_id'],
                        "Logged_ID" => $this->info[0],
                        "Transaction_Description" => $ex['note'],
                        "Current_Ex_Rate" => $ex['current_rate'],
                        "second_currency_rate" => $ex_second_rate,
                        "main_id" => $purchase_id,
                        "main_type" => "pur",
                        "branch_id" => $branch_id,
                        "due_date" => $this->info['Purchase_Due_Date'],
                        "main_nb" => $purch_num,
                        "job_id" => $opposite_job,
                        "project_id" => $this->info['project_id'],
                        "user_ref" => $this->info['Supplier_Invoice_ID']
                    ];
                    JV::addTransaction($data_trans, $is_actual);
                }
            }
        }
        if (!empty($this->info['order_id']))
            $this->db->prepare_Stmt("update  tbl_purchase_order set is_converted = 1 where Order_ID = ?", [&$this->info['order_id']]);
        $purchase_detail_ids = array();
        $prod_arr = array();
        $prod_ids_arr = array();
        $total_extra_cost = $this->info['extra_cost'] + $this->info['shipping'];
        foreach ($this->info['Products'] as $item) {
            $cost_percent = 0;
            if (!empty($total_extra_cost)) {
                if ($this->info['cost_dist_method'] == 0) {
                    $cost_percent = (($item['Item_Quantity'] == 0 || $this->info['total_qty'] == 0) ? 0 : ($item['Item_Quantity'] / $this->info['total_qty']));
                } else if ($this->info['cost_dist_method'] == 1) {
                    $cost_percent = (($item['Product_Total_Price'] == 0 || ($this->info['Purchase_Sub_Total'] * ((100 - $this->info['Purchase_Discount']) / 100)) == 0) ? 0 : ($item['Product_Total_Price'] / (($this->info['Purchase_Sub_Total'] * ((100 - $this->info['Purchase_Discount']) / 100)) /* - $this->info['shipping'] */)));
                } else if ($this->info['cost_dist_method'] == 2) {
                    $cost_percent = $item['cost_percent'] / 100;
                }
            }
            $prod_ids_arr[] = $item['Product_ID'];
            $productID = $item['Product_ID'];
            $product_quantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $productID);
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';
            $item["vat2_percent"] = !empty($item["vat2_percent"]) ? $item["vat2_percent"] : 0;
            $item["vat2_amount"] = !empty($item["vat2_amount"]) ? $item["vat2_amount"] : 0;
            $item['additional_cost'] = !empty($item['additional_cost']) ? $item['additional_cost'] : 0;

            $prod_arr[] = array("product_id" => $item['Product_ID'],
                "total_amount" => ($item['Product_Total_Price']),
                "description" => $Product_Description, "vat_amount" => $item['vat_val']);
            $new_cost = ($item['additional_cost'] / $product_quantity ) + ($item['Item_Price'] / ($product_quantity / $item['Item_Quantity']) * ((100 - $item['Item_Discount']) / 100) * ((100 - $this->info['Purchase_Discount']) / 100)) + ($product_quantity == 0 ? 0 : ($total_extra_cost * $cost_percent / $product_quantity));
//            echo (($item['additional_cost'] / ($product_quantity / $item['Item_Quantity']))/$item['Item_Quantity']).'<br>';
//            echo ($item['Item_Price'] / ($product_quantity / $item['Item_Quantity']) * ((100 - $item['Item_Discount']) / 100) * ((100 - $this->info['Purchase_Discount']) / 100)).'<br>';
//            echo ($product_quantity == 0 ? 0 : ($total_extra_cost * $cost_percent / $product_quantity)).'<br>';
//            echo'==========';
            $expiry_date = !empty($item['expiry_date']) ? $item['expiry_date'] : null;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $item['is_service'] = !empty($item['is_service']) ? $item['is_service'] : 0;
            $item['iata_charges'] = !empty($item['iata_charges']) ? $item['iata_charges'] : 0;
            $item['fare_basis'] = !empty($item['fare_basis']) ? $item['fare_basis'] : 0;
            $item['taxes'] = !empty($item['taxes']) ? $item['taxes'] : 0;
            $item['farebasis_disc'] = !empty($item['farebasis_disc']) ? $item['farebasis_disc'] : 0;
            $depot_detail_id = !empty($item['depot_id']) ? $item['depot_id'] : $depot_id;
            //            echo $new_cost.'===<br>';
            if (empty($item['delivery_id']) && empty($this->info['is_noqty'])) {
                $costdata = [
                    "Product_ID" => $productID,
                    "Quantity" => $product_quantity,
                    "Unit_Cost" => $new_cost,
                    "unit_price" => $item['Item_Price'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "date_time" => $mydate,
                    "date_time_now" => $mydate,
                    "current_rate" => $rate,
                    "depot_id" => $depot_detail_id,
                    "trans_date" => $this->info['Purchase_Date'],
                    "current_quantity" => $item['Item_Quantity'],
                    "uom_id" => $item['UOM_ID'],
                    "is_actual" => $is_actual,
                    "expiry_date" => $expiry_date,
                    "lot_nb" => $lot_nb,
                    "serial_nb" => $serial_nb,
                    "main_id" => $purchase_id,
                    "is_service" => $item['is_service'],
                    "main_nb" => $purch_num,
                    "supplier_id" => $this->info['Supplier_ID']
                ];
                //            echo "<pre>";print_r($costdata);
                CommonBusiness::addCostByType($costdata, 'add_purchase');
            }
            $item['class_id'] = !empty($item['class_id']) ? $item['class_id'] : $this->info['Class_ID'];
            $item['delivery_id'] = !empty($item['delivery_id']) ? $item['delivery_id'] : null;

            //            self::addCostData($costdata);
            $prod_insert = [
                &$purchase_id,
                &$productID,
                &$product_quantity,
                &$item['Item_Price'],
                &$item['Product_Total_Price'],
                &$item['Item_Discount'],
                &$item['Item_Quantity'],
                &$item['UOM_ID'],
                &$item['vat_percent'],
                &$item['vat_val'],
                &$item['vat2_percent'],
                &$item['vat2_amount'],
                &$Product_Description,
                &$item['cost_percent'],
                &$item['class_id'],
                &$new_cost,
                &$expiry_date, &$lot_nb, &$serial_nb, &$item['delivery_id'],
                &$item['iata_charges'], &$item['fare_basis'], &$item['taxes'], &$item['farebasis_disc'],
                &$depot_detail_id, $item['additional_cost'],
                &$item['modify_date'], &$item['vehicle_id'], &$item['item_driver_id']
                , &$item['n_total']
                , &$item['n_width']
                , &$item['n_height']
            ];
            $this->db->prepare_Stmt("
                                        INSERT
                                        INTO
                                                tbl_inventory_purchase_items
                                        (
                                                Purchase_ID_Auto,
                                                Product_ID,
                                                Item_Quantity,
                                                Item_Price,
                                                Product_Total_Price,
                                                Item_Discount,
                                                Item_Quantity_Current,
                                                UOM_ID,
                                                vat_percent,
                                                vat_amount,vat2_percent,vat2_amount,
                                                product_description,cost_percent,supp_class_id,
                                                real_cost,expiry_date,lot_nb,serial_nb,Delivery_Report_ID,
                                                iata_charges,farebasis,taxes,farebasis_disc,depot_id,additional_cost,modify_date,vehicle_id,driver_id
                                                ,n_total
                                                ,n_width
                                                ,n_height
                                        )
                                                VALUES
                                        (
                                                ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
                                        )
                                ", $prod_insert);
            $pur_detail_id = $this->db->id();
            if (isset($item['invoice_detail_line']))
                $purchase_detail_ids[$item['invoice_detail_line']] = $pur_detail_id;
            if (empty($item['delivery_id']) && $item['is_service'] != 1 && empty($this->info['is_noqty'])) {
                $quant = [
                    &$product_quantity,
                    &$productID
                ];
                $this->db->prepare_Stmt("
                                UPDATE 
                                        tbl_stock_products
                                SET 
                                        Product_Quantity =  Product_Quantity + ?
                                WHERE 
                                        Product_ID       = ?

                                ", $quant);
                $location = [
                    &$productID,
                    &$depot_detail_id,
                    &$product_quantity,
                    &$product_quantity
                ];
                $this->db->prepare_Stmt("INSERT INTO tbl_stock_product_location
                                                (
                                                        Location_Product_ID,
                                                        Product_Depot_ID,
                                                        Product_Depot_Quantity
                                                )
                                                        VALUES
                                                (
                                                        ?,?,?
                                                )
                                            ON DUPLICATE KEY
                                            UPDATE Product_Depot_Quantity = Product_Depot_Quantity + ?


                                                ", $location);
            }
            if (!empty($item['cost_arr'])) {
                $item['cost_arr'] = json_decode($item['cost_arr'], true);
                foreach ($item['cost_arr'] as $ex) {
                    $deb_acc = !empty($ex['debit_acc_id']) ? $ex['debit_acc_id'] : null;
                    $cre_acc = !empty($ex['credit_acc_id']) ? $ex['credit_acc_id'] : null;
                    $ex_second_rate = CurrencyFactory::getSecondCurrencyLastExRate($ex['currency_id']);
                    $data_extra = [$purchase_id, $pur_detail_id, $ex['amount'], $ex['currency_id'], $ex['current_rate'], $ex_second_rate,
                        $ex['type'], $deb_acc, $cre_acc, $ex['note']];
                    $this->db->prepare_Stmt('INSERT INTO `tbl_purchase_extra_cost`( `purchase_id`,purchase_detail_id, `amount`,
                `currency_id`, `current_rate`, `second_currency_rate`,type,debit_acc_id,credit_acc_id,note)
                values(?,?,?,?,?,?,?,?,?,?)', $data_extra);
                    if (!empty($deb_acc) && !empty($cre_acc)) {
                        $data_trans = ["JV_ID" => $jv,
                            "Transaction_Reference" => 'extra cost',
                            "Transaction_Account" => $deb_acc,
                            "Transaction_Type" => "Debit",
                            "Transaction_Amount" => $ex['amount'],
                            "Transaction_Date" => $this->info['Purchase_Date'],
                            "Currency_ID" => $ex['currency_id'],
                            "Logged_ID" => $this->info[0],
                            "Transaction_Description" => $ex['note'],
                            "Current_Ex_Rate" => $ex['current_rate'],
                            "second_currency_rate" => $ex_second_rate,
                            "main_id" => $purchase_id,
                            "main_type" => "pur",
                            "branch_id" => $branch_id,
                            "due_date" => $this->info['Purchase_Due_Date'],
                            "main_nb" => $purch_num,
                            "job_id" => $opposite_job,
                            "project_id" => $this->info['project_id'],
                            "user_ref" => $this->info['Supplier_Invoice_ID']
                        ];
                        JV::addTransaction($data_trans, $is_actual);
                        $data_trans = ["JV_ID" => $jv,
                            "Transaction_Reference" => 'extra cost',
                            "Transaction_Account" => $cre_acc,
                            "Transaction_Type" => "Credit",
                            "Transaction_Amount" => $ex['amount'],
                            "Transaction_Date" => $this->info['Purchase_Date'],
                            "Currency_ID" => $ex['currency_id'],
                            "Logged_ID" => $this->info[0],
                            "Transaction_Description" => $ex['note'],
                            "Current_Ex_Rate" => $ex['current_rate'],
                            "second_currency_rate" => $ex_second_rate,
                            "main_id" => $purchase_id,
                            "main_type" => "pur",
                            "branch_id" => $branch_id,
                            "due_date" => $this->info['Purchase_Due_Date'],
                            "main_nb" => $purch_num,
                            "job_id" => $opposite_job,
                            "project_id" => $this->info['project_id'],
                            "user_ref" => $this->info['Supplier_Invoice_ID']
                        ];
                        JV::addTransaction($data_trans, $is_actual);
                    }
                }
            }
        }
//        die();
        $prod_str =implode( ',',$prod_ids_arr);
        $prod_trans_arr = CommonBusiness::get_item_acc_transactions($prod_arr, $prod_str, 'pur', $purchase_account, $this->info['Purchase_Discount'], $this->info['shipping_account'], $this->info['shipping']);


        $suppName = $this->info['Supplier_Name'];
        $pur_ref = "Pur." . $purch_num;
        $curr_symbol = $this->info['CurrencySymbole'];
        $desc = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : 'Purchased products with ' . round(($this->info['Purchase_Net_Total'] + $this->info['shipping']), 2) . ' ' . $curr_symbol . ' from ' . $suppName;
        //        $s_account = JV::getAccountCodeByID($suppAccount);
        $supp_vat_account = Supplier::returnSuppVATAccount($this->info['Supplier_ID'])['Account_ID'];
        $amount_novat = $this->info['Purchase_Net_Total'] - $this->info['Invoice_VAT'];
        foreach ($prod_trans_arr as $trans) {
            //            $trans_desc = $trans[]
            if (isset($trans['main'])) {
                $trans_main = $trans['main'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => (empty($trans_main['ref']) ? 'pur' : $trans_main['ref']),
                    "Transaction_Account" => $trans_main['trans_account'],
                    "Transaction_Type" => "Debit",
                    "Transaction_Amount" => $trans_main['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info[0],
                    "Transaction_Description" => (empty($trans_main['trans_desc']) ? $desc : $trans_main['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $purchase_id,
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "subtype" => "pur",
                    "main_nb" => $purch_num,
                    "job_id" => $opposite_job,
                    "project_id" => $this->info['project_id'],
                    "user_ref" => $this->info['Supplier_Invoice_ID']
                ];
                JV::addTransaction($data_trans, $is_actual);
            }


            if (isset($trans['person'])) {
                $trans_person = $trans['person'];
                $supp_amount = smc_session()['default_setting']['merge_cust_supp_accounts'] == 1 ? ($trans_person['trans_amount'] + $this->info['currency_round'] ) : $trans_person['trans_amount'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => $pur_ref,
                    "Transaction_Account" => $suppAccount,
                    "Transaction_Type" => "Credit",
                    "Transaction_Amount" => $supp_amount,
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info[0],
                    "Transaction_Description" => (empty($trans_person['trans_desc']) ? $desc : $trans_person['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $purchase_id,
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "main_nb" => $purch_num,
                    "job_id" => $person_job,
                    "project_id" => $this->info['project_id'],
                    "user_ref" => $this->info['Supplier_Invoice_ID']
                ];
                JV::addTransaction($data_trans, $is_actual);
                //                 $error = $this->db->error();
                //            die(print_r($error));
            }
        }
        if (smc_session()['default_setting']['merge_cust_supp_accounts'] == 0) {
            $trans_type = $this->info['currency_round'] > 0 ? 'Credit' : 'Debit';
            $data_trans = ["JV_ID" => $jv,
                "Transaction_Reference" => $pur_ref,
                "Transaction_Account" => $suppAccount,
                "Transaction_Type" => $trans_type,
                "Transaction_Amount" => abs($this->info['currency_round']),
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "main_nb" => $purch_num,
                "job_id" => $person_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => $this->info['Supplier_Invoice_ID']
            ];
            JV::addTransaction($data_trans, $is_actual);
        }
        $trans_disc_type = $this->info['currency_round'] < 0 ? 'Credit' : 'Debit';
        $dat_112 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $purchase_account,
            "Transaction_Type" => $trans_disc_type,
            "Transaction_Amount" => abs($this->info['currency_round']),
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $purch_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID']
        );
        JV::addTransaction($dat_112, $is_actual);

        $Invoice_Currency = &$this->info['Currency_ID'];
        $second_rate2 = $this->info['second_currency_rate'];
        $lebanon_vat_amount=smc_session()['default_setting']['lebanon_vat_amount'];
        if($Invoice_Currency == '144'){
            $second_rate2 = $lebanon_vat_amount;
        }

        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['vat1_total'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate2,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $purch_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID'],
            "subtype" => "vat1"
        );
        JV::addTransaction($dat_3, $is_actual);
        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['vat2_total'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $purch_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID'],
            "subtype" => "vat2"
        );
        JV::addTransaction($dat_3, $is_actual);
        if (smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 0) {
            $dat_112 = array(
                "JV_ID" => $jv,
                "Transaction_Reference" => $pur_ref,
                "Transaction_Account" => $suppAccount,
                "Transaction_Type" => "Debit",
                "Transaction_Amount" => $this->info['Purchase_Net_Total'] - $rem,
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "main_nb" => $purch_num,
                "job_id" => $person_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => $this->info['Supplier_Invoice_ID']
            );
            JV::addTransaction($dat_112, $is_actual);
            $dat_4 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'credit',
                "Transaction_Account" => $this->info['Card_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Card_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "credit",
                "main_nb" => $purch_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['card_user_ref']) ? $this->info['card_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_4, $is_actual);
            $dat_5 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'cash',
                "Transaction_Account" => $this->info['Cash_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Cash_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "cash",
                "main_nb" => $purch_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['cash_user_ref']) ? $this->info['cash_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_5, $is_actual);
            $dat_5 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'other',
                "Transaction_Account" => $this->info['Other_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Other_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "other",
                "main_nb" => $purch_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['other_user_ref']) ? $this->info['other_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_5, $is_actual);
            $dat_6 = ["JV_ID" => $jv,
                "Transaction_Reference" => 'check',
                "Transaction_Account" => $this->info['Check_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Check_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info[0],
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $purchase_id,
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
                "value_date" => (empty($this->info['value_date']) ? '' : $this->info['value_date']),
                "check_nb" => empty($this->info['Check_Num']) ? '' : $this->info['Check_Num'],
                "subtype" => "check",
                "main_nb" => $purch_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['check_user_ref']) ? $this->info['check_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_6, $is_actual);
        } else {
            if ($this->info['Cash_Amount'] > 0 || $this->info['Card_Amount'] > 0 || $this->info['Check_Amount'] > 0) {
                $pay_data = array();
                $pay_data['Payment_Date'] = $this->info['Purchase_Date'];
                $pay_data['Status_ID'] = $is_actual;
                $pay_data['branch_id'] = $branch_id;
                $pay_data['payment_prefix'] = '';
                $pay_data['IsReceipt'] = 0;
                $pay_data['Currency_Rate'] = $rate;
                $pay_data['Currency_ID'] = $this->info['Currency_ID'];
                $pay_data['date_time'] = $mydate;
                $pay_data['date_created'] = $mydate;
                $pay_data['Logged_ID'] = $this->info[0];
                $pay_data['created_logged_id'] = $this->info[0];
                $pay_data['Account_Code'] = $suppAccount;
                $pay_data['job_id'] = $this->info['job_id'];
                $pay_data['project_id'] = $this->info['project_id'];
                $pay_data['payment'] = array();
                if ($this->info['Card_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Card_Account'],
                        'Payment_Amount' => $this->info['Card_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => '',
                        'Check_Date' => '',
                        'value_date' => '',
                        'user_ref' => (empty($this->info['card_user_ref']) ? '' : $this->info['card_user_ref']),
                    );
                }
                if ($this->info['Cash_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Cash_Account'],
                        'Payment_Amount' => $this->info['Cash_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => '',
                        'Check_Date' => '',
                        'value_date' => '',
                        'user_ref' => (empty($this->info['cash_user_ref']) ? '' : $this->info['cash_user_ref']),
                    );
                }
                if ($this->info['Check_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Check_Account'],
                        'Payment_Amount' => $this->info['Check_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => (empty($this->info['Check_Num']) ? '' : $this->info['Check_Num']),
                        'Check_Date' => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
                        'value_date' => (empty($this->info['value_date']) ? '' : $this->info['value_date']),
                        'user_ref' => (empty($this->info['check_user_ref']) ? '' : $this->info['check_user_ref']),
                    );
                }
                $payment = new Payment();
                $payment->stop_transaction_start_end = true;
                $payment->setData($pay_data)->create();
            }
        }
        $error = $this->db->error();
        //        die(print_r($error));
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query("COMMIT");
            token_unique::remove_token();
            return $return_inv_num ? [$purchase_id, $purch_num, $purchase_detail_ids] : $purchase_id;
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query("ROLLBACK");
            return $return_inv_num ? [array_unique($error)] : array_unique($error);
        }
    }

    public function getPurchases() {

        $data = array();
        $query = $this->db->query('SELECT 
                                        i.Purchase_ID,
                                        c.Supplier_Name,
                                        i.Purchase_Date,
                                        i.Purchase_Due_Date,
                                        i.Purchase_Discount,
                                        i.Purchase_VAT,
                                        i.Purchase_Sub_Total,
                                        i.Purchase_Net_Total,
                                        i.Currency_ID,
                                        i.Supplier_ID 
                                    FROM 
                                        tbl_inventory_purchases i
                                    LEFT JOIN
                                        tbl_stock_suppliers c
                                    ON 
                                        i.Supplier_ID = c.Supplier_ID
                                    WHERE
                                        i.current_year_id = "' . $this->year_id . '"');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function getPurchase($IID, $is_actual = null) {
        $data = array();
        if (is_null($is_actual))
            $column = 'Purchase_ID_Auto';
        else
            $column = 'Purchase_ID';
        $query = $this->db->query('SELECT * FROM purchase_main_list
                                    WHERE 
                                        ' . $column . ' = "' . $IID . '" and current_year_id = "' . $this->year_id . '"

									');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        //        echo"<pre>";
        //        print_r($data);
        //        die();
        return $data;
    }

    public function getPurchaseDetails($IID) {

        $tax = 0;
        $totalVat = 0;
        $data = array();
        $query = $this->db->query('SELECT * from purchase_details WHERE Purchase_ID_Auto = "' . $IID . '" and current_year_id = "' . $this->year_id . '"');
        while ($row = $this->db->assoc($query)) {
            $tax += $row['Item_VAT'] ? $row['Product_Total_Price'] : 0;
            $totalVat += $row['Item_VAT'];

            $data[] = $row;
        }
        $data['tax'] = $tax;
        $data['totalVAT'] = $totalVat;
        return $data;
    }

    public function getPurchaseAct($IID) {
        $data = array();
        $year = SESSION::getCurrentYearID();
        $query = $this->db->query('SELECT * FROM purchase_main_list
                                    WHERE 
                                        Purchase_ID = "' . $IID . '"
                                            AND current_year_id = "' . $year . '"

									');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function getPurchaseActDetails($IID) {

        $tax = 0;
        $totalVat = 0;
        $data = array();
        $query = $this->db->query('SELECT * from purchase_details WHERE Purchase_ID = "' . $IID . '" AND current_year_id = "' . $this->year_id . '"');
        while ($row = $this->db->assoc($query)) {
            $tax += $row['Item_VAT'] ? $row['Product_Total_Price'] : 0;
            $totalVat += $row['Item_VAT'] ? ($row['Product_Total_Price'] * 0.1) : 0;

            $data[] = $row;
        }
        $data['tax'] = $tax;
        $data['totalVAT'] = $totalVat;
        return $data;
    }

    public function getPurchaseByID($id) {
        $data = array();
        $year = SESSION::getCurrentYearID();
        $query_main = $this->db->query('select current_year_id,Purchase_ID AS ID,driver_id AS driver_id,from_place AS from_place,to_place AS to_place,Purchase_ID_Auto AS Auto_ID,
         Purchase_Date AS Date,Purchase_Due_Date AS Due_Date,Purchase_Discount AS Discount,discount_amount,
         Purchase_VAT AS VAT,Purchase_Sub_Total AS Sub_Total,Purchase_Net_Total AS Net_Total,Purchase_Paid_Amount AS Paid_Amount,
         Currency_ID,Currency_Symbol,Currency_Name,currency_round,Depot_ID,Supplier_Invoice_ID,
         Invoice_Description,Supplier_ID,sales_purchase_id,Purchase_Shipping as shipping,Account_ID,
         Account_Code,Account_Name,current_rate,extra_cost,cost_dist_method,due_date_period,bone_type_id,
         bone_type_name,job_id,job_name,loading_number,truck,service_amount,service_vat,project_id,project_name,
         Class_ID,Class_Name,second_currency_rate,ship_date,ship_bill_nb,invoice_type_id,container_nb,
         container_size,ctn_nb,ctn_date
         from purchase_main_list where Purchase_ID_Auto = "' . smc_escape($id) . '" 
         AND current_year_id = "' . $this->year_id . '"');
        $row = $this->db->assoc($query_main);
        $row['driver_name'] = CommonBusiness::getDriverByDriverId($row['driver_id']);

        $data['Main'] = $row;
        $ref = "Pur." . $id;
        $acc_query = $this->db->query("SELECT 
                                            p.Account_Name,
                                            p.Account_Code,
                                            p.Account_ID,
                                             t.Transaction_Reference
                                        FROM 
                                            tbl_accounting_transactions t
                                        LEFT JOIN 
                                            tbl_chart_of_accounts p
                                        ON 
                                            t.Account_ID = p.Account_ID
                                       WHERE 
                                            t.main_id = '" . $id . "'
                                        AND 
                                            t.main_type = 'pur'
                                        AND 
                                         t.Transaction_Reference = 'ship'
                                        ");
        $data['Main']['shipping_account'] = '';
        $data['Main']['shipping_id'] = '';
        $data['Main']['shipping_name'] = '';
        while ($acc_row = $this->db->assoc($acc_query)) {
            //            $data['Main']['shipping_account'] = '';
            //            $data['Main']['shipping_name'] = '';
            //            if ($acc_row['Transaction_Reference'] === 'ship') {
            $data['Main']['shipping_account'] = $acc_row['Account_Code'];
            $data['Main']['shipping_id'] = $acc_row['Account_ID'];
            $data['Main']['shipping_name'] = $acc_row['Account_Name'];
            //            } else {
            //                $data['Main']['Account_Code'] = $acc_row['Account_Code'];
            //                $data['Main']['Account_Name'] = $acc_row['Account_Name'];
            //                $data['Main']['Account_ID'] = $acc_row['Account_ID'];
            //            }
        }

        $data['Person'] = Supplier::getSupplierByID(!empty($data['Main']['Supplier_ID']) ? $data['Main']['Supplier_ID'] : '');
        $query_details = $this->db->query('select i.Item_ID as Entery_ID,
                                                p.Purchase_ID_Auto AS Invoice_ID_Auto,i.modify_date,
                                                i.Item_Quantity_Current,i.vehicle_id,v.Vehicle_Code,v.Vehicle_Name,
                                                ps.Product_Code AS Code,
                                                ps.Product_Name AS Name,
                                                i.n_width,
                                                i.n_height,
                                                i.n_total,

                                                ps.Product_Limit_Discount,
                                                ps.Status_ID,ps.is_lot,ps.is_serial,ps.is_service,
                                               if(i.vat_percent <> 0,1,0) AS VAT,
                                                ps.Product_Quantity,
                                                i.Product_ID AS Product_ID,
                                                i.vat_percent,
                                                i.vat_amount,i.vat2_percent,i.vat2_amount,
                                                i.product_description,
                                                i.Item_Discount AS Product_Discount,
                                                i.Item_Price AS Product_Net_Price,
                                                i.Product_Total_Price AS Product_Total_Price,
                                                (i.Item_Quantity/i.Item_Quantity_Current) AS uom_con,
                                                 i.UOM_ID,
                                                 i.driver_id,
                                                GROUP_CONCAT(uom_from separator "/") AS Product_UOM,
                                                i.cost_percent,i.real_cost,uc.Bar_Code,i.expiry_date,ps.is_expiry,
                                                i.`liter_abs`, i.`coeff`, i.`temp`, i.`compts`,i.lot_nb,i.serial_nb,
                                                i.supp_class_id,pc.Class_Name as supp_class_name,i.Delivery_Report_ID,
                                                i.depot_id,w.Depot_Code,w.Depot_Name,i.additional_cost
                                            from 
                                                tbl_inventory_purchase_items i 
                                            left join 
                                                tbl_inventory_purchases p 
                                            on
                                                p.Purchase_ID_Auto = i.Purchase_ID_Auto
                                            LEFT JOIN
                                                uom_conversions uc
                                            ON 
                                                uc.Product_ID = i.Product_ID
                                            left join tbl_garage_vehicle v on v.Vehicle_ID = i.vehicle_id
                                            left join 
                                                tbl_stock_products ps 
                                            on
                                                ps.Product_ID = i.Product_ID
                                                left join tbl_pricing_class pc on pc.Class_ID = i.supp_class_id
                                                inner join tbl_stock_depot_warehouse w on w.Depot_ID = i.depot_id

                                            where
                                                p.current_year_id = "' . $year . '"
                                            and 
                                                p.Purchase_ID_Auto = "' . $id . '"
                                            GROUP BY i.Item_ID
                                            order by p.Purchase_ID

                                            ');

        while ($row = $this->db->assoc($query_details)) {
            $last_cost = CommonBusiness::viewLastProductCost($row["Product_ID"]) * $row['uom_con'];
            $row['LAST_COST'] = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $data['Main']['Currency_ID'], $last_cost);
            $row['cost_arr'] = array();
            $data['Details'][$row['Entery_ID']] = $row;
        }
        $query = $this->db->query("SELECT 
                                             t.Transaction_Amount,
                                            t.Transaction_Reference,
                                            t.Account_ID,
                                            p.Account_Name AS P_Name,
                                            t.check_nb,t.due_date,t.value_date,t.user_ref
                                        FROM 
                                            tbl_accounting_transactions t
                                        LEFT JOIN 
                                            tbl_chart_of_accounts p
                                        ON 
                                            t.Account_ID = p.Account_ID
                                        WHERE 
                                             t.main_id = '" . $id . "'
                                        AND 
                                            t.main_type = 'pur'
                                        AND 
                                            t.Transaction_Reference in ('cash','check','credit','other')
                                        ");
        $data['Payment'] = array();
        while ($row = $this->db->assoc($query)) {
            if (stripos($row['Transaction_Reference'], 'cash') !== false)
                $data['Payment']['Cash'] = $row;
            if (stripos($row['Transaction_Reference'], 'check') !== false)
                $data['Payment']['Cheque'] = $row;
            if (stripos($row['Transaction_Reference'], 'credit') !== false)
                $data['Payment']['Credit_Card'] = $row;
            if (stripos($row['Transaction_Reference'], 'other') !== false)
                $data['Payment']['others'] = $row;
        }
        $data['extra_cost'] = array();
        $query_ex = $this->db->query('select c.*,
            ifnull(concat(deb.Account_Code," - ",deb.Account_Name),"") as debit_acc_name,
            ifnull(concat(cre.Account_Code," - ",cre.Account_Name),"") as credit_acc_name
            from tbl_purchase_extra_cost c
            left join tbl_chart_of_accounts deb on deb.Account_ID = c.debit_acc_id
            left join tbl_chart_of_accounts cre on cre.Account_ID = c.credit_acc_id
            where purchase_id = "' . $id . '"');
        while ($row = $this->db->assoc($query_ex)) {
            if (empty($row['purchase_detail_id'])) {
                $data['extra_cost'][] = $row;
            } else {
                $data['Details'][$row['purchase_detail_id']]['cost_arr'][] = $row;
            }
        }
//               echo"<pre>";
//                die(print_r($data));
        return $data;
    }

    public function getDeliveredPurchaseDetails($IID) {

        $data = array();
        $query = $this->db->query(' SELECT 
					i.Item_ID,
                                        p.Purchase_ID,
                                        i.Purchase_ID_Auto,
                                        i.Product_ID,
                                        i.Item_Discount,
                                        i.Item_Price,
                                        i.Item_Quantity,
                                        i.Product_Total_Price
                                    From 
                                        tbl_inventory_purchase_items i
                                    LEFT JOIN
                                        tbl_inventory_purchases p
                                    ON
                                        p.Purchase_ID_Auto = i.Purchase_ID_Auto
                                    WHERE 
					p.Purchase_ID = "' . $IID . '"
                                    and
					p.current_year_id = "' . $this->year_id . '"');
        while ($row = $this->db->assoc($query)) {

            $product = self::getProductNameCode($row['Product_ID']);
            $row['Name'] = $product['Product_Name'];
            $row['Code'] = $product['Product_Code'];

            $delivered = self::returnDeliveredQuantity($IID, $row['Product_ID']);
            $row['Item_Quantity'] = $row['Item_Quantity'] - $delivered;
            $data[] = $row;
        }
        return $data;
    }

    public function returnDeliveredQuantity($inv_id, $product_id) {

        $query = $this->db->query('SELECT 
                                        SUM(i.Product_Delivery_Quantity) AS Sum_Delivered
                                    FROM 
                                        tbl_inventory_delivery_report d
                                    LEFT JOIN 
                                        tbl_inventory_delivery_report_items i
                                    ON 
                                        d.Delivery_Report_ID = i.Delivery_Report_ID 
                                    LEFT JOIN
                                        tbl_inventory_purchases p
                                     ON
                                        p.Purchase_ID = d.Invoice_Purchase_ID
                                    WHERE 
                                        d.Invoice_Purchase_ID = "' . $inv_id . '"
                                    AND 
                                        i.Product_ID = "' . $product_id . '"
                                    AND 
                                        d.Is_Customer_Invoice = 0
                                        and
						p.current_year_id = "' . $this->year_id . '"
                                ');
        $row = $this->db->assoc($query);
        $sum_delivered = $row['Sum_Delivered'];
        return $sum_delivered;
    }

    public function getMaxPurchaseID($table = null) {

        if (is_null($table)) {
            $table = 'tbl_inventory_purchases WHERE 1=1';
            $col = 'Purchase_ID_Auto';
            $yearid = $this->year_id;
        } else {
            $table = 'tbl_mgt_logs_backups WHERE Is_Purchase = 1';
            $col = 'ID_Auto';
            $yearid = $this->year_id_actual;
        }
        //        $query = $this->db->query('SELECT MAX(' . $col . ') AS Entry_ID FROM ' . $table . ' AND current_year_id = "' . $yearid . '"');
        $query = $this->db->query('SELECT MAX(' . $col . ') AS Entry_ID FROM ' . $table);
        $row = $this->db->assoc($query);
        if (!empty($row))
            $Invoice = $row['Entry_ID'];
        else
            $Invoice = 1;

        return $Invoice;
    }

    public function getMaxPurchase($is_actual) {

        $yearid = $is_actual ? $this->year_id_actual : $this->year_id;
        $query = $this->db->query('SELECT MAX(Purchase_ID) AS Entry_ID FROM tbl_inventory_purchases where current_year_id = "' . $yearid . '" and is_actual = "' . $is_actual . '"');

        $row = $this->db->assoc($query);
        if (!empty($row))
            $Invoice = $row['Entry_ID'] + 1;
        else
            $Invoice = 1;

        return $Invoice;
    }

    public function getVendorPurchases($VID) {
        $query = $this->db->query('SELECT * FROM tbl_inventory_purchases WHERE Supplier_ID = "' . $VID . '" WHERE current_year_id = "' . $this->year_id . '"');
        $index = 0;
        while ($row = $this->db->fetch($query)) {
            $info[$index] = array(
                $row['Purchase_ID'],
                $row['Purchase_Date'],
                $row['Purchase_ReferenceNumber'],
                $row['Warehouse_ID'],
                $row['Supplier_ID']
            );
            $index++;
        }
        return $info;
    }

    public function getPurchaseItems($PID) {
        $query = $this->db->query('SELECT * FROM tbl_inventory_purchase_items WHERE Purchase_ID_Auto = "' . $PID . '"');
        $index = 0;
        while ($row = $this->db->fetch($query)) {
            $info[$index] = array(
                $row['Item_ID'],
                $row['Product_ID'],
                $row['Item_Quantity'],
                $row['Item_Price']
            );
            $index++;
        }
        return $info;
    }

    private function getProductNameCode($id) {
        $query = $this->db->query('SELECT 
                                        Product_Code,
                                        Product_Name,
                                        Product_VAT,
                                        Product_Quantity
                                    FROM 
                                            tbl_stock_products
                                    WHERE 
                                            Product_ID = "' . $id . '"
				');
        $row = $this->db->assoc($query);
        return $row;
    }

    public function getPurchaseDeliveryNoteList($date = null, $year = null, $month = null) {
        $condition = '';
        $data = array();
        if (!is_null($date))
            $condition .= ' AND r.Delivery_Report_Date = "' . $date . '"';
        if (!is_null($year))
            $condition .= ' AND YEAR(r.Delivery_Report_Date) = "' . $year . '"';
        if (!is_null($month))
            $condition .= ' AND MONTH(r.Delivery_Report_Date) = "' . $month . '"';

        $query = $this->db->query('SELECT
                                    DISTINCT r.Delivery_Report_ID,
                                    r.Delivery_Report_Date,
                                    r.Customer_Supplier_ID,
                                    s.Supplier_Name

                                FROM
                                    tbl_inventory_delivery_report r
                                LEFT JOIN
                                    tbl_inventory_delivery_report_items d
                                ON
                                    d.Delivery_Report_ID = r.Delivery_Report_ID

                                LEFT JOIN
                                    tbl_stock_suppliers s
                                ON
                                    s.Supplier_ID = r.Customer_Supplier_ID
                                WHERE
                                    r.Is_Customer_Invoice = 0
                                AND 
                                    s.Status_ID = 1



                                ' . $condition);
        while ($row = $this->db->assoc($query)) {

            $data[] = $row;
        }
        return $data;
    }

    public function getPurchaseDeliveryNoteListDetails($ID) {

        $data = array();
        $query = $this->db->query('SELECT * FROM purchase_delivery_note_list WHERE ID = "' . $ID . '"');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    //    public function returnSuppVATAccount($supp_code) {
    //        $query = $this->db->query('SELECT VAT_Type_ID FROM tbl_organization WHERE Organization_ID = 1');
    //        $row = $this->db->assoc($query);
    //        $org_type = $row['VAT_Type_ID'];
    //        if ($org_type == 1)
    //            $vat_1 = "44210";
    //        else
    //            $vat_1 = "44211";
    //        $acc_supp_last_digits = substr($supp_code, -3);
    //        $query = $this->db->query('SELECT 
    //                                        Account_Code
    //                                    FROM 
    //                                        tbl_chart_of_accounts
    //                                    WHERE 
    //                                        LEFT(Account_Code,5) = "' . $vat_1 . '"
    //                                    AND 
    //                                        RIGHT(Account_Code,3) = "' . $acc_supp_last_digits . '"
    //                ');
    //        $row = $this->db->assoc($query);
    //        return $row['Account_Code'];
    //    }
    //    public function createActualInvoice() {
    //        $check = JV::checkCurrentYear($this->info['Purchase_Date'], $this->info['Purchase_Date'], 1);
    //        if ($check !== '') {
    //            $error = array();
    //            $error[0] = $check;
    //            return $error;
    //        }
    //        if (!$this->stop_transaction_start_end)
    //            $this->db->query('START TRANSACTION');
    //        $mydate = date("Y-m-d h:i:s a");
    //        $depot_id = $this->info['Depot_ID'];
    //        $purchase_account = $this->info['Account_Code'];
    //        $actual_amount = $this->info['Purchase_Net_Total'] - $this->info['Old_Total'];
    //        $paid = $this->info['Card_Amount'] + $this->info['Cash_Amount'] + $this->info['Check_Amount'];
    //        $rem_old = $this->info['Old_Total'] - $this->info['Paid_Old'];
    //        if ($paid > $rem_old) {
    //            $paid_old = $rem_old;
    //            $paid -= $paid_old;
    //        } else {
    //            $paid_old = $paid;
    //            $paid = 0;
    //        }
    //        $rem = $actual_amount - $paid;
    //        $suppAccount = $this->info['Supplier_Account'];
    //        if ($rem > 0) {
    //            $from_date = substr($this->info['Purchase_Date'], 0, 4) . "-01-01";
    //            $advance_payment = self::returnExactBalance($suppAccount, $this->info['Currency_ID'], $from_date, $this->info['Purchase_Date'], 1, true, true);
    //            if ($advance_payment < $rem) {
    //                $paid += $advance_payment;
    //            } else
    //                $paid += $rem;
    //        }
    //        $purch_num = self::getMaxPurchase("1");
    //        if (array_key_exists("Purchase_Invoice_ID", $this->info))
    //            $purchase_invoice_id = $this->info['Purchase_Invoice_ID'];
    //        else
    //            $purchase_invoice_id = 0;
    //        $is_purchase = "1";
    //        $data = [
    //            &$purch_num,
    //            &$this->info['Supplier_ID'],
    //            &$purchase_invoice_id,
    //            &$this->info['Purchase_Date'],
    //            &$this->info['Purchase_Due_Date'],
    //            &$this->info['Currency_ID'],
    //            &$this->info['shipping'],
    //            &$this->info['Purchase_Sub_Total'],
    //            &$this->info['Purchase_Net_Total'],
    //            &$this->info['Purchase_Discount'],
    //            &$paid,
    //            &$this->info['Old_Total'],
    //            &$is_purchase,
    //            &$this->info[0],
    //            &$this->year_id_actual,
    //            &$mydate
    //        ];
    //        $this->db->prepare_Stmt("
    //                                    INSERT
    //                                    INTO
    //                                            tbl_mgt_logs_backups
    //                                    (
    //                                            Entry_ID,
    //                                            Customer_Supplier_ID,
    //                                            Purchase_Invoice_ID,
    //                                            Date,
    //                                            Due_Date,
    //                                            Currency_ID,
    //                                            shipping,
    //                                            Sub_Total,
    //                                            Net_Total,
    //                                            Discount,
    //                                            Paid_Amount,
    //                                            Old_Total,
    //                                            Is_Purchase,
    //                                            Logged_ID,
    //                                            current_year_id,
    //                                            date_time
    //                                    )
    //                                            VALUES
    //                                    (
    //                                            ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
    //                                    )
    //                                ", $data);
    //        $purchase_id = $this->db->id();
    //        $jv = JV::returnJV("1");
    //        $curr_symbol = $this->info['Currency_Symbol'];
    //        $suppName = $this->info['Supplier_Name'];
    //        $desc = 'Purchased products with ' . $this->info['Purchase_Net_Total'] . ' ' . $curr_symbol . ' from ' . $suppName;
    //        if ($paid_old > 0) {
    //            $up_old = [&$paid_old, &$purchase_invoice_id];
    //            $this->db->prepare_Stmt("UPDATE tbl_inventory_purchases SET Purchase_Paid_Amount = Purchase_Paid_Amount + ? WHERE Purchase_ID_Auto = ?", $up_old);
    //            $desc_old = 'Payment to ' . $suppName;
    //            $jv_old = JV::returnJV();
    //            $dat1 = array(
    //                "JV_ID" => $jv_old,
    //                "Transaction_Reference" => $this->info['Purchase_Invoice_ID'],
    //                "Transaction_Account" => $suppAccount,
    //                "Transaction_Type" => "Debit",
    //                "Transaction_Amount" => $paid_old,
    //                "Transaction_Date" => $this->info['Purchase_Date'],
    //                "Currency_ID" => $this->info['Currency_ID'],
    //                "Logged_ID" => $this->info[0],
    //                "Transaction_Description" => $desc_old,
    //                "Current_Ex_Rate" => "0",
    //                "main_id" => $purchase_invoice_id,
    //                "main_type" => "pur"
    //            );
    //            JV::addTransaction($dat1);
    //            $amount_ch = $paid_old;
    //            if ($this->info['Card_Amount'] < $paid_old) {
    //                $amount_ch = $this->info['Card_Amount'];
    //                $paid_old -= $amount_ch;
    //                $amount_b = $paid_old;
    //                if ($this->info['Check_Amount'] < $paid_old) {
    //                    $amount_b = $this->info['Check_Amount'];
    //                    $paid_old -= $amount_b;
    //                    $amount_cash = $paid_old;
    //                    if ($this->info['Cash_Amount'] < $paid_old) {
    //                        $amount_cash = $this->info['Cash_Amount'];
    //                        $paid_old -= $amount_cash;
    //                    }
    //                    $dat2 = array(
    //                        "JV_ID" => $jv_old,
    //                        "Transaction_Reference" => $this->info['Purchase_Invoice_ID'],
    //                        "Transaction_Account" => $this->info['Cash_Account'],
    //                        "Transaction_Type" => "Credit",
    //                        "Transaction_Amount" => $amount_cash,
    //                        "Transaction_Date" => $this->info['Purchase_Date'],
    //                        "Currency_ID" => $this->info['Currency_ID'],
    //                        "Logged_ID" => $this->info[0],
    //                        "Transaction_Description" => $desc_old,
    //                        "Current_Ex_Rate" => "0",
    //                        "main_id" => $purchase_invoice_id,
    //                        "main_type" => "pur"
    //                    );
    //                    JV::addTransaction($dat2);
    //                    $this->info['Cash_Amount'] -= $amount_cash;
    //                }
    //                $dat2 = array(
    //                    "JV_ID" => $jv_old,
    //                    "Transaction_Reference" => $this->info['Purchase_Invoice_ID'],
    //                    "Transaction_Account" => $this->info['Check_Account'],
    //                    "Transaction_Type" => "Credit",
    //                    "Transaction_Amount" => $amount_b,
    //                    "Transaction_Date" => $this->info['Purchase_Date'],
    //                    "Currency_ID" => $this->info['Currency_ID'],
    //                    "Logged_ID" => $this->info[0],
    //                    "Transaction_Description" => $desc_old,
    //                    "Current_Ex_Rate" => "0",
    //                    "main_id" => $purchase_invoice_id,
    //                    "main_type" => "pur"
    //                );
    //                JV::addTransaction($dat2);
    //                $this->info['Check_Amount'] -= $amount_b;
    //            }
    //            $dat2 = array(
    //                "JV_ID" => $jv_old,
    //                "Transaction_Reference" => $this->info['Purchase_Invoice_ID'],
    //                "Transaction_Account" => $this->info['Card_Account'],
    //                "Transaction_Type" => "Credit",
    //                "Transaction_Amount" => $amount_ch,
    //                "Transaction_Date" => $this->info['Purchase_Date'],
    //                "Currency_ID" => $this->info['Currency_ID'],
    //                "Logged_ID" => $this->info[0],
    //                "Transaction_Description" => $desc_old,
    //                "Current_Ex_Rate" => "0",
    //                "main_id" => $purchase_invoice_id,
    //                "main_type" => "pur"
    //            );
    //            JV::addTransaction($dat2);
    //            $this->info['Card_Amount'] -= $amount_ch;
    //        }
    //
    //        $dat3 = array(
    //            "JV_ID" => $jv,
    //            "Transaction_Reference" => $purchase_id,
    //            "Transaction_Account" => $purchase_account,
    //            "Transaction_Type" => "Debit",
    //            "Transaction_Amount" => $actual_amount,
    //            "Transaction_Date" => $this->info['Purchase_Date'],
    //            "Currency_ID" => $this->info['Currency_ID'],
    //            "Logged_ID" => $this->info[0],
    //            "Transaction_Description" => $desc,
    //            "Current_Ex_Rate" => "0",
    //            "main_id" => $purchase_id,
    //            "main_type" => "apr"
    //        );
    //        JV::addTransaction($dat3, "1");
    //        $dat4 = array(
    //            "JV_ID" => $jv,
    //            "Transaction_Reference" => $purchase_id,
    //            "Transaction_Account" => $suppAccount,
    //            "Transaction_Type" => "Credit",
    //            "Transaction_Amount" => $rem,
    //            "Transaction_Date" => $this->info['Purchase_Date'],
    //            "Currency_ID" => $this->info['Currency_ID'],
    //            "Logged_ID" => $this->info[0],
    //            "Transaction_Description" => $desc,
    //            "Current_Ex_Rate" => "0",
    //            "main_id" => $purchase_id,
    //            "main_type" => "apr"
    //        );
    //        JV::addTransaction($dat4, "1");
    //        $dat5 = array(
    //            "JV_ID" => $jv,
    //            "Transaction_Reference" => $purchase_id,
    //            "Transaction_Account" => $this->info['Card_Account'],
    //            "Transaction_Type" => "Credit",
    //            "Transaction_Amount" => $this->info['Card_Amount'],
    //            "Transaction_Date" => $this->info['Purchase_Date'],
    //            "Currency_ID" => $this->info['Currency_ID'],
    //            "Logged_ID" => $this->info[0],
    //            "Transaction_Description" => $desc,
    //            "Current_Ex_Rate" => "0",
    //            "main_id" => $purchase_id,
    //            "main_type" => "apr"
    //        );
    //        JV::addTransaction($dat5, "1");
    //        $dat6 = array(
    //            "JV_ID" => $jv,
    //            "Transaction_Reference" => $purchase_id,
    //            "Transaction_Account" => $this->info['Check_Account'],
    //            "Transaction_Type" => "Credit",
    //            "Transaction_Amount" => $this->info['Check_Amount'],
    //            "Transaction_Date" => $this->info['Purchase_Date'],
    //            "Currency_ID" => $this->info['Currency_ID'],
    //            "Logged_ID" => $this->info[0],
    //            "Transaction_Description" => $desc,
    //            "Current_Ex_Rate" => "0",
    //            "main_id" => $purchase_id,
    //            "main_type" => "apr"
    //        );
    //        JV::addTransaction($dat6, "1");
    //        $dat7 = array(
    //            "JV_ID" => $jv,
    //            "Transaction_Reference" => $purchase_id,
    //            "Transaction_Account" => $this->info['Cash_Account'],
    //            "Transaction_Type" => "Credit",
    //            "Transaction_Amount" => $this->info['Cash_Amount'],
    //            "Transaction_Date" => $this->info['Purchase_Date'],
    //            "Currency_ID" => $this->info['Currency_ID'],
    //            "Logged_ID" => $this->info[0],
    //            "Transaction_Description" => $desc,
    //            "Current_Ex_Rate" => "0",
    //            "main_id" => $purchase_id,
    //            "main_type" => "apr"
    //        );
    //        JV::addTransaction($dat7, "1");
    //        foreach ($this->info['Products'] as $item) {
    //            $productID = $item['Product_ID'];
    //            $product_quantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $productID);
    //            $costdata = [
    //                "Product_ID" => $productID,
    //                "Quantity" => $product_quantity,
    //                "Quantity_Current" => $item['Item_Quantity'],
    //                "UOM_ID" => $item['UOM_ID'],
    //                "Unit_Cost" => $item['Item_Price'],
    //                "Currency_ID" => $this->info['Currency_ID'],
    //                "Depot_ID" => $depot_id,
    //                "Type" => "1",
    //                "Date" => $this->info['Purchase_Date'],
    //                "Logged_ID" => $this->info[0],
    //                "Operation" => "+"
    //            ];
    //            self::addCostData($costdata);
    //            $prod_insert = [
    //                &$purchase_id,
    //                &$productID,
    //                &$product_quantity,
    //                &$item['Item_Price'],
    //                &$item['Product_Total_Price'],
    //                &$item['Item_Discount'],
    //                &$item['Item_Quantity'],
    //                &$item['UOM_ID']
    //            ];
    //            $this->db->prepare_Stmt("
    //                                        INSERT
    //                                            INTO
    //                                                tbl_mgt_logs_backups_details
    //                                            (
    //                                                ID_Auto,
    //                                                Item_ID,
    //                                                Item_Quantity,
    //                                                Item_Price,
    //                                                Item_Total_Price,
    //                                                Item_Discount,
    //                                                Item_Quantity_Current,
    //                                                UOM_ID
    //                                            )
    //                                                VALUES
    //                                        (
    //                                                ?,?,?,?,?,?,?,?
    //                                        )
    //                                ", $prod_insert);
    //
    //            if ('Purchase_Invoice_ID' == 0) {
    //                $quant = [
    //                    &$product_quantity,
    //                    &$productID
    //                ];
    //                $this->db->prepare_Stmt("
    //                                    UPDATE 
    //                                            tbl_stock_products
    //                                    SET 
    //                                            Product_Quantity =  Product_Quantity + ?
    //                                    WHERE 
    //                                            Product_ID       = ?
    //
    //                                    ", $quant);
    //
    //                $location = [
    //                    &$productID,
    //                    &$depot_id,
    //                    &$product_quantity,
    //                    &$product_quantity
    //                ];
    //                $this->db->prepare_Stmt("INSERT INTO tbl_stock_product_location
    //                                                (
    //                                                        Location_Product_ID,
    //                                                        Product_Depot_ID,
    //                                                        Product_Depot_Quantity
    //                                                )
    //                                                        VALUES
    //                                                (
    //                                                        ?,?,?
    //                                                )
    //                                            ON DUPLICATE KEY
    //                                            UPDATE 
    //                                                                    Product_Depot_Quantity = Product_Depot_Quantity + ?
    //
    //                                                ", $location);
    //            }
    //        }
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("COMMIT");
    //            return $purchase_id;
    //        } else {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("ROLLBACK");
    //        }
    //        return array_unique($error);
    //    }

    public function getPurchaseNumbers() {
        $data = array();
        $today = Date::getToday();
        $totalPrice = 0;


        $query1 = $this->db->query('SELECT
                                        COUNT(Purchase_ID) AS count
                                    FROM
                                        tbl_inventory_purchases
                                    WHERE
                                        Purchase_Date = "' . $today . '"


                                    ');
        $Pur = $this->db->assoc($query1);
        $PurNb = $Pur['count'];


        $Legal = $this->db->query('SELECT
                                        Purchase_ID,
                                        Purchase_Net_Total AS Total,
                                        Currency_ID
                                    FROM
                                        tbl_inventory_purchases
                                    WHERE
                                        Purchase_Date = "' . $today . '"
                                    ');
        while ($row = $this->db->assoc($Legal)) {

            $totalPrice += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Total']);
        }



        $data['count'] = $PurNb;
        $data['Total'] = $totalPrice;
        return $data;
    }

    //    private function returnExactBalance($code, $currency_id, $from_date, $to_date, $opening_balance = 1, $back_up = false) {
    //        $report = new Report();
    //        $cust_account_code = JV::getAccountCodeByID($code);
    //        $balance = $report->returnExactBalance($cust_account_code, $currency_id, $from_date, $to_date, $opening_balance, $back_up)['Balance'];
    //        if ($balance < 0)
    //            $balance = 0;
    //        return $balance;
    //    }
    //    public function getPurchaseAccounts() {
    //        $data = array();
    //        $query = $this->db->query('SELECT 
    //                                        *
    //                                    FROM 
    //                                        tbl_chart_of_accounts
    //                                    WHERE 
    //                                        LEFT(Account_Code,3) = 601
    //                ');
    //        while ($row = $this->db->assoc($query))
    //            $data[] = $row;
    //        return $data;
    //    }

    public function getPurchaseByDueDate($week = null, $month = null, $year = null) {
        $data = array();
        $totalPrice = 0.0;
        $condition = '';
        $today = Date::getToday();
        $default_currency = CurrencyFactory::getDefaultCurrency();
        $Currency_Symbol = $this->db->query('SELECT Currency_Symbol FROM tbl_common_currency WHERE Currency_ID = "' . $default_currency . '"');
        $currency_row = $this->db->assoc($Currency_Symbol);
        $curr_symbol = $currency_row['Currency_Symbol'];
        $year = date("Y", strtotime($today)); // get the year from today
        $month = date("m", strtotime($today)); // get the month from today
        if (!is_null($year)) {
            $condition .= 'AND YEAR(p.Purchase_Due_Date)  ="' . $year . '"';
        }

        if (!is_null($month)) {
            $condition .= 'AND MONTH(p.Purchase_Due_Date)  ="' . $month . '"';
        }

        if (!is_null($week)) {

            $condition .= ' AND WEEKOFYEAR(p.Purchase_Due_Date)="' . $week . '"';
        }

        $query = $this->db->query('SELECT 
									    p.Purchase_ID,
                                        p.Purchase_Net_Total ,
                                        p.Purchase_Due_Date ,
                                        p.Currency_ID,
                                        p.Purchase_Paid_Amount,
										c.Currency_Symbol,
										cu.Supplier_ID,
										cu.Supplier_Name,
										cu.Supplier_Email,
										cu.Supplier_Phone,
										cu.Supplier_Company


									FROM	
										   tbl_inventory_purchases p
								    LEFT JOIN
											tbl_common_currency c
									ON
										  p.Currency_ID= c.Currency_ID
								    LEFT JOIN
											tbl_stock_suppliers cu
									ON 
										p.Supplier_ID = cu.Supplier_ID
								    WHERE
									p.Purchase_Net_Total > p.Purchase_Paid_Amount



									' . $condition);
        $count = 0;
        while ($row = $this->db->assoc($query)) {
            $count++;

            $totalPrice += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Purchase_Net_Total']);

            $data[] = $row;
        }
        $data['Total'] = $totalPrice;
        $data['Count'] = $count;
        $data['Currency_Symbol'] = $curr_symbol;
        return $data;
    }

    public function addPurchaseOrder() {
        $error = token_unique::is_valid_token();
        if (!empty($error))
            return $error;
//        if (!empty($this->info['unique_id'])) {
//            if (!isset(smc_session()['duplicate_check'][$this->info['unique_id']])) {
//                $error = array();
//                $error[0] = CommonLanguage::getMessage('duplicate_record');
//                return $error;
//            } else {
//                unset(smc_session()['duplicate_check'][$this->info['unique_id']]);
//            }
//        }
        $is_actual = isset($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'order', 'start_date' => $this->info['Invoice_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Invoice_Date'], $this->info['Invoice_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        $web_api_ord_id = isset($this->info['web_api_ord_id']) ? $this->info['web_api_ord_id'] : 0;
        $web_api_user_id = isset($this->info['web_api_user_id']) ? $this->info['web_api_user_id'] : 0;

        $logged_id = !empty($this->info['Logged_ID']) ? $this->info['Logged_ID'] : smc_session()['user_logged_id'];
        $depot_id = $this->info['Depot_ID'];
        $app_user_id = isset($this->info['app_user_id']) ? $this->info['app_user_id'] : 0;
        $sale_app_id = isset($this->info['sale_app_id']) ? $this->info['sale_app_id'] : 0;
        $this->info['supp_class_id'] = isset($this->info['supp_class_id']) ? $this->info['supp_class_id'] : 0;
        $this->info['job_id'] = isset($this->info['job_id']) ? $this->info['job_id'] : 0;
        $this->info['project_id'] = isset($this->info['project_id']) ? $this->info['project_id'] : 0;
        $this->info['quotation_id'] = isset($this->info['quotation_id']) ? $this->info['quotation_id'] : NULL;
        $branch_id = isset($this->info['branch_id']) ? $this->info['branch_id'] : CommonBusiness::getBranchByDepot($depot_id);
        if (isset($this->info['sale_prefix']))
            $sale_prefix = $this->info['sale_prefix'];
        else {
            $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'];
            $sale_prefix = smc_session()['user_accounts']['serial_prefix'] ? smc_session()['user_accounts']['serial_prefix'] : $branch_prefix;
        }

        $Person_ID = $this->info['Customer_ID'];
        $sale_num = isset($this->info['Sale_Number']) ? $this->info['Sale_Number'] : self::getMaxOrder($this->info['is_quotation'], $this->info['IsSales'], $sale_prefix, $is_actual);
        if (isset($this->info['Invoice_Due_Date'])) {
            $Sale_Due_Date = $this->info['Invoice_Due_Date'];
        } else {
            $Sale_Due_Date = $this->info['Invoice_Date'];
        }
        $Invoice_Currency = $this->info['Invoice_Currency'];
        $mydate = date("Y-m-d H:i:s");
        $rate = !empty($this->info['Sale_Currency_Rate']) ? $this->info['Sale_Currency_Rate'] : CurrencyFactory::getLastExRate($Invoice_Currency);
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';
        $year_id = $is_actual ? $this->year_id_actual : $this->year_id;
        $sales_pur_order_id = !empty($this->info['sales_pur_order_id']) ? $this->info['sales_pur_order_id'] : null;
        $this->info['total_cost'] = !empty($this->info['total_cost']) ? $this->info['total_cost'] : 0;
        $delivery_date = !empty($this->info['order_delivery_date']) ? $this->info['order_delivery_date'] : NULL;
        $extra_cost = !empty($this->info['extra_cost']) ? $this->info['extra_cost'] : 0;
        $this->info['postponed_status_id'] = !empty($this->info['postponed_status_id']) ? $this->info['postponed_status_id'] : NULL;
        $this->info['postponed_date_time'] = (!empty($this->info['postponed_date_time']) && !empty($this->info['postponed_status_id'])) ? $this->info['postponed_date_time'] : NULL;
        $this->info['postponed_note'] = !empty($this->info['postponed_note']) ? $this->info['postponed_note'] : NULL;
        $customer_name_alias = isset($this->info['customer_name_alias']) ? $this->info['customer_name_alias'] : '';
        $customer_address_alias = isset($this->info['customer_address_alias']) ? $this->info['customer_address_alias'] : '';
        $this->info['shipping'] = isset($this->info['shipping']) ? $this->info['shipping'] : 0;
        $this->info['current_invoice_type'] = !empty($this->info['current_invoice_type']) ? $this->info['current_invoice_type'] : null;
        $driver_id = isset($this->info['driver_id']) ? $this->info['driver_id'] : 0;

        $data = [
            &$sale_num, &$Person_ID,
            &$this->info['Invoice_Date'], &$logged_id, &$Invoice_Currency, &$rate, &$depot_id, &$branch_id,
            &$this->info['IsSales'], &$this->info['is_quotation'], &$sale_app_id, &$app_user_id, &$Sale_Due_Date, &$logged_id,
            &$mydate, &$mydate, &$sale_prefix, &$this->info['Invoice_VAT'], &$this->info['Invoice_Discount'], &$this->info['discount_amount'],
            &$this->info['Invoice_Net_Total'], &$this->info['Invoice_Sub_Total'],
            &$this->info['Invoice_Description'], &$is_actual, &$year_id, &$this->info['Class_ID'], &$this->info['supp_class_id'],
            &$this->info['job_id'], &$this->info['project_id'], &$this->info['total_cost'],
            &$this->info['quotation_id'], &$sales_pur_order_id, &$delivery_date, &$extra_cost, &$web_api_ord_id, &$web_api_user_id,
            &$this->info['postponed_status_id'], &$this->info['postponed_date_time'], &$this->info['postponed_note'],
            $customer_name_alias, $customer_address_alias, $this->info['shipping'], $this->info['current_invoice_type'],$this->info['po'], $this->info['project_name_inv'], $this->info['job_inv'], $this->info['project_code'], $this->info['our_ref'], $this->info['supply_date']
            ,$driver_id
            ,&$this->info['from_place']
            ,&$this->info['to_place']
        ];
        $this->db->prepare_Stmt('INSERT INTO `tbl_purchase_order`(`Order_ID_Auto`, `Supplier_ID`, 
            `Order_Date`, `Status_ID`, `Logged_ID`, `Currency_ID`, `current_rate`, `Depot_ID`, `branch_id`,
            `is_sales`, `is_quotation`, `sale_app_id`, `app_user_id`, `sale_due_date`, `created_logged_id`,
            `date_time`, `date_created`, `sale_prefix`, `total_vat`, `discount_percent`, `discount_amount`,
            `net_total`, `sub_total`, `order_description`, `is_actual`,current_year_id,Class_ID,supp_class_id,
            job_id,project_id,total_cost,quotation_id,sales_pur_order_id,delivery_date,extra_cost,web_api_ord_id,web_api_user_id,
            postponed_status_id,postponed_date_time,postponed_note,customer_name_alias,customer_address_alias,shipping,invoice_type_id,po,project_name_inv,job_inv,project_code,our_ref,supply_date,driver_id,from_place,to_place) 
            values (?,?,?,1,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ', $data);

        $Sale_ID = $this->db->id();
        $is_converted = (!empty($this->info['is_qto']) && $this->info['is_qto']) ? 1 : 0;
        if ($is_converted == 1) {
            $this->db->prepare_Stmt('update tbl_purchase_order set is_converted = 1 where Order_ID = ?', [&$this->info['quotation_id']]);
        }

        foreach ($this->info['Products'] as $item) {
            //            $prod_arr
            $ProductID = $item['Product_ID'];
            $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $item['Product_ID']);
            $ProductDiscount = $item['Item_Discount'];
            $ProductNetPrice = $item['Item_Price'];
            $Product_Total_Price = $item['Product_Total_Price'];
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';
            $disc_amount = $ProductQuantity * $ProductNetPrice * $ProductDiscount / 100;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $item['class_id'] = !empty($item['class_id']) ? $item['class_id'] : $this->info['supp_class_id'];
            $item['item_cost'] = !empty($item['item_cost']) ? $item['item_cost'] : 0;
            $item['other_cost'] = !empty($item['other_cost']) ? $item['other_cost'] : 0;
            $prod = [&$Sale_ID, &$ProductID, &$ProductQuantity, &$item['Item_Quantity'], &$item['UOM_ID'],
                &$ProductNetPrice, &$ProductDiscount,
                &$Product_Total_Price, &$item['vat_percent'],
                &$item['vat_val'], &$Product_Description, &$disc_amount, &$lot_nb, &$serial_nb, &$item['class_id'], &$item['item_cost'], &$item['other_cost'], &$item['from_time'], &$item['to_time'], &$item['modify_date']
                , &$item['driver_id']
                , &$item['n_width']
                , &$item['n_height']
                , &$item['n_total']
            
            ];
            $this->db->prepare_Stmt("INSERT INTO `tbl_purchase_order_details`( `Order_ID`,
                `Item_ID`, `Quantity`, `Item_Quantity_Current`, `UOM_ID`, `Unit_Price`, `discount_percent`,
                 `total_price`, `vat_percent`, `vat_amount`, `note`,discount_amount,lot_nb,serial_nb,
                 supp_class_id,item_cost,other_cost,from_time,to_time,modify_date
                 ,driver_id
                 ,n_width
                 ,n_height
                 ,n_total
                 
                 ) 
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $prod);
            $new_entry_id = $this->db->id();
            if (!empty($item['criteria_details'])) {
                $criteria_details = $item['criteria_details'];
                foreach ($criteria_details as $details) {
                    $this->db->prepare_Stmt("INSERT INTO
                                        tbl_order_product_criteria 
                                        (Entry_ID,Quantity,criteria_detail_id,criteria_price,criteria_note)
                                        VALUES
                                        (?,?,?,?,?)
                    ", [&$new_entry_id, &$details['Quantity'], &$details['criteria_detail_id'],
                        &$details['criteria_price'], &$details['criteria_note']]);
                }
            }
            //              $error = $this->db->error();
            //              print_r($error);
        }

        $error = $this->db->error();
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query("COMMIT");
            token_unique::remove_token();
            return [$Sale_ID, ($sale_prefix . $sale_num)];
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query("ROLLBACK");
            return array_unique($error);
        }
    }

    public function deleteQuotationOrder() {
        $query = $this->db->query('select Order_Date,is_actual from tbl_purchase_order 
                where Order_ID = "' . $this->info['Order_ID'] . '"');
        $row = $this->db->assoc($query);
        $check = CommonFunctions::check_lock_data(['type' => 'order', 'start_date' => $row['Order_Date'], 'is_actual' => $row['is_actual']]);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
//        die('here');
        $this->db->query('START TRANSACTION');
        $invoice_count = $quotation_count = $versions_count = $delivery_count = 0;
        $invoice_query = $this->db->query('select * from tbl_invoices 
                                            where order_id = "' . $this->info['Order_ID'] . '" limit 1');
        $invoice_count = $this->db->rowsno($invoice_query);
        if ($this->info['is_quotation'] == 1) {
            $order_query = $this->db->query('select * from tbl_purchase_order 
                                            where quotation_id = "' . $this->info['Order_ID'] . '" limit 1');
            $quotation_count = $this->db->rowsno($order_query);
            if ($this->info['is_sales'] == 1) {
                $versions_query = $this->db->query('select * from tbl_versions 
                                            where main_id = "' . $this->info['Order_ID'] . '" and main_type = "sqo" limit 1');
                $versions_count = $this->db->rowsno($versions_query);
            }
        } else {
            $delivery_query = $this->db->query('select * from tbl_purchase_order 
                                            where quotation_id = "' . $this->info['Order_ID'] . '" limit 1');
            $delivery_count = $this->db->rowsno($delivery_query);
            if ($this->info['is_sales'] == 1) {
                $order_query = $this->db->query('select * from tbl_purchase_order 
                                            where sales_pur_order_id = "' . $this->info['Order_ID'] . '" limit 1');
                $quotation_count = $this->db->rowsno($order_query);
            }
        }
        if ($quotation_count > 0 || $versions_count > 0 || $invoice_count > 0 || $delivery_count > 0)
            return [CommonLanguage::getMessage('unable_delete_quotation')];
        //        echo '<pre>';
        //        print_r($this->info);
        //        die('okffff');
        $this->db->prepare_Stmt('delete from tbl_purchase_order_details where Order_ID = ?', [&$this->info['Order_ID']]);
        $this->db->prepare_Stmt('delete from tbl_purchase_order where Order_ID = ?', [&$this->info['Order_ID']]);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query("COMMIT");
        } else {
            $this->db->query("ROLLBACK");
        }
        return array_unique($error);
    }

    //    public function addPurchaseOrder() {
    //        if (!$this->stop_transaction_start_end)
    //            $this->db->query('START TRANSACTION;');
    ////        $branch_id = CommonBusiness::getBranchByDepot($this->info['Depot_ID']);
    //        $logged_id = smc_session()['user_logged_id'];
    //        $rate = CurrencyFactory::getLastExRate($this->info['Currency_ID']);
    //        $mydate = date("Y-m-d H:i:s");
    //        $app_user_id = isset($this->info['app_user_id']) ? $this->info['app_user_id'] : 0;
    //        $sale_app_id = isset($this->info['sale_app_id']) ? $this->info['sale_app_id'] : 0;
    //        $branch_id = isset($this->info['branch_id']) ? $this->info['branch_id'] : CommonBusiness::getBranchByDepot($this->info['Depot_ID']);
    //        if (isset($this->info['sale_prefix']))
    //            $sale_prefix = $this->info['sale_prefix'];
    //        else {
    //            $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'];
    //            $sale_prefix = smc_session()['user_accounts']['serial_prefix'] ? smc_session()['user_accounts']['serial_prefix'] : $branch_prefix;
    //        }
    //        $OrderIDAuto = self::getMaxOrder($this->info['is_quotation'], $this->info['IsSales'],$sale_prefix);
    //
    //        $order = [&$OrderIDAuto, &$this->info['Vendor_ID'], &$this->info['Order_Date'], &$this->info['Currency_ID'],
    //            &$rate, &$this->info['Depot_ID'], &$branch_id, &$this->info['IsSales'], &$logged_id, &$logged_id,
    //            &$mydate, &$mydate, &$this->info['is_quotation'], &$sale_app_id, &$app_user_id, $this->info['sale_due_date']];
    //        $this->db->prepare_Stmt("INSERT INTO tbl_purchase_order (Order_ID_Auto,Supplier_ID,Order_Date,Currency_ID,
    //            current_rate,Depot_ID,branch_id,is_sales,Logged_ID,created_logged_id,date_time,date_created,is_quotation,
    //            sale_app_id,app_user_id,sale_due_date) 
    //            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $order);
    //        $parent_id = $this->db->id();
    //
    //        if (is_array($this->info['Items'])) {
    //            foreach ($this->info['Items'] as $item) {
    //                $product_quantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Quantity'], $item['Item_ID']);
    //                $details = [&$parent_id, &$item['Item_ID'], &$product_quantity, &$item['Quantity'], &$item['UOM_ID'], &$item['Unit_Price']];
    //                $this->db->prepare_Stmt("INSERT INTO tbl_purchase_order_details (Order_ID,Item_ID,Quantity,Item_Quantity_Current,UOM_ID,Unit_Price) 
    //                    VALUES (?,?,?,?,?,?) ", $details);
    //            }
    //        }
    //
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("COMMIT");
    //        } else {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("ROLLBACK");
    //        }
    //        return array_unique($error);
    //    }

    public function getMaxOrder($is_quotation, $is_sales, $sale_prefix, $is_actual) {
        $query = $this->db->query('SELECT MAX(Order_ID_Auto) AS Entry_ID 
            FROM tbl_purchase_order where  is_quotation = "' . $is_quotation . '"
                and is_sales = "' . $is_sales . '" and sale_prefix = "' . $sale_prefix . '" and is_actual = "' . $is_actual . '"');
        $row = $this->db->assoc($query);
        if (!empty($row))
            $order = $row['Entry_ID'] + 1;
        else
            $order = 1;

        return $order;
    }

    public function getPurchaseOrderDetails($ID) {

        $data = array();
        $query = $this->db->query('SELECT 
                                       *
                                   FROM 
                                        delivered_purchase_order
                                    WHERE 
                                        Order_ID = "' . smc_escape($ID) . '"
				');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    //    public function getOrderDetails($flag, $id) {
    //        $table = '';
    //        $data = array();
    //        if ($flag == 1) {
    //            $table = ' purchase_order_details ';
    //        } else {
    //            $table = ' sales_order_detailes ';
    //        }
    //        $query = $this->db->query('SELECT * FROM ' . $table . ' WHERE Order_ID = "' . $id . '"');
    //        while ($row = $this->db->assoc($query)) {
    //            $data[] = $row;
    //        }
    //        return $data;
    //    }

    public function editPurchase($return_inv_num = false) {
        $is_actual = !empty($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'purchase', 'start_date' => $this->info['Purchase_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Purchase_Date'], $this->info['Purchase_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        $mydate = date("Y-m-d H:i:s");
        $today = Date::getToday();
        $this->info['Logged_ID'] = Session::getUserID();
        $jv_query = $this->db->query("SELECT DISTINCT JV_ID FROM tbl_accounting_transactions  WHERE main_id='" . $this->info['Invoice_ID_Auto'] . "' AND main_type= 'pur' ");
        $jv_assoc = $this->db->assoc($jv_query);
        if (!empty($jv_assoc))
            $jv = $jv_assoc['JV_ID'];
        else
            $jv = JV::returnJV($is_actual);
        $this->db->prepare_Stmt("DELETE FROM tbl_accounting_transactions  WHERE main_id= ? AND main_type= 'pur' ", [&$this->info['Invoice_ID_Auto']]);
        $this->info['Other_Amount'] = !empty($this->info['Other_Amount']) ? $this->info['Other_Amount'] : 0;
        $paid = $this->info['Card_Amount'] + $this->info['Cash_Amount'] + $this->info['Check_Amount'] + $this->info['Other_Amount'];
        $remaining = $this->info['Purchase_Net_Total'] - $paid;
        if (smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 1) {
            $paid = 0;
            $remaining = $this->info['Purchase_Net_Total'];
        }
        $suppAccount = $this->info['Supplier_Account'];
        $this->info['currency_round'] = !empty($this->info['currency_round']) ? $this->info['currency_round'] : 0;
        //
        if (empty($this->info['is_noqty']))
            $this->edit_old_details_qty_cost($this->info['Invoice_ID_Auto']);
        //
        $query = $this->db->query("SELECT date_time,created_logged_id,date_created,Purchase_ID
        from tbl_inventory_purchases  WHERE Purchase_ID_Auto = '" . $this->info['Invoice_ID_Auto'] . "'");
        $pur_old = $this->db->assoc($query);
        $pur_num = $pur_old['Purchase_ID'];
        $old_date_created = $pur_old['date_created'];
        $old_created_logged_id = $pur_old['created_logged_id'];
        $old_date_time = $pur_old['date_time'];
        $this->info['vat1_total'] = !empty($this->info['vat1_total']) ? $this->info['vat1_total'] : $this->info['Invoice_VAT'];
        $this->info['vat2_total'] = !empty($this->info['vat2_total']) ? $this->info['vat2_total'] : 0;
        $driver_id = !empty($this->info['driver_id']) ? $this->info['driver_id'] : 0;
        $job_trans_type = smc_session()['default_setting']['job_transaction_type'];
        $person_job = ($job_trans_type == 0 || $job_trans_type == 1 ? $this->info['job_id'] : 0);
        $opposite_job = ($job_trans_type == 0 || $job_trans_type == 2 ? $this->info['job_id'] : 0);

        $branch_id = CommonBusiness::getBranchByDepot($this->info['Depot_ID']);
        $rate = !empty($this->info['Invoice_Currency_Rate']) ? $this->info['Invoice_Currency_Rate'] : CurrencyFactory::getLastExRate($this->info['Currency_ID']);
        $second_rate = !empty($this->info['second_currency_rate']) ? $this->info['second_currency_rate'] : CurrencyFactory::getSecondCurrencyLastExRate($this->info['Currency_ID']);

        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';
        $this->info['ship_bill_nb'] = !empty($this->info['ship_bill_nb']) ? $this->info['ship_bill_nb'] : '';
        $this->info['ship_date'] = !empty($this->info['ship_date']) ? $this->info['ship_date'] : '';
        $this->info['container_nb'] = !empty($this->info['container_nb']) ? $this->info['container_nb'] : '';
        $this->info['container_size'] = !empty($this->info['container_size']) ? $this->info['container_size'] : '';
        $this->info['ctn_nb'] = !empty($this->info['ctn_nb']) ? $this->info['ctn_nb'] : '';
        $this->info['ctn_date'] = !empty($this->info['ctn_date']) ? $this->info['ctn_date'] : '';

        $purchase_account = $this->info['Account_Code'];
        $up_main = [
            &$this->info['Purchase_Date'],
            &$this->info['Purchase_Due_Date'],
            &$this->info['Currency_ID'],
            &$this->info['Supplier_ID'],
            &$this->info['Purchase_Sub_Total'],
            &$this->info['Purchase_Net_Total'],
            &$this->info['Purchase_Discount'],
            &$this->info['discount_amount'],
            &$this->info['Depot_ID'],
            &$this->info['Supplier_Invoice_ID'],
            &$this->info['Invoice_Description'],
            &$paid,
            &$this->info['Invoice_VAT'],
            &$this->info['vat1_total'],
            &$this->info['vat2_total'],
            &$this->info['shipping'],
            &$rate, &$second_rate,
            &$this->info[0],
            &$branch_id,
            &$purchase_account,
            &$this->info['extra_cost'],
            &$this->info['cost_dist_method'],
            &$this->info['job_id'],
            &$this->info['project_id'],
            &$this->info['Class_ID'],
            &$mydate,
            &$this->info['currency_round'],
            $this->info['ship_bill_nb'], $this->info['ship_date'], $this->info['container_nb'],
            $this->info['container_size'], $this->info['ctn_nb'], $this->info['ctn_date'],
            &$driver_id,
            $this->info['from_place'],
            $this->info['to_place'],
            &$this->info['Invoice_ID_Auto']
        ];
        $this->db->prepare_Stmt("UPDATE 
                                    tbl_inventory_purchases 
                                SET
                                    Purchase_Date = ?,
                                    Purchase_Due_Date = ?,
                                    Currency_ID = ?,
                                    Supplier_ID = ?,
                                    Purchase_Sub_Total = ?,
                                    Purchase_Net_Total = ?,
                                    Purchase_Discount = ?,
                                    discount_amount = ?,
                                    Depot_ID = ?,
                                    Supplier_Invoice_ID = ?,
                                    Invoice_Description=?,
                                    Purchase_Paid_Amount = ?,
                                    Purchase_VAT = ?,vat1_total=?,vat2_total=?,
                                    Purchase_Shipping = ?,
                                    current_rate = ?,second_currency_rate=?,
                                    Logged_ID = ?,
                                    branch_id = ?,
                                    Account_ID = ?,
                                    extra_cost = ?,
                                    cost_dist_method = ?,
                                    job_id=?,project_id=?,Class_ID = ?,
                                    date_time=?,currency_round = ?,ship_bill_nb=?,ship_date=?,container_nb=?,
                                    container_size=?,ctn_nb=?,ctn_date=?,driver_id=?
                                    ,from_place =?
                                    ,to_place=?
                                WHERE 
                                    Purchase_ID_Auto = ?

                 ", $up_main);

        $update_stock = [&$this->info['Invoice_ID_Auto']];
        $arr_purchase = ['type' => 'pur', 'main_id' => $this->info['Invoice_ID_Auto'], 'action' => 1, 'date_time' => $mydate,
            'user_id' => smc_session()['user_logged_id']];
        CommonFunctions::add_user_log($arr_purchase);
        $this->db->prepare_Stmt('delete from tbl_purchase_extra_cost where purchase_id = "' . $this->info['Invoice_ID_Auto'] . '"');
        if (!empty($this->info['extra_cost_arr'])) {
            foreach ($this->info['extra_cost_arr'] as $ex) {
                $deb_acc = !empty($ex['debit_acc_id']) ? $ex['debit_acc_id'] : null;
                $cre_acc = !empty($ex['credit_acc_id']) ? $ex['credit_acc_id'] : null;
                $ex_second_rate = CurrencyFactory::getSecondCurrencyLastExRate($ex['currency_id']);
                $data_extra = [$this->info['Invoice_ID_Auto'], $ex['amount'], $ex['currency_id'], $ex['current_rate'], $ex_second_rate,
                    $ex['type'], $deb_acc, $cre_acc, $ex['note']];
                $this->db->prepare_Stmt('INSERT INTO `tbl_purchase_extra_cost`( `purchase_id`, `amount`,
                `currency_id`, `current_rate`, `second_currency_rate`,type,debit_acc_id,credit_acc_id,note)
                values(?,?,?,?,?,?,?,?,?)', $data_extra);
                if (!empty($deb_acc) && !empty($cre_acc)) {
                    $data_trans = ["JV_ID" => $jv,
                        "Transaction_Reference" => 'extra cost',
                        "Transaction_Account" => $deb_acc,
                        "Transaction_Type" => "Debit",
                        "Transaction_Amount" => $ex['amount'],
                        "Transaction_Date" => $this->info['Purchase_Date'],
                        "Currency_ID" => $ex['currency_id'],
                        "Logged_ID" => smc_session()['user_logged_id'],
                        "Transaction_Description" => $ex['note'],
                        "Current_Ex_Rate" => $ex['current_rate'],
                        "second_currency_rate" => $ex_second_rate,
                        "main_id" => $this->info['Invoice_ID_Auto'],
                        "main_type" => "pur",
                        "branch_id" => $branch_id,
                        "due_date" => $this->info['Purchase_Due_Date'],
                        "main_nb" => $pur_num,
                        "job_id" => $opposite_job,
                        "project_id" => $this->info['project_id'],
                        "user_ref" => $this->info['Supplier_Invoice_ID']
                    ];
                    JV::addTransaction($data_trans, $is_actual);
                    $data_trans = ["JV_ID" => $jv,
                        "Transaction_Reference" => 'extra cost',
                        "Transaction_Account" => $cre_acc,
                        "Transaction_Type" => "Credit",
                        "Transaction_Amount" => $ex['amount'],
                        "Transaction_Date" => $this->info['Purchase_Date'],
                        "Currency_ID" => $ex['currency_id'],
                        "Logged_ID" => smc_session()['user_logged_id'],
                        "Transaction_Description" => $ex['note'],
                        "Current_Ex_Rate" => $ex['current_rate'],
                        "second_currency_rate" => $ex_second_rate,
                        "main_id" => $this->info['Invoice_ID_Auto'],
                        "main_type" => "pur",
                        "branch_id" => $branch_id,
                        "due_date" => $this->info['Purchase_Due_Date'],
                        "main_nb" => $pur_num,
                        "job_id" => $opposite_job,
                        "project_id" => $this->info['project_id'],
                        "user_ref" => $this->info['Supplier_Invoice_ID']
                    ];
                    JV::addTransaction($data_trans, $is_actual);
                }
            }
        }

        $this->db->prepare_Stmt("DELETE FROM tbl_inventory_purchase_items  WHERE Purchase_ID_Auto = ?", $update_stock);

        $purchase_detail_ids = array();
        $prod_arr = array();
        $prod_ids_arr = array();
        $total_extra_cost = $this->info['extra_cost'] + $this->info['shipping'];
        CommonBusiness::update_trans_record_current('pur', $this->info['Invoice_ID_Auto']);
        foreach ($this->info['Products'] as $item) {
            $cost_percent = 0;
            if (!empty($total_extra_cost)) {
                if ($this->info['cost_dist_method'] == 0) {
                    $cost_percent = (($item['Item_Quantity'] == 0 || $this->info['total_qty'] == 0) ? 0 : ($item['Item_Quantity'] / $this->info['total_qty']));
                } else if ($this->info['cost_dist_method'] == 1) {
                    $cost_percent = (($item['Product_Total_Price'] == 0 || ($this->info['Purchase_Sub_Total'] * ((100 - $this->info['Purchase_Discount']) / 100)) == 0) ? 0 : ($item['Product_Total_Price'] / (($this->info['Purchase_Sub_Total'] * ((100 - $this->info['Purchase_Discount']) / 100)) /* - $this->info['shipping'] */)));
                } else if ($this->info['cost_dist_method'] == 2) {
                    $cost_percent = $item['cost_percent'] / 100;
                }
            }
            $item["vat2_percent"] = !empty($item["vat2_percent"]) ? $item["vat2_percent"] : 0;
            $item["vat2_amount"] = !empty($item["vat2_amount"]) ? $item["vat2_amount"] : 0;
            $item["additional_cost"] = !empty($item["additional_cost"]) ? $item["additional_cost"] : 0;

            $prod_ids_arr[] = $item['Product_ID'];
            $productID = $item['Product_ID'];
            $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $productID);
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';

            $prod_arr[] = array("product_id" => $item['Product_ID'],
                "total_amount" => ($item['Product_Total_Price']),
                "description" => $Product_Description, "vat_amount" => $item['vat_val']);
            $new_cost = ($item['additional_cost'] / $ProductQuantity) + ($item['Item_Price'] / ($ProductQuantity / $item['Item_Quantity']) * ((100 - $item['Item_Discount']) / 100) * ((100 - $this->info['Purchase_Discount']) / 100)) + ($ProductQuantity == 0 ? 0 : ($total_extra_cost * $cost_percent / $ProductQuantity));

            $expiry_date = !empty($item['expiry_date']) ? $item['expiry_date'] : null;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $item['is_service'] = !empty($item['is_service']) ? $item['is_service'] : 0;
            $item['iata_charges'] = !empty($item['iata_charges']) ? $item['iata_charges'] : 0;
            $item['fare_basis'] = !empty($item['fare_basis']) ? $item['fare_basis'] : 0;
            $item['taxes'] = !empty($item['taxes']) ? $item['taxes'] : 0;
            $item['farebasis_disc'] = !empty($item['farebasis_disc']) ? $item['farebasis_disc'] : 0;
            $depot_detail_id = !empty($item['depot_id']) ? $item['depot_id'] : $this->info['Depot_ID'];

            if (empty($item['delivery_id']) && empty($this->info['is_noqty'])) {
                $costdata = [
                    "Product_ID" => $productID,
                    "Quantity" => $ProductQuantity,
                    "Unit_Cost" => $new_cost,
                    "unit_price" => $item['Item_Price'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "date_time" => $old_date_time,
                    "date_time_now" => $mydate,
                    "current_rate" => $rate,
                    "depot_id" => $depot_detail_id,
                    "trans_date" => $this->info['Purchase_Date'],
                    "current_quantity" => $item['Item_Quantity'],
                    "uom_id" => $item['UOM_ID'],
                    "is_actual" => $is_actual,
                    "expiry_date" => $expiry_date,
                    "lot_nb" => $lot_nb,
                    "serial_nb" => $serial_nb,
                    "main_id" => $this->info['Invoice_ID_Auto'],
                    "is_service" => $item['is_service'],
                    "main_nb" => $pur_num,
                    "supplier_id" => $this->info['Supplier_ID']
                ];
                //            $error = $this->db->error();
                //        die(print_r($costdata));
                CommonBusiness::addCostByType($costdata, "edit_purchase_new");
            }
            $item['class_id'] = !empty($item['class_id']) ? $item['class_id'] : $this->info['Class_ID'];
            $item['delivery_id'] = !empty($item['delivery_id']) ? $item['delivery_id'] : null;
            $prod = [
                &$this->info['Invoice_ID_Auto'],
                &$productID,
                &$ProductQuantity,
                &$item['Item_Price'],
                &$item['Product_Total_Price'],
                &$item['Item_Discount'],
                &$item['vat_percent'],
                &$item['vat_val'],
                &$item['vat2_percent'],
                &$item['vat2_amount'],
                &$item['Item_Quantity'],
                &$item['UOM_ID'],
                &$Product_Description,
                &$item['cost_percent'],
                &$item['class_id'],
                &$new_cost, &$expiry_date,
                &$lot_nb, &$serial_nb, &$item['delivery_id'],
                &$item['iata_charges'], &$item['fare_basis'], &$item['taxes'], &$item['farebasis_disc'],
                &$depot_detail_id, $item['additional_cost']
                , $item['modify_date'], $item['vehicle_id'], $item['item_driver_id'],&$item['n_width'], &$item['n_height'], &$item['n_total']
            ];

            $this->db->prepare_Stmt("
                                        INSERT
                                        INTO
                                                tbl_inventory_purchase_items
                                        ( " . (!empty($item['entry_id']) ? 'Item_ID,' : '') . "
                                                Purchase_ID_Auto,
                                                Product_ID,
                                                Item_Quantity,
                                                Item_Price,
                                                Product_Total_Price,
                                                Item_Discount,
                                                vat_percent,
                                                vat_amount,vat2_percent,vat2_amount,
                                                Item_Quantity_Current,
                                                UOM_ID,
                                                product_description,cost_percent,
                                                supp_class_id,real_cost,expiry_date,lot_nb,serial_nb,Delivery_Report_ID,
                                                iata_charges,farebasis,taxes,farebasis_disc,depot_id,additional_cost,modify_date,vehicle_id,driver_id,n_width,n_height,n_total
                                    )
                                                VALUES
                                        (
                                               " . (!empty($item['entry_id']) ? '"' . $item['entry_id'] . '",' : '') . "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
                                        )
                                ", $prod);
            $pur_detail_id = $this->db->id();
            if (isset($item['invoice_detail_line']))
                $purchase_detail_ids[$item['invoice_detail_line']] = $pur_detail_id;
            if (empty($item['delivery_id']) && $item['is_service'] != 1 && empty($this->info['is_noqty'])) {
                $up_quan = [&$ProductQuantity, &$productID];
                $this->db->prepare_Stmt("UPDATE 
                                            tbl_stock_products 
                                    SET 
                                            Product_Quantity = Product_Quantity + ?
                                    WHERE 
                                            Product_ID = ? 
                                ", $up_quan);
                $dep_dat = [&$productID, &$depot_detail_id, &$ProductQuantity, &$ProductQuantity];
                $this->db->prepare_Stmt("INSERT INTO tbl_stock_product_location
                                                (
                                                        Location_Product_ID,
                                                        Product_Depot_ID,
                                                        Product_Depot_Quantity
                                                )
                                                        VALUES
                                                (
                                                        ?,?,?
                                                )
                                            ON DUPLICATE KEY
                                            UPDATE Product_Depot_Quantity = Product_Depot_Quantity + ?


                                                ", $dep_dat);
            }
            if (!empty($item['cost_arr'])) {
                $item['cost_arr'] = json_decode($item['cost_arr'], true);
                foreach ($item['cost_arr'] as $ex) {
                    $deb_acc = !empty($ex['debit_acc_id']) ? $ex['debit_acc_id'] : null;
                    $cre_acc = !empty($ex['credit_acc_id']) ? $ex['credit_acc_id'] : null;
                    $ex_second_rate = CurrencyFactory::getSecondCurrencyLastExRate($ex['currency_id']);
                    $data_extra = [$this->info['Invoice_ID_Auto'], $pur_detail_id, $ex['amount'], $ex['currency_id'], $ex['current_rate'], $ex_second_rate,
                        $ex['type'], $deb_acc, $cre_acc, $ex['note']];
                    $this->db->prepare_Stmt('INSERT INTO `tbl_purchase_extra_cost`( `purchase_id`,purchase_detail_id, `amount`,
                                `currency_id`, `current_rate`, `second_currency_rate`,type,debit_acc_id,credit_acc_id,note)
                                values(?,?,?,?,?,?,?,?,?,?)', $data_extra);
                    if (!empty($deb_acc) && !empty($cre_acc)) {
                        $data_trans = ["JV_ID" => $jv,
                            "Transaction_Reference" => 'extra cost',
                            "Transaction_Account" => $deb_acc,
                            "Transaction_Type" => "Debit",
                            "Transaction_Amount" => $ex['amount'],
                            "Transaction_Date" => $this->info['Purchase_Date'],
                            "Currency_ID" => $ex['currency_id'],
                            "Logged_ID" => smc_session()['user_logged_id'],
                            "Transaction_Description" => $ex['note'],
                            "Current_Ex_Rate" => $ex['current_rate'],
                            "second_currency_rate" => $ex_second_rate,
                            "main_id" => $this->info['Invoice_ID_Auto'],
                            "main_type" => "pur",
                            "branch_id" => $branch_id,
                            "due_date" => $this->info['Purchase_Due_Date'],
                            "main_nb" => $pur_num,
                            "job_id" => $opposite_job,
                            "project_id" => $this->info['project_id'],
                            "user_ref" => $this->info['Supplier_Invoice_ID']
                        ];
                        JV::addTransaction($data_trans, $is_actual);
                        $data_trans = ["JV_ID" => $jv,
                            "Transaction_Reference" => 'extra cost',
                            "Transaction_Account" => $cre_acc,
                            "Transaction_Type" => "Credit",
                            "Transaction_Amount" => $ex['amount'],
                            "Transaction_Date" => $this->info['Purchase_Date'],
                            "Currency_ID" => $ex['currency_id'],
                            "Logged_ID" => smc_session()['user_logged_id'],
                            "Transaction_Description" => $ex['note'],
                            "Current_Ex_Rate" => $ex['current_rate'],
                            "second_currency_rate" => $ex_second_rate,
                            "main_id" => $this->info['Invoice_ID_Auto'],
                            "main_type" => "pur",
                            "branch_id" => $branch_id,
                            "due_date" => $this->info['Purchase_Due_Date'],
                            "main_nb" => $pur_num,
                            "job_id" => $opposite_job,
                            "project_id" => $this->info['project_id'],
                            "user_ref" => $this->info['Supplier_Invoice_ID']
                        ];
                        JV::addTransaction($data_trans, $is_actual);
                    }
                }
            }
            //            $dep_dat = [&$ProductQuantity, &$productID, &$this->info['Depot_ID']];
            //            $this->db->prepare_Stmt("UPDATE 
            //                                        tbl_stock_product_location 
            //                                SET 
            //                                        Product_Depot_Quantity = Product_Depot_Quantity + ?
            //                                WHERE 
            //                                        Location_Product_ID = ? 
            //                                AND 
            //                                        Product_Depot_ID = ?
            //                                ", $dep_dat);
        }

        $prod_str =implode( ',',$prod_ids_arr);
        $prod_trans_arr = CommonBusiness::get_item_acc_transactions($prod_arr, $prod_str, 'pur', $purchase_account, $this->info['Purchase_Discount'], $this->info['shipping_account'], $this->info['shipping']);

        $suppName = $this->info['Supplier_Name'];
        $pur_ref = "Pur." . $pur_num;
        $curr_symbol = $this->info['CurrencySymbole'];
        $desc = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : 'Purchased products with ' . round(($this->info['Purchase_Net_Total'] + $this->info['shipping']), 2) . ' ' . $curr_symbol . ' from ' . $suppName;
        //         echo $suppAccount.'===';
        //        die();
        //        $s_account = JV::getAccountCodeByID($suppAccount);

        $supp_vat_account = Supplier::returnSuppVATAccount($this->info['Supplier_ID'])['Account_ID'];
        $amount_novat = $this->info['Purchase_Net_Total'] - $this->info['Invoice_VAT'];
        foreach ($prod_trans_arr as $trans) {
            //            $trans_desc = $trans[]
            if (isset($trans['main'])) {
                $trans_main = $trans['main'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => (empty($trans_main['ref']) ? 'pur' : $trans_main['ref']),
                    "Transaction_Account" => $trans_main['trans_account'],
                    "Transaction_Type" => "Debit",
                    "Transaction_Amount" => $trans_main['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info['Logged_ID'],
                    "date_created" => $old_date_created,
                    "created_logged_id" => $old_created_logged_id,
                    "Transaction_Description" => (empty($trans_main['trans_desc']) ? $desc : $trans_main['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $this->info['Invoice_ID_Auto'],
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "subtype" => "pur",
                    "main_nb" => $pur_num,
                    "job_id" => $opposite_job,
                    "project_id" => $this->info['project_id'],
                    "user_ref" => $this->info['Supplier_Invoice_ID']
                ];
                JV::addTransaction($data_trans, $is_actual);
            }


            if (isset($trans['person'])) {
                $trans_person = $trans['person'];
                $supp_amount = smc_session()['default_setting']['merge_cust_supp_accounts'] == 1 ? ($trans_person['trans_amount'] + $this->info['currency_round'] ) : $trans_person['trans_amount'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => $pur_ref,
                    "Transaction_Account" => $suppAccount,
                    "Transaction_Type" => "Credit",
                    "Transaction_Amount" => $supp_amount,
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info['Logged_ID'],
                    "date_created" => $old_date_created,
                    "created_logged_id" => $old_created_logged_id,
                    "Transaction_Description" => (empty($trans_person['trans_desc']) ? $desc : $trans_person['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $this->info['Invoice_ID_Auto'],
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "main_nb" => $pur_num,
                    "job_id" => $person_job,
                    "project_id" => $this->info['project_id'],
                    "user_ref" => $this->info['Supplier_Invoice_ID']
                ];
                JV::addTransaction($data_trans, $is_actual);
                //                 $error = $this->db->error();
                //            die(print_r($error));
            }
        }
        if (smc_session()['default_setting']['merge_cust_supp_accounts'] == 0) {
            $trans_type = $this->info['currency_round'] > 0 ? 'Credit' : 'Debit';
            $dat_12 = array(
                "JV_ID" => $jv,
                "Transaction_Reference" => $pur_ref,
                "Transaction_Account" => $suppAccount,
                "Transaction_Type" => $trans_type,
                "Transaction_Amount" => abs($this->info['currency_round']),
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "main_nb" => $pur_num,
                "job_id" => $person_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => $this->info['Supplier_Invoice_ID']
            );
            JV::addTransaction($dat_12, $is_actual);
        }
        $discount_account = $purchase_account;
        $trans_disc_type = $this->info['currency_round'] < 0 ? 'Credit' : 'Debit';
        $dat_12 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $discount_account,
            "Transaction_Type" => $trans_disc_type,
            "Transaction_Amount" => abs($this->info['currency_round']),
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $pur_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID']
        );
        
        $Invoice_Currency = &$this->info['Currency_ID'];
        $second_rate2 = $this->info['second_currency_rate'];
        $lebanon_vat_amount=smc_session()['default_setting']['lebanon_vat_amount'];
        if($Invoice_Currency == '144'){
            $second_rate2 = $lebanon_vat_amount;
        }

        JV::addTransaction($dat_12, $is_actual);
        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['vat1_total'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate2,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $pur_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID'],
            "subtype" => "vat1"
        );
        JV::addTransaction($dat_3, $is_actual);
        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['vat2_total'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $pur_num,
            "job_id" => $opposite_job,
            "project_id" => $this->info['project_id'],
            "user_ref" => $this->info['Supplier_Invoice_ID'],
            "subtype" => "vat2"
        );
        JV::addTransaction($dat_3, $is_actual);
        if (smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 0) {
            $dat_12 = array(
                "JV_ID" => $jv,
                "Transaction_Reference" => $pur_ref,
                "Transaction_Account" => $suppAccount,
                "Transaction_Type" => "Debit",
                "Transaction_Amount" => $this->info['Purchase_Net_Total'] - $remaining,
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "main_nb" => $pur_num,
                "job_id" => $person_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => $this->info['Supplier_Invoice_ID']
            );
            JV::addTransaction($dat_12, $is_actual);
            $dat_4 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'credit',
                "Transaction_Account" => $this->info['Card_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Card_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "credit",
                "main_nb" => $pur_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['card_user_ref']) ? $this->info['card_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_4, $is_actual);
            $dat_5 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'cash',
                "Transaction_Account" => $this->info['Cash_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Cash_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "cash",
                "main_nb" => $pur_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['cash_user_ref']) ? $this->info['cash_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_5, $is_actual);
            $dat_5 = [
                "JV_ID" => $jv,
                "Transaction_Reference" => 'other',
                "Transaction_Account" => $this->info['Other_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Other_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => $this->info['Purchase_Due_Date'],
                "subtype" => "other",
                "main_nb" => $pur_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['other_user_ref']) ? $this->info['other_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_5, $is_actual);
            $dat_6 = ["JV_ID" => $jv,
                "Transaction_Reference" => 'check',
                "Transaction_Account" => $this->info['Check_Account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $this->info['Check_Amount'],
                "Transaction_Date" => $this->info['Purchase_Date'],
                "Currency_ID" => $this->info['Currency_ID'],
                "Logged_ID" => $this->info['Logged_ID'],
                "date_created" => $old_date_created,
                "created_logged_id" => $old_created_logged_id,
                "Transaction_Description" => $desc,
                "Current_Ex_Rate" => $rate,
                "second_currency_rate" => $second_rate,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "main_type" => "pur",
                "branch_id" => $branch_id,
                "due_date" => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
                "value_date" => (empty($this->info['value_date']) ? '' : $this->info['value_date']),
                "check_nb" => empty($this->info['Check_Num']) ? '' : $this->info['Check_Num'],
                "subtype" => "check",
                "main_nb" => $pur_num,
                "job_id" => $opposite_job,
                "project_id" => $this->info['project_id'],
                "user_ref" => (!empty($this->info['check_user_ref']) ? $this->info['check_user_ref'] : $this->info['Supplier_Invoice_ID'])
            ];
            JV::addTransaction($dat_6, $is_actual);
        } else {
            if ($this->info['Cash_Amount'] > 0 || $this->info['Card_Amount'] > 0 || $this->info['Check_Amount'] > 0) {
                $pay_data = array();
                $pay_data['Payment_Date'] = $this->info['Purchase_Date'];
                $pay_data['Status_ID'] = $is_actual;
                $pay_data['branch_id'] = $branch_id;
                $pay_data['payment_prefix'] = '';
                $pay_data['IsReceipt'] = 0;
                $pay_data['Currency_Rate'] = $rate;
                $pay_data['Currency_ID'] = $this->info['Currency_ID'];
                $pay_data['date_time'] = $mydate;
                $pay_data['date_created'] = $mydate;
                $pay_data['Logged_ID'] = $this->info['Logged_ID'];
                $pay_data['created_logged_id'] = $this->info['Logged_ID'];
                $pay_data['Account_Code'] = $suppAccount;
                $pay_data['job_id'] = $this->info['job_id'];
                $pay_data['project_id'] = $this->info['project_id'];
                $pay_data['payment'] = array();
                if ($this->info['Card_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Card_Account'],
                        'Payment_Amount' => $this->info['Card_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => '',
                        'Check_Date' => '',
                        'value_date' => '',
                        'user_ref' => (empty($this->info['card_user_ref']) ? '' : $this->info['card_user_ref']),
                    );
                }
                if ($this->info['Cash_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Cash_Account'],
                        'Payment_Amount' => $this->info['Cash_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => '',
                        'Check_Date' => '',
                        'value_date' => '',
                        'user_ref' => (empty($this->info['cash_user_ref']) ? '' : $this->info['cash_user_ref']),
                    );
                }
                if ($this->info['Check_Amount'] > 0) {
                    $pay_data['payment'][] = array(
                        'is_cheque' => 0,
                        'Payment_Type_ID' => $this->info['Check_Account'],
                        'Payment_Amount' => $this->info['Check_Amount'],
                        'Payment_Note' => $desc,
                        'Check_Number' => (empty($this->info['Check_Num']) ? '' : $this->info['Check_Num']),
                        'Check_Date' => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
                        'value_date' => (empty($this->info['value_date']) ? '' : $this->info['value_date']),
                        'user_ref' => (empty($this->info['check_user_ref']) ? '' : $this->info['check_user_ref']),
                    );
                }
                $payment = new Payment();
                $payment->stop_transaction_start_end = true;
                $payment->setData($pay_data)->create();
            }
        }
        $error = $this->db->error();
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query('COMMIT');
            return $return_inv_num ? [$this->info['Invoice_ID_Auto'], $pur_num, $purchase_detail_ids] : $this->info['Invoice_ID_Auto'];
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query('ROLLBACK');
            return $return_inv_num ? [array_unique($error)] : array_unique($error);
        }
        return array_unique($error);
    }

    //    private function addCostEditPurchase($item) {
    //        $mydate = date("Y-m-d h:i:s a");
    //        $method = Session::stock_method();
    //        if ($method == 1 or $method == 2) {
    //            if ($method == 1) {
    //                $concat = ' ORDER BY Product_Cost_ID DESC LIMIT 1';
    //            } else if ($method == 2) {
    //                $concat = ' LIMIT 1';
    //            }
    //            $amount = $item['Quantity'];
    //            $item['Type'] = '12';
    //            $item['Operation'] = '+';
    //            while ($amount > 0) {
    //                $select = $this->db->query('SELECT
    //                                             Product_Cost_ID,
    //                                             Unit_Cost,
    //                                             Currency_ID,
    //                                             Product_Quantity-Product_Released_Quantity AS Remaining_Quantity
    //                                         FROM
    //                                             tbl_stock_products_costs 
    //                                         WHERE
    //                                             Product_Quantity-Product_Released_Quantity > 0
    //                                         AND 
    //                                             Product_ID = "' . $item['Item_ID'] . '"
    //
    //                    ' . $concat);
    //
    //                $row = $this->db->assoc($select);
    //                if (!empty($row)) {
    //                    if ($row['Remaining_Quantity'] != 0 && $amount > $row['Remaining_Quantity']) {
    //                        $temp_amount = $row['Remaining_Quantity'];
    //                        $amount -= $row['Remaining_Quantity'];
    //                    } else {
    //                        $temp_amount = $amount;
    //                        $amount = 0;
    //                    }
    //                    $update = [&$temp_amount, &$row['Product_Cost_ID']];
    //                    $this->db->prepare_Stmt("UPDATE
    //                                            tbl_stock_products_costs
    //                                        SET
    //                                            Product_Quantity = Product_Quantity - ?
    //                                        WHERE
    //                                            Product_Cost_ID = ?
    //                    ", $update);
    //                    $current_cost = $row['Unit_Cost']; // / $rate;
    //                    $item_curr_id = $row['Currency_ID'];
    //                } else {
    //                    $temp_amount = $amount;
    //                    $amount = 0;
    //                    $current_cost = 0;
    //                    $item_curr_id = CurrencyFactory::returnLocalCurrency();
    //                }
    //                $data = [
    //                    &$item['Item_ID'],
    //                    &$temp_amount,
    //                    &$current_cost,
    //                    &$item_curr_id,
    //                    &$item['Depot_ID'],
    //                    &$item['Type'],
    //                    &$item['Date'],
    //                    &$item['Logged_ID'],
    //                    &$item['Operation'],
    //                    &$temp_amount,
    //                    &$item['UOM_ID'],
    //                    &$mydate
    //                ];
    //                $this->db->prepare_Stmt('INSERT INTO
    //                                            tbl_stock_product_transactions(
    //                                                Product_ID,
    //                                                Product_Quantity,
    //                                                Unit_Cost,
    //                                                Currency_ID,
    //                                                Depot_ID,
    //                                                Transaction_Type_ID,
    //                                                Transaction_Date,
    //                                                Logged_ID,
    //                                                Operation_Type,
    //                                                Item_Quantity_Current,
    //                                                UOM_ID,
    //                                                date_time
    //                                            )
    //                                            VALUES(
    //                                                ?,?,?,?,?,?,?,?,?,?,?,?
    //                                            )
    //                        ', $data);
    //            }
    //        } else {
    //            $row = self::viewCostByAverage($item['Product_ID']);
    //            $data = [
    //                &$item['Item_ID'],
    //                &$item['Quantity'],
    //                &$row['Unit_Cost'],
    //                &$row['Currency_ID'],
    //                &$item['Depot_ID'],
    //                &$item['Type'],
    //                &$item['Date'],
    //                &$item['Logged_ID'],
    //                &$item['Operation'],
    //                &$item['Quantity'],
    //                &$item['UOM_ID'],
    //                &$mydate
    //            ];
    //            $this->db->prepare_Stmt('INSERT INTO
    //                                            tbl_stock_product_transactions(
    //                                                Product_ID,
    //                                                Product_Quantity,
    //                                                Unit_Cost,
    //                                                Currency_ID,
    //                                                Depot_ID,
    //                                                Transaction_Type_ID,
    //                                                Transaction_Date,
    //                                                Logged_ID,
    //                                                Operation_Type,
    //                                                Item_Quantity_Current,
    //                                                UOM_ID,
    //                                                date_time
    //                                            )
    //                                            VALUES(
    //                                                ?,?,?,?,?,?,?,?,?,?,?,?
    //                                            )
    //                        ', $data);
    //        }
    //    }
    //    public static function deletePurchase($id) {
    //        $mydate = date("Y-m-d H:i:s");
    //        $logged_id = smc_session()['user_logged_id'];
    //        $db = DBConnectorFactory::loadDriver();
    //        $depot_query = $db->query('select Depot_ID from  tbl_inventory_purchases where Purchase_ID_Auto = "' . $id . '"');
    //        $depot_id = $db->assoc($depot_query)['Depot_ID'];
    //        $db->query('START TRANSACTION');
    //        $db->prepare_Stmt('delete from tbl_accounting_transactions where main_id= ? and main_type="pur"', [&$id]);
    //        $db->prepare_Stmt("UPDATE 
    //                                    tbl_stock_products s
    //                                JOIN 
    //                                    (select Product_ID, sum(Item_Quantity) as Item_Quantity 
    //                                        from tbl_inventory_purchase_items where Purchase_ID_Auto = ? group by Product_ID) i
    //                                USING(Product_ID)
    //                                SET 
    //                                    s.Product_Quantity = s.Product_Quantity - i.Item_Quantity
    //                ", [&$id]);
    //
    //
    //        $update_dep = [&$id, &$depot_id];
    //        $db->prepare_Stmt("UPDATE 
    //                                    tbl_stock_product_location s
    //                                JOIN 
    //                                    (select Product_ID, sum(Item_Quantity) as Item_Quantity 
    //                                        from tbl_inventory_purchase_items where Purchase_ID_Auto = ? group by Product_ID) i
    //                                ON 
    //                                    s.Location_Product_ID = i.Product_ID
    //                                SET 
    //                                    s.Product_Depot_Quantity = s.Product_Depot_Quantity - i.Item_Quantity
    //                                WHERE s.Product_Depot_ID = ?
    //                ", $update_dep);
    //
    //        $db->prepare_Stmt("DELETE FROM tbl_inventory_purchase_items  WHERE Purchase_ID_Auto = ?", [&$id]);
    //        $db->prepare_Stmt('update tbl_inventory_purchases set Purchase_Sub_Total = 0,Purchase_Net_Total =0,
    //            Purchase_Paid_Amount=0,Purchase_Shipping=0,date_time=?,Logged_ID = ? where Purchase_ID_Auto= ? ', [&$mydate, &$logged_id, &$id]);
    //        $error = $db->error();
    //        if (empty($error)) {
    //            $db->query('COMMIT');
    //        } else {
    //            $db->query('ROLLBACK');
    //        }
    //        return array_unique($error);
    //    }
    //    public function getPurchaseOrderByID($PID) {
    //        $data = array();
    //        $query = $this->db->prepare_Stmt('select * from purchase_order_list where Order_ID = ?', [&$PID]);
    //        $row = $this->db->assoc($query);
    //        $data['Main'] = $row;
    //        $query_details = $this->db->query('select
    //                                                p.Order_ID,
    //                                                i.Item_Quantity_Current AS Item_Quantity_Current,
    //                                                ps.Product_Code AS Code,
    //                                                ps.Product_Name AS Name,
    //                                                ps.Product_Limit_Discount,
    //                                                ps.is_tax,
    //                                                if(ps.vat_percent <> 0,1,0) AS VAT,
    //                                                (if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity)/uc.conversion_amount+ i.Item_Quantity_Current) as Product_Quantity,
    //                                                (if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity)/uc.conversion_amount+ i.Item_Quantity_Current) as Quantity,
    //                                                i.Item_ID AS Product_ID,
    //                                                ps.vat_percent,
    //                                                (i.Unit_Price * ps.vat_percent/100) as vat_amount,
    //                                                uc.Bar_Code,
    //                                                i.Unit_Price,
    //                                                i.Unit_Price as Product_Net_Price,
    //                                                "" as product_description,
    //                                                "" as Product_Discount,
    //                                                
    //                                                (i.Quantity/i.Item_Quantity_Current) AS uom_con,
    //                                                 i.UOM_ID,
    //                                                GROUP_CONCAT(uom_from separator "/") AS Product_UOM
    //                                            from 
    //                                                tbl_purchase_order_details i 
    //                                            left join 
    //                                                tbl_purchase_order p 
    //                                            on
    //                                                p.Order_ID = i.Order_ID
    //                                            LEFT JOIN
    //                                                uom_conversions uc
    //                                            ON 
    //                                                uc.Product_ID = i.Item_ID
    //                                            left join 
    //                                                tbl_stock_products ps 
    //                                            on
    //                                                ps.Product_ID = i.Item_ID
    //                                                left  join tbl_stock_product_location l
    //                                                on l.Location_Product_ID = i.Item_ID 
    //                                                and l.Product_Depot_ID = "' . $data['Main']['Depot_ID'] . '"
    //                                            where
    //                                                
    //                                                p.Order_ID = "' . $PID . '"
    //                                            GROUP BY i.Entry_ID
    //
    //                                            ');
    //        while ($row = $this->db->assoc($query_details)) {
    //            $data['Details'][] = $row;
    //        }
    //        if ($data['Main']['is_sales'] == 1) {
    //            $data['Person'] = Customer::getCustomerByID($data['Main']['Supplier_ID']);
    //        } else {
    //            $data['Person'] = Supplier::getSupplierByID($data['Main']['Supplier_ID']);
    //        }
    ////echo"<pre>";
    ////die(print_r($data));
    //        return $data;
    //    }
    public function getPurchaseOrderByID($id, $from_pos = false) {
        $data = array("Main" => array(), "Details" => array(), "Person" => array());
        $year = SESSION::getCurrentYearID();
        $query_main = $this->db->query('select 
                                            current_year_id,
                                            from_place ,
                                            to_place ,
                                            driver_id,
                                            concat(sale_prefix,Order_ID_Auto) AS ID,
                                            Order_ID AS Auto_ID,
                                            Order_Date AS Date,
                                            po,job_inv,project_code ,project_name_inv,our_ref,supply_date,
                                            sale_due_date AS Due_Date,
                                            discount_percent AS Discount,
                                            discount_amount,
                                            total_vat AS VAT,
                                            sub_total AS Sub_Total,
                                            net_total AS Net_Total,
                                            Currency_ID,
                                            Currency_Symbol,
                                            Currency_Name,
                                            currency_round,
                                            Depot_ID,
                                            Supplier_ID as Person_ID,
                                            Supplier_ID as Customer_ID,
                                            Person_Name,                                           
                                            Person_Name as Customer_Name,
                                            Class_ID,
                                            Class_Name,
                                            order_description as Invoice_Description,due_date_period ,
                                           is_ttc,supp_class_id,supp_class_name,
                                           current_rate,is_sales,created_logged_id,date_time,
                                           Order_ID_Auto,job_id,project_id,job_name,project_name,version_nb,
                                           delivery_date,is_actual,is_sales,extra_cost,sale_app_id,
                                           postponed_note,postponed_date_time,postponed_status_id,
                                           customer_address_alias,customer_name_alias,shipping
                                        from purchase_order_list where Order_ID = "' . smc_escape($id) . '" ');
        $row = $this->db->assoc($query_main);
        $row['cost_dist_method'] = smc_session()['default_setting']['cost_dist_method'];
        if (!empty($row)) {
            $row['driver_name'] = CommonBusiness::getDriverByDriverId($row['driver_id']);

            $data['Main'] = $row;
            $emp_query = $this->db->query('select u.Employee_ID,
            concat(e.Employee_FirstName," ",e.Employee_MiddleName," ",e.Employee_LastName) as Employee_Name
            from tbl_common_users u join tbl_hrm_employee e using(Employee_ID)
            where User_ID = "' . $data['Main']['created_logged_id'] . '"');
            $emp_data = $this->db->assoc($emp_query);
            $data['Main']['Sales_ID'] = $emp_data['Employee_ID'];
            $data['Main']['Employee_Name'] = $emp_data['Employee_Name'];
            if ($data['Main']['is_sales']) {
                $data['Person'] = Customer::getCustomerByID($data['Main']['Person_ID']);
            } else {
                $data['Person'] = Supplier::getSupplierByID($data['Main']['Person_ID']);
            }
            //            echo '<pre>';
            //            print_r($data['Person']);

            $data['Main']['Address'] = $data['Person']['Address'];
            $data['Main']['Phone'] = $data['Person']['Mobile'];

            $product_ids = array();
            $prod_query = $this->db->query('select distinct Item_ID 
                from tbl_purchase_order_details where Order_ID = "' . $id . '"');
            while ($row = $this->db->assoc($prod_query)) {
                $product_ids[] = $row['Item_ID'];
            }
            $last_price_arr = CommonBusiness::viewLastProductCustomerClassPrice($product_ids, $data['Main']['Person_ID'], $data['Main']['Class_ID']);

            $query_details = $this->db->query('select
                                                i.Entry_ID AS Entery_ID,
                                                i.n_height AS n_height,
                                                i.n_width AS n_width,
                                                i.n_total AS n_total,

                                                i.from_time AS from_time,
                                                i.to_time AS to_time,
                                                i.modify_date AS modify_date,
                                                i.driver_id AS driver_id,
                                                driver.driver_name AS driver_name,
                                                p.Order_ID AS Invoice_ID_Auto,
                                                i.Item_Quantity_Current AS Item_Quantity_Current,
                                                ps.Product_Code AS Code,
                                                ps.Product_Name AS Name,
                                                ps.Product_Name AS Product_Name,
                                                ps.Product_Limit_Discount,
                                                ps.is_tax,ps.is_lot,ps.is_serial,ps.is_service,
                                                ps.Status_ID,
                                                if(i.vat_percent <> 0,1,0) AS VAT,
                                                (( if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity) /uc.conversion_amount)) as Product_Quantity,
                                                (( if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity) /uc.conversion_amount)) AS Quantity,
                                                i.Item_ID AS Product_ID,
                                                i.vat_percent,
                                                i.vat_amount,
                                                i.note as product_description,
                                                uc.Bar_Code,
                                                i.discount_percent AS Product_Discount,
                                                i.Unit_Price AS Product_Net_Price,
                                                i.total_price AS Product_Total_Price,
                                                (i.Quantity/i.Item_Quantity_Current) AS uom_con,
                                                 i.UOM_ID,"" as expiry_date,ps.is_expiry,
                                                 0 as unit_tax,
                                                 0 as total_tax,i.lot_nb,i.serial_nb,
                                                GROUP_CONCAT(uom_from separator "/") AS Product_UOM,p.current_rate,
                                                "" as TAG,
                                                "" as add_ons,
                                                "hidden" as link_product_class,pc.Class_Name as supp_class_name,
                                                i.supp_class_id,i.item_cost,i.other_cost
                                            from 
                                                tbl_purchase_order_details i 
                                            left join 
                                                tbl_purchase_order p 
                                            on
                                                p.Order_ID = i.Order_ID
                                            LEFT JOIN
                                                uom_conversions uc
                                            ON 
                                                uc.Product_ID = i.Item_ID
                                            
                                            LEFT JOIN
                                                tbl_drivers driver
                                            ON 
                                                driver.driver_id = i.driver_id


                                            left join 
                                                tbl_stock_products ps 
                                            on
                                                ps.Product_ID = i.Item_ID
                                                left  join tbl_stock_product_location l on l.Location_Product_ID = i.Item_ID and l.Product_Depot_ID = "' . $data['Main']['Depot_ID'] . '"
                                                left  join tbl_pricing_class pc on pc.Class_ID = i.supp_class_id
                                            where
                                                p.current_year_id = "' . $year . '"
                                            and 
                                                p.Order_ID = "' . $id . '"
                                            GROUP BY i.Entry_ID
                                            order by p.Order_ID_Auto

                                            ');
            //        $query_details = $this->db->query('select * from invoice_details where Invoice_ID_Auto = "'.smc_escape($id).'"');
            $data['Main']['total_qty'] = 0;
            while ($row = $this->db->assoc($query_details)) {
                $data['Main']['total_qty'] += $row['Item_Quantity_Current'];
                $row['ttc_price'] = $row['Product_Net_Price'] * (1 + ($row['vat_percent'] / 100));
                $row['unit_cost'] = CommonBusiness::viewCurrentProductCost($row['Product_ID']) / $row['current_rate'];
                $last_cost = CommonBusiness::viewLastProductCost($row["Product_ID"]) * $row['uom_con'];
                $row['LAST_COST'] = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $data['Main']['Currency_ID'], $last_cost);
                $last_price = 0;
                if (array_key_exists($row['Product_ID'], $last_price_arr) && !is_null($data['Main']['Person_ID']) && $this->permissions->hasPermission('view_sales_last_price') && $data['Main']['is_sales'] == 1) {
                    $last_price = $last_price_arr[$row["Product_ID"]];
                    //                    $last_price = CommonBusiness::viewLastProductCustomerClassPrice($row["Product_ID"], $data['Main']['Person_ID'], $data['Main']['Class_ID']);
                }
                $row['last_price'] = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $data['Main']['Currency_ID'], $last_price);

                $data['Details'][$row['Entery_ID']] = $row;
                $entry_ids_array[] = $row['Entery_ID'];
            }
            $entry_ids_str = implode(',', $entry_ids_array);
            $criteria_details_query = $this->db->query('select  ord_details.Entry_ID as Entery_ID,
                                                            crit_details.criteria_detail_id,
                                                            crit_details.criteria_detail_name, 
                                                            ord_details.criteria_price, 
                                                            ord_details.criteria_note,
                                                            crit_details.criteria_id
                                                    from tbl_order_product_criteria ord_details
                                                    inner join tbl_product_criteria_detail crit_details
                                                    using(criteria_detail_id)

                                                    where ord_details.Entry_ID IN (' . $entry_ids_str . ')
                                                    ');
            while ($row = $this->db->assoc($criteria_details_query)) {
                $data['Details'][$row['Entery_ID']]['criteria'][] = $row;
            }
        }

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

    public function editPurchaseOrder() {
        $is_actual = isset($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'order', 'start_date' => $this->info['Invoice_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Invoice_Date'], $this->info['Invoice_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        $version_nb = 1;
        if ($this->info['is_quotation'] == 1 && $this->info['IsSales'] == 1) {

            $version_arr = $this->getPurchaseOrderByID($this->info['ID_Auto']);
            $version_nb = $version_arr['Main']['version_nb'];
            $ver_data = ['main_type' => 'sqo', 'main_id' => $this->info['ID_Auto'],
                'version_array' => json_encode($version_arr), 'version_nb' => $version_nb];
            CommonFunctions::add_version($ver_data);
        }
        $logged_id = !empty($this->info['Logged_ID']) ? $this->info['Logged_ID'] : smc_session()['user_logged_id'];
        $depot_id = $this->info['Depot_ID'];
        $app_user_id = isset($this->info['app_user_id']) ? $this->info['app_user_id'] : 0;
        $sale_app_id = isset($this->info['sale_app_id']) ? $this->info['sale_app_id'] : 0;
        $branch_id = isset($this->info['branch_id']) ? $this->info['branch_id'] : CommonBusiness::getBranchByDepot($depot_id);
        if (isset($this->info['invoice_prefix']))
            $sale_prefix = $this->info['invoice_prefix'];
        else {
            $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'];
            $sale_prefix = smc_session()['user_accounts']['serial_prefix'] ? smc_session()['user_accounts']['serial_prefix'] : $branch_prefix;
        }


        $Person_ID = $this->info['Customer_ID'];
        $sale_num = isset($this->info['Sale_Number']) ? $this->info['Sale_Number'] : self::getMaxOrder($this->info['is_quotation'], $this->info['IsSales'], $sale_prefix, $is_actual);
        if (isset($this->info['Invoice_Due_Date'])) {
            $Sale_Due_Date = $this->info['Invoice_Due_Date'];
        } else {
            $Sale_Due_Date = $this->info['Invoice_Date'];
        }
        $Invoice_Currency = $this->info['Invoice_Currency'];
        $mydate = date("Y-m-d H:i:s");
        $rate = !empty($this->info['Invoice_Currency_Rate']) ? $this->info['Invoice_Currency_Rate'] : CurrencyFactory::getLastExRate($Invoice_Currency);

        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';
        $delivery_date = !empty($this->info['order_delivery_date']) ? $this->info['order_delivery_date'] : NULL;
        $year_id = $is_actual ? $this->year_id_actual : $this->year_id;
        $version_nb = $version_nb + 1;
        $extra_cost = !empty($this->info['extra_cost']) ? $this->info['extra_cost'] : 0;
        $this->info['postponed_status_id'] = !empty($this->info['postponed_status_id']) ? $this->info['postponed_status_id'] : NULL;
        $this->info['postponed_date_time'] = (!empty($this->info['postponed_date_time']) && !empty($this->info['postponed_status_id'])) ? $this->info['postponed_date_time'] : NULL;
        $this->info['postponed_note'] = !empty($this->info['postponed_note']) ? $this->info['postponed_note'] : NULL;
        $customer_name_alias = isset($this->info['customer_name_alias']) ? $this->info['customer_name_alias'] : '';
        $customer_address_alias = isset($this->info['customer_address_alias']) ? $this->info['customer_address_alias'] : '';
        $this->info['shipping'] = isset($this->info['shipping']) ? $this->info['shipping'] : 0;
        $driver_id = isset($this->info['driver_id']) ? $this->info['driver_id'] : 0;

        $data = [&$Person_ID,
            &$this->info['Invoice_Date'], &$logged_id, &$Invoice_Currency, &$rate, &$depot_id, &$branch_id,
            &$Sale_Due_Date,
            &$mydate, &$this->info['Invoice_VAT'], &$this->info['Invoice_Discount'], &$this->info['discount_amount'],
            &$this->info['Invoice_Net_Total'], &$this->info['Invoice_Sub_Total'],
            &$this->info['Invoice_Description'], &$this->info['Class_ID'], &$this->info['job_id'],
            &$this->info['project_id'], &$this->info['supp_class_id'], &$this->info['total_cost'],
            &$version_nb, &$delivery_date, &$extra_cost, &$this->info['postponed_status_id'],
            &$this->info['postponed_date_time'], &$this->info['postponed_note'], $customer_name_alias,
            $customer_address_alias, $this->info['shipping'],&$this->info['po'],&$this->info['project_name_inv'],&$this->info['project_code'],&$this->info['job_inv'],&$this->info['our_ref'],&$this->info['supply_date']
            ,$driver_id
            ,&$this->info['from_place']
            ,&$this->info['to_place']
            , &$this->info['ID_Auto']
        ];
        $this->db->prepare_Stmt('update `tbl_purchase_order` set  `Supplier_ID` = ?, 
            `Order_Date` = ?, `Logged_ID` = ?, `Currency_ID` = ?, `current_rate` = ?, `Depot_ID` = ?, `branch_id` = ?,
             `sale_due_date` = ?, 
            `date_time` = ?,`total_vat` = ?, `discount_percent` = ?, `discount_amount` = ?,
            `net_total` = ?, `sub_total` = ?, `order_description` = ?, Class_ID = ?,job_id=?,project_id=?,
            supp_class_id=?,total_cost=?,version_nb=?,delivery_date = ?,extra_cost=?,postponed_status_id= ?,postponed_date_time= ?,postponed_note= ?,
            customer_name_alias=?,customer_address_alias=?,shipping=?,po=?,project_name_inv=?,project_code=?,job_inv=?,our_ref=?,supply_date=?,driver_id=?,from_place=?, to_place=? where Order_ID = ?', $data);
        //         $error = $this->db->error();
        //                echo"<pre>";
        //                die(print_r($error));
        $Sale_ID = $this->info['ID_Auto'];
        $this->db->prepare_Stmt("DELETE criteria FROM  tbl_order_product_criteria criteria
                                inner join tbl_purchase_order_details details on details.Entry_ID = criteria.Entry_ID
                                where details.Order_ID = ?", [&$this->info['ID_Auto']]);
        $this->db->prepare_Stmt('delete from tbl_purchase_order_details where Order_ID = ?', [&$this->info['ID_Auto']]);
        foreach ($this->info['Products'] as $item) {
            //            $prod_arr
            $ProductID = $item['Product_ID'];
            $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $item['Product_ID']);
            $ProductDiscount = $item['Item_Discount'];
            $ProductNetPrice = $item['Item_Price'];
            $Product_Total_Price = $item['Product_Total_Price'];
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';
            $disc_amount = $ProductQuantity * $ProductNetPrice * $ProductDiscount / 100;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $item['class_id'] = !empty($item['class_id']) ? $item['class_id'] : $this->info['supp_class_id'];
            $prod = [&$Sale_ID, &$ProductID, &$ProductQuantity, &$item['Item_Quantity'], &$item['UOM_ID'],
                &$ProductNetPrice, &$ProductDiscount,
                &$Product_Total_Price, &$item['vat_percent'],
                &$item['vat_val'], &$Product_Description, &$disc_amount, &$lot_nb, &$serial_nb, &$item['class_id'], &$item['item_cost'], &$item['other_cost'], &$item['from_time'], &$item['to_time'], &$item['modify_date']
                , &$item['driver_id']
                , &$item['n_height']
                , &$item['n_width']
                , &$item['n_total']
            
            
            ];
 
            //             print_r($prod);
            $this->db->prepare_Stmt("INSERT INTO `tbl_purchase_order_details`( " . (!empty($item['entry_id']) ? 'Entry_ID,' : '') . "`Order_ID`,
                `Item_ID`, `Quantity`, `Item_Quantity_Current`, `UOM_ID`, `Unit_Price`, `discount_percent`,
                 `total_price`, `vat_percent`, `vat_amount`, `note`,discount_amount,lot_nb,serial_nb,supp_class_id,item_cost,other_cost,from_time,to_time,modify_date
                 ,driver_id
                 ,n_height
                 ,n_width
                 ,n_total
                 
                 ) 
                VALUES (" . (!empty($item['entry_id']) ? '"' . $item['entry_id'] . '",' : '') . "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $prod);
            //                          $error = $this->db->error();
            //                          print_r($error);
            $new_entry_id = $this->db->id();
            if (!empty($item['criteria_details'])) {
                $criteria_details = $item['criteria_details'];
                foreach ($criteria_details as $details) {
                    $this->db->prepare_Stmt("INSERT INTO
                                        tbl_order_product_criteria 
                                        (Entry_ID,Quantity,criteria_detail_id,criteria_price,criteria_note)
                                        VALUES
                                        (?,?,?,?,?)
                    ", [&$new_entry_id, &$details['Quantity'], &$details['criteria_detail_id'],
                        &$details['criteria_price'], &$details['criteria_note']]);
                }
            }
        }

        $error = $this->db->error();
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query("COMMIT");
            return [$Sale_ID, ($sale_prefix . $sale_num)];
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query("ROLLBACK");
            return array_unique($error);
        }
    }

    //    public function editPurchaseOrder() {
    //        if (!$this->stop_transaction_start_end)
    //            $this->db->query('START TRANSACTION;');
    //        $mydate = date("Y-m-d H:i:s");
    //        $branch_id = CommonBusiness::getBranchByDepot($this->info['Depot_ID']);
    //        $logged_id = smc_session()['user_logged_id'];
    //        $rate = CurrencyFactory::getLastExRate($this->info['Currency_ID']);
    //        $order = [&$this->info['Vendor_ID'], &$this->info['Order_Date'], &$this->info['Currency_ID'],
    //            &$rate, &$this->info['Depot_ID'], &$branch_id, &$logged_id, &$mydate, &$this->info['sale_due_date'], $this->info['Order_ID']];
    //        $this->db->prepare_Stmt("update tbl_purchase_order set Supplier_ID=?,Order_Date=?,Currency_ID=?,
    //            current_rate=?,Depot_ID=?,branch_id=?,Logged_ID=?,date_time=?,sale_due_date=? where Order_ID = ?", $order);
    //        $parent_id = $this->info['Order_ID'];
    //        $this->db->prepare_Stmt('delete from tbl_purchase_order_details where Order_ID = ? ', [&$this->info['Order_ID']]);
    //        if (is_array($this->info['Items'])) {
    //            foreach ($this->info['Items'] as $item) {
    //                $product_quantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Quantity'], $item['Item_ID']);
    //                $details = [&$parent_id, &$item['Item_ID'], &$product_quantity, &$item['Quantity'], &$item['UOM_ID'], &$item['Unit_Price']];
    //                $this->db->prepare_Stmt("INSERT INTO tbl_purchase_order_details (Order_ID,Item_ID,Quantity,Item_Quantity_Current,UOM_ID,Unit_Price) 
    //                    VALUES (?,?,?,?,?,?) ", $details);
    //            }
    //        }
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("COMMIT");
    //        } else {
    //            if (!$this->stop_transaction_start_end)
    //                $this->db->query("ROLLBACK");
    //        }
    //        return array_unique($error);
    //    }

    public function getPurchaseToPrint($id) {
        $data = array();
        $year = SESSION::getCurrentYearID();
        $query_main = $this->db->query('select current_year_id,
                                            Purchase_ID AS ID,
                                            Purchase_ID_Auto AS Auto_ID,
                                            Purchase_ID AS Purchase_ID_number,
                                            Purchase_Date AS Date,
                                            Purchase_Due_Date AS Due_Date,
                                            Purchase_Discount AS Discount,
                                            discount_amount,
                                            Purchase_VAT AS VAT,
                                            Purchase_Sub_Total AS Sub_Total,
                                            Purchase_Net_Total AS Net_Total,
                                            Purchase_Paid_Amount AS Paid_Amount,
                                            Currency_ID,
                                            Currency_Symbol,
                                            Currency_Name,
                                            currency_round,
                                            Depot_ID,Depot_Name,
                                            Supplier_Invoice_ID,
                                            Invoice_Description,
                                            driver_id,
                                            from_place,
                                            to_place,
                                            Supplier_ID,
                                            sales_purchase_id,
                                            Purchase_Shipping as shipping,
                                            (Purchase_VAT*current_rate) as local_vat_amount,
                                            Account_ID,
                                            Account_Code,Account_Name,current_rate,extra_cost,cost_dist_method,
                                            job_id,job_name,project_id,project_name,is_actual,currency_round as pur_currency_round
                                        from purchase_main_list where Purchase_ID_Auto = "' . smc_escape($id) . '" AND current_year_id = "' . $this->year_id . '"');
        $row = $this->db->assoc($query_main);
        $net_total = $row['Net_Total'];
        $shipping_amount = $row['shipping'];
        $paid_amount = $row['Paid_Amount'];
        $grand_total = $net_total + $shipping_amount + $row['pur_currency_round'];
        $total_vat = $row['VAT'];
        $local_vat = $row['local_vat_amount'];
        $prec = $row['Currency_ID'] == 84 ? 0 : 2;
        $row['Invoice_Sub_Total'] = CommonFunctions::public_round_number($row['Sub_Total']);
        $row['Invoice_Net_Total'] = CommonFunctions::public_round_number($row['Net_Total']);
        $row['Invoice_Paid_Amount'] = CommonFunctions::public_round_number($paid_amount);
        $row['Invoice_VAT'] = CommonFunctions::public_round_number($total_vat);
        $row['Invoice_Discount'] = CommonFunctions::public_round_number($row['Discount']);
        $row['discount_amount'] = CommonFunctions::public_round_number($row['discount_amount']);
        $row['Invoice_Shipping'] = CommonFunctions::public_round_number($row['shipping']);
        $row['local_vat_amount'] = CommonFunctions::public_round_number($local_vat);
        $row['local_net_total'] = CommonFunctions::public_round_number(($net_total * $row['current_rate']));
        $row['net_total_in_usd'] = CommonFunctions::public_round_number(CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($net_total, 144, $net_total));
        $row['grand_total'] = CommonFunctions::public_round_number($grand_total);
        $row['grand_total_word_ar'] = Forms::num_to_word($grand_total, $row['Currency_ID'], 'ar');
        $row['grand_total_word_en'] = Forms::num_to_word($grand_total, $row['Currency_ID'], 'en');
        $row['total_vat_word_ar'] = Forms::num_to_word($total_vat, $row['Currency_ID'], 'ar');
        $row['total_vat_word_en'] = Forms::num_to_word($total_vat, $row['Currency_ID'], 'en');
        $row['local_vat_word_ar'] = Forms::num_to_word($local_vat, smc_session()['local_currency'], 'ar');
        $row['local_vat_word_en'] = Forms::num_to_word($local_vat, smc_session()['local_currency'], 'en');
        $row['driver_name'] = CommonBusiness::getDriverByDriverId($row['driver_id']);
        //        echo"<pre>";die(print_r($row));
        $person = Supplier::getSupplierByID($row['Supplier_ID']);
        $data['main'] = array_merge($row, $person);
        $query_details = $this->db->query('select
                                                i.liter_abs,
                                                i.temp,
                                                i.coeff,
                                                i.compts,
                                                
                                                p.Purchase_ID_Auto AS Invoice_ID_Auto,

                                                i.driver_id,
                                                drv.driver_name,
                                                i.modify_date,
                                                i.vehicle_id,
                                                v.Vehicle_Code,v.Vehicle_Name,

                                                i.Item_Quantity_Current,
                                                ps.Product_Code AS Code,
                                                ps.Product_Name,
                                                ps.Product_Limit_Discount,
                                               if(i.vat_percent <> 0,1,0) AS VAT,
                                                ps.Product_Quantity,
                                                i.Product_ID AS Product_ID,
                                                i.vat_percent,
                                                i.vat_amount,
                                                i.product_description,
                                                i.Item_Discount AS Product_Discount,
                                                i.Item_Price AS Product_Net_Price,
                                                i.Product_Total_Price AS Product_Total_Price,
                                                (i.Item_Quantity/i.Item_Quantity_Current) AS uom_con,
                                                su.UOM_Name,
                                                 i.UOM_ID,
                                                GROUP_CONCAT(uom_from separator "/") AS Product_UOM,
                                                i.cost_percent,i.real_cost,i.lot_nb,i.serial_nb
                                            from 
                                                tbl_inventory_purchase_items i 
                                            inner join 
                                                tbl_inventory_purchases p 
                                            on
                                                p.Purchase_ID_Auto = i.Purchase_ID_Auto
                                            left join tbl_drivers drv on drv.driver_id = i.driver_id
                                            left join tbl_garage_vehicle v on v.Vehicle_ID = i.vehicle_id

                                            inner JOIN
                                                uom_conversions uc
                                            ON 
                                                uc.Product_ID = i.Product_ID
                                            inner join 
                                                tbl_stock_products ps 
                                            on
                                                ps.Product_ID = i.Product_ID
                                            inner join tbl_stock_uom su on su.UOM_ID = i.UOM_ID
                                            where
                                                p.current_year_id = "' . $year . '"
                                            and 
                                                p.Purchase_ID_Auto = "' . $id . '"
                                            GROUP BY i.Item_ID
                                            order by p.Purchase_ID

                                            ');
        $i = 0;
        while ($item_row = $this->db->assoc($query_details)) {
            $total_price = $item_row['Product_Total_Price'];
            $vat_amount = $item_row['vat_amount'];
            $item_row['Product_Net_Price'] = CommonFunctions::public_round_number($item_row['Product_Net_Price']);
            $item_row['Product_Discount'] = CommonFunctions::public_round_number($item_row['Product_Discount']);
            $item_row['Product_Total_Price'] = CommonFunctions::public_round_number($item_row['Product_Total_Price']);
            $item_row['vat_amount'] = CommonFunctions::public_round_number($item_row['vat_amount']);
            $item_row['Item_Quantity_Current'] = CommonFunctions::public_round_number($item_row['Item_Quantity_Current']);
            $item_row['Count'] = ++$i;
            $item_row['total_with_vat'] = CommonFunctions::public_round_number(($total_price + $vat_amount));
            $data['Details'][] = $item_row;
        }
        //
        //        echo"<pre>";
        //        die(print_r($data));
        return $data;
    }

    public function get_total_purchased_items() {
        $cond = ' current_year_id = "' . $this->year_id . '" ';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and (Purchase_Date between "' . smc_escape($_GET['from_date']) . '" and "' . smc_escape($_GET['to_date']) . '" )  ';
        if (!empty($_GET['product']))
            $cond .= ' and  Product_ID = ' . smc_escape($_GET['product']) . '';
        if (empty($_GET['is_actual']))
            $cond .= ' and  is_actual = 0';
        if (!empty($_GET['supplier']) || is_numeric($_GET['supplier'])) //we put it for zero : cash supplier
            $cond .= ' and Supplier_ID = ' . smc_escape($_GET['supplier']) . ' ';
        if (!empty($_GET['depot_id']))
            $cond .= ' and  detail_depot_id = ' . smc_escape($_GET['depot_id']) . '';
        if (!empty($_GET['category_id']))
            $cond .= ' and  Category_ID = ' . smc_escape($_GET['category_id']) . '';
        if (!empty($_GET['brand_id']))
            $cond .= ' and  brand_id = ' . smc_escape($_GET['brand_id']) . '';
        $query = $this->db->query('select sum(Product_Total_Price*current_rate) as total from detailed_purchase_report where true and ' . $cond);
        $row = $this->db->assoc($query);
        return empty($row) ? 0 : CommonFunctions::formatNumber($row['total']);
    }

    public function last_insert_sales_invoice() {
        $query = $this->db->query('select max(Invoice_ID_Auto) as last_inv from tbl_invoices');
        $row = $this->db->assoc($query);

        return array_unique([$row['last_inv']]);
    }
    public function delete_purchase($id_arr) {

        if (smc_session()['year_closed'] == 1) {
            $error = array();
            $error[0] = CommonLanguage::getMessage('delete_year_alert');
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        $date_time = date("Y-m-d H:i:s");
        foreach ($id_arr as $id) {
            $query = $this->db->query('select Purchase_Date,is_actual
                from tbl_inventory_purchases  where Purchase_ID_Auto = "' . $id . '"');
            $row = $this->db->assoc($query);
            $check = CommonFunctions::check_lock_data(['type' => 'purchase', 'start_date' => $row['Purchase_Date'], 'is_actual' => $row['is_actual']]);
            if ($check !== '') {
                continue;
            }
            $query_check = $this->db->query('select purchase_id from tbl_inventory_delivery_report 
                where purchase_id = "' . $id . '"');
            $pur_count = $this->db->rowsno($query_check);
            if (!empty($pur_count)) {
                $error = array();
                $error[0] = CommonLanguage::getMessage('pur_del_link_alert');
                return $error;
            }
            $query = $this->db->query('SELECT * FROM `tbl_invoice_payments` WHERE inv_pur_id = "' . $id . '" and type in ("pay","smjv","deb") ');
            $row_nb = $this->db->rowsno($query);
            if ($row_nb > 0) {
                $error[0] = CommonLanguage::getMessage('related_to_payment');
                return $error;
            }

            $this->db->prepare_Stmt('delete from tbl_accounting_transactions where main_id= ? and main_type="pur"', [&$id]);

            $this->edit_old_details_qty_cost($id, 1);

            $this->db->prepare_Stmt('delete from tbl_inventory_purchase_items where Purchase_ID_Auto= ? ', [&$id]);
            $this->db->prepare_Stmt('delete from tbl_inventory_purchases  where Purchase_ID_Auto= ? ', [&$id]);
            $arr_purchase = ['type' => 'pur', 'main_id' => $id, 'action' => 2, 'date_time' => $date_time,
                'user_id' => smc_session()['user_logged_id']];
            CommonFunctions::add_user_log($arr_purchase);
        }
        $error = $this->db->error();
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query('COMMIT');
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function edit_old_details_qty_cost($inv_auto_id, $is_delete = 0) {
        $mydate = Date('Y-m-d H:i:s');
        $trans_type = $is_delete == 1 ? 'delete_purchase' : 'edit_purchase_old';
        $query = $this->db->query("SELECT 
                                        p.Product_ID as Item_ID,
                                        p.Item_Quantity AS Quantity,
                                        p.Item_Quantity_Current AS Quantity_Current,
                                        p.Item_Price,
                                        p.UOM_ID,
                                        p.expiry_date,
                                        i.Currency_ID,
                                        p.depot_id as Depot_ID,
                                        i.date_time,
                                        i.current_rate,
                                        i.Purchase_ID,p.real_cost,i.created_logged_id,i.date_created,
                                        i.Purchase_Date,i.is_actual,p.lot_nb,p.serial_nb,pr.is_service,
                                        i.Supplier_ID

                                    FROM 
                                        tbl_inventory_purchase_items p
                                    LEFT JOIN 
                                        tbl_inventory_purchases i
                                        USING(Purchase_ID_Auto)
                                        join tbl_stock_products pr on pr.Product_ID = p.Product_ID

                                    WHERE 
                                        p.Purchase_ID_Auto = '" . $inv_auto_id . "' and (isnull(p.Delivery_Report_ID) or p.Delivery_Report_ID = 0)
                ");
        $old_date_time = $mydate;
        $old_date_created = $mydate;
        $old_created_logged_id = smc_session()['user_logged_id'];
        while ($row = $this->db->assoc($query)) {
            //            $pur_num = $row['Purchase_ID'];
            $old_date_created = $row['date_created'];
            $old_created_logged_id = $row['created_logged_id'];
            $old_date_time = $row['date_time'];
            $old_expiry_date = !empty($row['expiry_date']) ? $row['expiry_date'] : null;
            $old_lot_nb = !empty($row['lot_nb']) ? $row['lot_nb'] : '';
            $old_serial_nb = !empty($row['serial_nb']) ? $row['serial_nb'] : '';

            $costdata = [
                "Product_ID" => $row['Item_ID'],
                "Quantity" => $row['Quantity'],
                "Unit_Cost" => $row['real_cost'],
                "unit_price" => $row['Item_Price'],
                "Currency_ID" => $row['Currency_ID'],
                "date_time" => $row['date_time'],
                "date_time_now" => $mydate,
                "current_rate" => $row['current_rate'],
                "depot_id" => $row['Depot_ID'],
                "trans_date" => $row['Purchase_Date'],
                "current_quantity" => $row['Quantity_Current'],
                "uom_id" => $row['UOM_ID'],
                "is_actual" => $row['is_actual'],
                "expiry_date" => $old_expiry_date,
                "lot_nb" => $old_lot_nb,
                "serial_nb" => $old_serial_nb,
                "main_id" => $inv_auto_id,
                "is_service" => $row['is_service'],
                "main_nb" => $row['Purchase_ID'],
                "supplier_id" => $row['Supplier_ID']
            ];
            CommonBusiness::addCostByType($costdata, $trans_type);
            if ($row['is_service'] != 1) {
                $update_stock = [&$row['Quantity'], &$row['Item_ID']];
                $this->db->prepare_Stmt("UPDATE 
                                    tbl_stock_products 
                                SET Product_Quantity = Product_Quantity - ? where Product_ID = ?
                ", $update_stock);


                $update_dep = [&$row['Quantity'], &$row['Depot_ID'], &$row['Item_ID']];
                $this->db->prepare_Stmt("UPDATE 
                                    tbl_stock_product_location 
                                    set Product_Depot_Quantity = Product_Depot_Quantity - ?
                                WHERE Product_Depot_ID = ? and Location_Product_ID = ?
                ", $update_dep);
            }
        }
        CommonBusiness::update_trans_record_current('pur', $inv_auto_id);
    }

    //    public function edit_old_details_qty_cost($inv_auto_id) {
    //        $mydate = Date('Y-m-d H:i:s');
    //        $query = $this->db->query("SELECT 
    //                                        p.Product_ID as Item_ID,
    //                                        p.Item_Quantity AS Quantity,
    //                                        p.Item_Quantity_Current AS Quantity_Current,
    //                                        p.Item_Price,
    //                                        p.UOM_ID,
    //                                        p.expiry_date,
    //                                        i.Currency_ID,
    //                                        i.Depot_ID,
    //                                        i.date_time,
    //                                        i.current_rate,
    //                                        i.Purchase_ID,p.real_cost,i.created_logged_id,i.date_created,
    //                                        i.Purchase_Date,i.is_actual,p.lot_nb,p.serial_nb
    //
    //                                    FROM 
    //                                        tbl_inventory_purchase_items p
    //                                    LEFT JOIN 
    //                                        tbl_inventory_purchases i
    //                                    USING(Purchase_ID_Auto)
    //                                    WHERE 
    //                                        p.Purchase_ID_Auto = '" . $inv_auto_id . "'
    //                ");
    //        $old_date_time = $mydate;
    //        $old_date_created = $mydate;
    //        $old_created_logged_id = smc_session()['user_logged_id'];
    //        while ($row = $this->db->assoc($query)) {
    //            //            $pur_num = $row['Purchase_ID'];
    //            $old_date_created = $row['date_created'];
    //            $old_created_logged_id = $row['created_logged_id'];
    //            $old_date_time = $row['date_time'];
    //            $old_expiry_date = !empty($row['expiry_date']) ? $row['expiry_date'] : null;
    //            $old_lot_nb = !empty($row['lot_nb']) ? $row['lot_nb'] : '';
    //            $old_serial_nb = !empty($row['serial_nb']) ? $row['serial_nb'] : '';
    //
    //            $costdata = [
    //                "Product_ID" => $row['Item_ID'],
    //                "Quantity" => $row['Quantity'],
    //                "Unit_Cost" => $row['real_cost'],
    //                "Currency_ID" => $row['Currency_ID'],
    //                "date_time" => $row['date_time'],
    //                "current_rate" => $row['current_rate'],
    //                "depot_id" => $row['Depot_ID'],
    //                "trans_date" => $row['Purchase_Date'],
    //                "current_quantity" => $row['Quantity_Current'],
    //                "uom_id" => $row['UOM_ID'],
    //                "is_actual" => $row['is_actual'],
    //                "expiry_date" => $old_expiry_date,
    //                "lot_nb"=>$old_lot_nb,
    //                "serial_nb"=>$old_serial_nb,
    //                "main_id" => $inv_auto_id
    //            ];
    //            CommonBusiness::addCostByType($costdata, 'edit_purchase_old');
    //            $update_stock = [&$inv_auto_id];
    //            $this->db->prepare_Stmt("UPDATE 
    //                                    tbl_stock_products s
    //                                JOIN 
    //                                    (select Product_ID, sum(Item_Quantity) as Item_Quantity 
    //                                        from tbl_inventory_purchase_items where Purchase_ID_Auto = ? group by Product_ID) i
    //                                USING(Product_ID)
    //                                SET 
    //                                    s.Product_Quantity = s.Product_Quantity - i.Item_Quantity
    //                ", $update_stock);
    //
    //
    //            $update_dep = [&$inv_auto_id, &$row['Depot_ID']];
    //            $this->db->prepare_Stmt("UPDATE 
    //                                    tbl_stock_product_location s
    //                                JOIN 
    //                                    (select Product_ID, sum(Item_Quantity) as Item_Quantity 
    //                                        from tbl_inventory_purchase_items where Purchase_ID_Auto = ? group by Product_ID) i
    //                                ON 
    //                                    s.Location_Product_ID = i.Product_ID
    //                                SET 
    //                                    s.Product_Depot_Quantity = s.Product_Depot_Quantity - i.Item_Quantity
    //                                WHERE s.Product_Depot_ID = ?
    //                ", $update_dep);
    //        }
    //    }

    public function add_station_purchase($return_inv_num = false) {
        $is_actual = !empty($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'station_purchase', 'start_date' => $this->info['Purchase_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Purchase_Date'], $this->info['Purchase_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        //send from view supplier account and name, send currency symbol,cash ,chequ and credit card accounts
        $paid = $this->info['Card_Amount'] + $this->info['Cash_Amount'] + $this->info['Check_Amount'];
        $rem = $this->info['Purchase_Net_Total'] - $paid;
        $suppAccount = $this->info['Supplier_Account'];
        $depot_id = $this->info['Depot_ID'];
        $branch_id = CommonBusiness::getBranchByDepot($depot_id);
        $purchase_account = $this->info['Account_Code'];
        $mydate = date("Y-m-d H:i:s");
        $purch_num = self::getMaxPurchase($is_actual);
        $rate = !empty($this->info['Invoice_Currency_Rate']) ? $this->info['Invoice_Currency_Rate'] : CurrencyFactory::getLastExRate($this->info['Currency_ID']);
        $second_rate = CurrencyFactory::getSecondCurrencyLastExRate($this->info['Currency_ID']);
        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';

        $main = [
            &$purch_num,
            &$this->info['Purchase_Date'],
            &$this->info['Purchase_Due_Date'],
            &$mydate,
            &$mydate,
            &$this->info['Currency_ID'],
            &$this->info['Supplier_ID'],
            &$this->info['Purchase_Sub_Total'],
            &$this->info['Purchase_Net_Total'],
            &$this->info['Purchase_Discount'],
            &$this->info['discount_amount'],
            &$depot_id,
            &$this->info['Supplier_Invoice_ID'],
            &$this->info['Invoice_Description'],
            &$this->info['loading_number'],
            &$this->info['truck'],
            &$paid,
            &$this->info['Invoice_VAT'],
            &$this->info['service'],
            &$this->info['service_vat'],
            &$this->info['shipping'],
            &$rate, &$second_rate,
            &$this->info[0],
            &$this->info[0],
            &$this->year_id,
            &$branch_id,
            &$purchase_account,
            &$is_actual,
            &$this->info['job_id'],
            &$this->info['project_id'],
            &$this->info['bone_type_id']
        ];
        $this->db->prepare_Stmt("
                                INSERT
                                INTO
                                        tbl_inventory_purchases
                                (
                                        Purchase_ID,
                                        Purchase_Date,
                                        Purchase_Due_Date,
                                        date_time,
                                        date_created,
                                        Currency_ID,
                                        Supplier_ID,
                                        Purchase_Sub_Total,
                                        Purchase_Net_Total,
                                        Purchase_Discount,
                                        discount_amount,
                                        Depot_ID,
                                        Supplier_Invoice_ID,
                                        Invoice_Description,
                                        loading_number,
                                        truck,
                                        Purchase_Paid_Amount,
                                        Purchase_VAT,service_amount,service_vat,
                                        Purchase_Shipping,
                                        current_rate,second_currency_rate,
                                        Logged_ID,created_logged_id,
                                        current_year_id,
                                        branch_id,
                                        Account_ID,
                                        is_actual,job_id,project_id,purchase_type_id,bone_type_id

                                )
                                        VALUES
                                (
                                        ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?
                                )
                                ", $main);

        $purchase_id = $this->db->id();


        $prod_arr = array();
        $prod_ids_arr = array();
        $vat_percent = $this->info['Invoice_VAT'] > 0 ? ($this->info['Invoice_VAT'] * 100) / $this->info['Purchase_Sub_Total'] : 0;
        foreach ($this->info['Products'] as $item) {
            $item['UOM_ID'] = Product::get_product_default_uom($item['Product_ID']);
            $item['vat_percent'] = $vat_percent;
            $item['vat_val'] = $item['vat_percent'] * $item['Product_Total_Price'] / 100;
            $prod_ids_arr[] = $item['Product_ID'];
            $productID = $item['Product_ID'];
            $product_quantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $productID);
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';

            $prod_arr[] = array("product_id" => $item['Product_ID'],
                "total_amount" => ($item['Product_Total_Price']),
                "description" => $Product_Description, "vat_amount" => $item['vat_val']);
            $new_cost = ($item['Item_Price'] / ($product_quantity / $item['Item_Quantity']) * (100 - $item['Item_Discount']) / 100);
            $expiry_date = !empty($item['expiry_date']) ? $item['expiry_date'] : null;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $is_service = !empty($item['is_service']) ? $item['is_service'] : 0;
            $depot_detail_id = !empty($item['depot_id']) ? $item['depot_id'] : $depot_id;
            $costdata = [
                "Product_ID" => $productID,
                "Quantity" => $product_quantity,
                "Unit_Cost" => $new_cost,
                "unit_price" => $item['Item_Price'],
                "Currency_ID" => $this->info['Currency_ID'],
                "date_time" => $mydate,
                "date_time_now" => $mydate,
                "current_rate" => $rate,
                "depot_id" => $depot_detail_id,
                "trans_date" => $this->info['Purchase_Date'],
                "current_quantity" => $item['Item_Quantity'],
                "uom_id" => $item['UOM_ID'],
                "is_actual" => $is_actual,
                "expiry_date" => $expiry_date,
                "lot_nb" => $lot_nb,
                "serial_nb" => $serial_nb,
                "main_id" => $purchase_id,
                "is_service" => $is_service,
                "main_nb" => $purch_num,
                "supplier_id" => $this->info['Supplier_ID']
            ];
            //            echo "<pre>";print_r($costdata);
            CommonBusiness::addCostByType($costdata, 'add_purchase');
            $comp = implode(',', $item['compts']);
            $prod_insert = [
                &$purchase_id,
                &$productID,
                &$product_quantity,
                &$item['Item_Price'],
                &$item['Product_Total_Price'],
                &$item['Item_Discount'],
                &$item['Item_Quantity'],
                &$item['UOM_ID'],
                &$item['vat_percent'],
                &$item['vat_val'],
                &$Product_Description,
                &$new_cost,
                &$expiry_date,
                &$item['liter_abs'],
                &$item['coeff'],
                &$item['temp'],
                &$comp, &$lot_nb, &$serial_nb, &$depot_detail_id
            ];
            $this->db->prepare_Stmt("
                                        INSERT
                                        INTO
                                                tbl_inventory_purchase_items
                                        (
                                                Purchase_ID_Auto,
                                                Product_ID,
                                                Item_Quantity,
                                                Item_Price,
                                                Product_Total_Price,
                                                Item_Discount,
                                                Item_Quantity_Current,
                                                UOM_ID,
                                                vat_percent,
                                                vat_amount,
                                                product_description,real_cost,expiry_date,
                                                liter_abs,coeff,temp,compts,lot_nb,serial_nb,depot_id
                                        )
                                                VALUES
                                        (
                                                ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
                                        )
                                ", $prod_insert);
            if ($is_service != 1) {
                $quant = [
                    &$product_quantity,
                    &$productID
                ];
                $this->db->prepare_Stmt("
                                UPDATE 
                                        tbl_stock_products
                                SET 
                                        Product_Quantity =  Product_Quantity + ?
                                WHERE 
                                        Product_ID       = ?

                                ", $quant);
                $location = [
                    &$productID,
                    &$depot_detail_id,
                    &$product_quantity,
                    &$product_quantity
                ];
                $this->db->prepare_Stmt("INSERT INTO tbl_stock_product_location
                                                (
                                                        Location_Product_ID,
                                                        Product_Depot_ID,
                                                        Product_Depot_Quantity
                                                )
                                                        VALUES
                                                (
                                                        ?,?,?
                                                )
                                            ON DUPLICATE KEY
                                            UPDATE Product_Depot_Quantity = Product_Depot_Quantity + ?


                                                ", $location);
            }
        }
        //        $error = $this->db->error();
        //        echo"<pre>";
        //die(print_r($prod_arr));
        //        die();
        $prod_str =implode( ',',$prod_ids_arr);
        $prod_trans_arr = CommonBusiness::get_item_acc_transactions($prod_arr, $prod_str, 'pur', $purchase_account, $this->info['Purchase_Discount'], $this->info['shipping_account'], $this->info['shipping']);

        $jv = JV::returnJV($is_actual);
        $suppName = $this->info['Supplier_Name'];
        $pur_ref = "Pur." . $purch_num;
        $curr_symbol = $this->info['CurrencySymbole'];
        $desc = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : 'Purchased products with ' . round(($this->info['Purchase_Net_Total'] + $this->info['shipping']), 2) . ' ' . $curr_symbol . ' from ' . $suppName;
        //        $s_account = JV::getAccountCodeByID($suppAccount);
        $supp_vat_account = Supplier::returnSuppVATAccount($this->info['Supplier_ID'])['Account_ID'];
        $amount_novat = $this->info['Purchase_Net_Total'] - $this->info['Invoice_VAT'];
        foreach ($prod_trans_arr as $trans) {
            //            $trans_desc = $trans[]
            if (isset($trans['main'])) {
                $trans_main = $trans['main'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => (empty($trans_main['ref']) ? 'pur' : $trans_main['ref']),
                    "Transaction_Account" => $trans_main['trans_account'],
                    "Transaction_Type" => "Debit",
                    "Transaction_Amount" => $trans_main['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info[0],
                    "Transaction_Description" => (empty($trans_main['trans_desc']) ? $desc : $trans_main['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $purchase_id,
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "subtype" => "pur",
                    "main_nb" => $purch_num,
                    "job_id" => $this->info['job_id'],
                    "project_id" => $this->info['project_id']
                ];
                JV::addTransaction($data_trans, $is_actual);
            }


            if (isset($trans['person'])) {
                $trans_person = $trans['person'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => $pur_ref,
                    "Transaction_Account" => $suppAccount,
                    "Transaction_Type" => "Credit",
                    "Transaction_Amount" => $trans_person['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info[0],
                    "Transaction_Description" => (empty($trans_person['trans_desc']) ? $desc : $trans_person['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $purchase_id,
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "main_nb" => $purch_num,
                    "job_id" => $this->info['job_id'],
                    "project_id" => $this->info['project_id']
                ];
                JV::addTransaction($data_trans, $is_actual);
                //                 $error = $this->db->error();
                //            die(print_r($error));
            }
        }

        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['Invoice_VAT'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $purch_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        );
        JV::addTransaction($dat_3, $is_actual);
        $dat_112 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $suppAccount,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['Purchase_Net_Total'] - $rem,
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $purch_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        );
        JV::addTransaction($dat_112, $is_actual);
        $dat_4 = [
            "JV_ID" => $jv,
            "Transaction_Reference" => 'credit',
            "Transaction_Account" => $this->info['Card_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Card_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "subtype" => "credit",
            "main_nb" => $purch_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_4, $is_actual);
        $dat_5 = [
            "JV_ID" => $jv,
            "Transaction_Reference" => 'cash',
            "Transaction_Account" => $this->info['Cash_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Cash_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "subtype" => "cash",
            "main_nb" => $purch_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_5, $is_actual);
        $dat_6 = ["JV_ID" => $jv,
            "Transaction_Reference" => 'check',
            "Transaction_Account" => $this->info['Check_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Check_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info[0],
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $purchase_id,
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
            "value_date" => $this->info['value_date'],
            "check_nb" => $this->info['Check_Num'],
            "subtype" => "check",
            "main_nb" => $purch_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_6, $is_actual);
        $error = $this->db->error();
        //        die(print_r($error));
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query("COMMIT");
            return $return_inv_num ? [$purchase_id, $purch_num] : $purchase_id;
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query("ROLLBACK");
            return $return_inv_num ? [array_unique($error)] : array_unique($error);
        }
    }

    public function edit_station_purchase($return_inv_num = false) {
        $is_actual = !empty($this->info['is_actual']) ? $this->info['is_actual'] : 0;
        $check = CommonFunctions::check_lock_data(['type' => 'station_purchase', 'start_date' => $this->info['Purchase_Date'], 'is_actual' => $is_actual]);

//        $check = JV::checkCurrentYear($this->info['Purchase_Date'], $this->info['Purchase_Date'], $is_actual);
        if ($check !== '') {
            $error = array();
            $error[0] = $check;
            return $error;
        }
        if (!$this->stop_transaction_start_end)
            $this->db->query('START TRANSACTION');
        $mydate = date("Y-m-d H:i:s");
        $today = Date::getToday();
        $this->info['Logged_ID'] = Session::getUserID();
        $jv_query = $this->db->query("SELECT DISTINCT JV_ID FROM tbl_accounting_transactions  WHERE main_id='" . $this->info['Invoice_ID_Auto'] . "' AND main_type= 'pur' ");
        $jv_assoc = $this->db->assoc($jv_query);
        if (!empty($jv_assoc))
            $jv = $jv_assoc['JV_ID'];
        else
            $jv = JV::returnJV($is_actual);
        $this->db->prepare_Stmt("DELETE FROM tbl_accounting_transactions  WHERE main_id= ? AND main_type= 'pur' ", [&$this->info['Invoice_ID_Auto']]);

        $paid = $this->info['Card_Amount'] + $this->info['Cash_Amount'] + $this->info['Check_Amount'];
        $remaining = $this->info['Purchase_Net_Total'] - $paid;
        $suppAccount = $this->info['Supplier_Account'];

        $pur_num = '';
        $query = $this->db->query("SELECT 
                                        p.Product_ID as Item_ID,
                                        p.Item_Quantity AS Quantity,
                                        p.Item_Quantity_Current AS Quantity_Current,
                                        p.Item_Price,
                                        p.UOM_ID,
                                        p.expiry_date,
                                        i.Currency_ID,
                                        i.depot_id as Depot_ID,
                                        i.date_time,
                                        i.current_rate,p.lot_nb,p.serial_nb,pr.is_service,
                                        i.Purchase_ID,p.real_cost,i.created_logged_id,i.date_created,
                                        i.Supplier_ID

                                    FROM 
                                        tbl_inventory_purchase_items p
                                    LEFT JOIN 
                                        tbl_inventory_purchases i
                                    USING(Purchase_ID_Auto)
                                    join tbl_stock_products pr on pr.Product_ID = p.Product_ID
                                    WHERE 
                                        p.Purchase_ID_Auto = '" . $this->info['Invoice_ID_Auto'] . "'
                ");
        $old_date_time = $mydate;
        $old_date_created = $mydate;
        $old_created_logged_id = smc_session()['user_logged_id'];
        while ($row = $this->db->assoc($query)) {
            $pur_num = $row['Purchase_ID'];
            $old_date_created = $row['date_created'];
            $old_created_logged_id = $row['created_logged_id'];
            $old_date_time = $row['date_time'];
            $old_expiry_date = !empty($row['expiry_date']) ? $row['expiry_date'] : null;
            $old_lot_nb = !empty($row['lot_nb']) ? $row['lot_nb'] : '';
            $old_serial_nb = !empty($row['serial_nb']) ? $row['serial_nb'] : '';

            $costdata = [
                "Product_ID" => $row['Item_ID'],
                "Quantity" => $row['Quantity'],
                "Unit_Cost" => $row['real_cost'],
                "unit_price" => $row['Item_Price'],
                "Currency_ID" => $row['Currency_ID'],
                "date_time" => $row['date_time'],
                "date_time_now" => $mydate,
                "current_rate" => $row['current_rate'],
                "depot_id" => $row['Depot_ID'],
                "trans_date" => $this->info['Purchase_Date'],
                "current_quantity" => $row['Quantity_Current'],
                "uom_id" => $row['UOM_ID'],
                "is_actual" => $is_actual,
                "expiry_date" => $old_expiry_date,
                "lot_nb" => $old_lot_nb,
                "serial_nb" => $old_serial_nb,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "is_service" => $row['is_service'],
                "main_nb" => $pur_num,
                "supplier_id" => $row['Supplier_ID']
            ];
            CommonBusiness::addCostByType($costdata, 'edit_purchase_old');
        }

        $branch_id = CommonBusiness::getBranchByDepot($this->info['Depot_ID']);
        $rate = !empty($this->info['Invoice_Currency_Rate']) ? $this->info['Invoice_Currency_Rate'] : CurrencyFactory::getLastExRate($this->info['Currency_ID']);
        $second_rate = CurrencyFactory::getSecondCurrencyLastExRate($this->info['Currency_ID']);
        $this->info['Invoice_Description'] = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : '';

        $purchase_account = $this->info['Account_Code'];
        $up_main = [
            &$this->info['Purchase_Date'],
            &$this->info['Purchase_Due_Date'],
            &$this->info['Currency_ID'],
            &$this->info['Supplier_ID'],
            &$this->info['Purchase_Sub_Total'],
            &$this->info['Purchase_Net_Total'],
            &$this->info['Purchase_Discount'],
            &$this->info['discount_amount'],
            &$this->info['Depot_ID'],
            &$this->info['Supplier_Invoice_ID'],
            &$this->info['Invoice_Description'],
            &$this->info['loading_number'],
            &$this->info['truck'],
            &$paid,
            &$this->info['Invoice_VAT'],
            &$this->info['service'],
            &$this->info['service_vat'],
            &$this->info['shipping'],
            &$rate, &$second_rate,
            &$this->info[0],
            &$branch_id,
            &$purchase_account,
            &$this->info['job_id'], &$this->info['project_id'],
            &$this->info['bone_type_id'],
            &$mydate,
            &$this->info['Invoice_ID_Auto']
        ];
        $this->db->prepare_Stmt("UPDATE 
                                    tbl_inventory_purchases 
                                SET
                                    Purchase_Date = ?,
                                    Purchase_Due_Date = ?,
                                    Currency_ID = ?,
                                    Supplier_ID = ?,
                                    Purchase_Sub_Total = ?,
                                    Purchase_Net_Total = ?,
                                    Purchase_Discount = ?,
                                    discount_amount = ?,
                                    Depot_ID = ?,
                                    Supplier_Invoice_ID = ?,
                                    Invoice_Description=?,
                                    loading_number=?,
                                    truck=?,
                                    Purchase_Paid_Amount = ?,
                                    Purchase_VAT = ?,service_amount=?,service_vat=?,
                                    Purchase_Shipping = ?,
                                    current_rate = ?,second_currency_rate=?,
                                    Logged_ID = ?,
                                    branch_id = ?,
                                    Account_ID = ?,
                                    job_id=?,project_id=?,bone_type_id=?,
                                    date_time=?
                                WHERE 
                                    Purchase_ID_Auto = ?

                 ", $up_main);

        $update_stock = [&$this->info['Invoice_ID_Auto']];
        $this->db->prepare_Stmt("UPDATE 
                                    tbl_stock_products s
                                JOIN 
                                    (select Product_ID, sum(Item_Quantity) as Item_Quantity 
                                        from tbl_inventory_purchase_items where Purchase_ID_Auto = ? group by Product_ID) i
                                USING(Product_ID)
                                SET 
                                    s.Product_Quantity = s.Product_Quantity - i.Item_Quantity where s.is_service <> 1
                ", $update_stock);


        $update_dep = [&$this->info['Invoice_ID_Auto'], &$this->info['Old_Depot_ID']];
        $this->db->prepare_Stmt("UPDATE 
                                    tbl_stock_product_location s
                                JOIN 
                                    (select pi.Product_ID, sum(Item_Quantity) as Item_Quantity 
                                        from tbl_inventory_purchase_items pi join tbl_stock_products pr
                                        on pr.Product_ID = pi.Product_ID
                                        where Purchase_ID_Auto = ? and pr.is_service <>1 group by Product_ID) i
                                ON 
                                    s.Location_Product_ID = i.Product_ID
                                SET 
                                    s.Product_Depot_Quantity = s.Product_Depot_Quantity - i.Item_Quantity
                                WHERE s.Product_Depot_ID = ?
                ", $update_dep);




        $this->db->prepare_Stmt("DELETE FROM tbl_inventory_purchase_items  WHERE Purchase_ID_Auto = ?", $update_stock);

        $prod_arr = array();
        $prod_ids_arr = array();
        $vat_percent = $this->info['Invoice_VAT'] > 0 ? ($this->info['Purchase_Sub_Total'] * 100) / $this->info['Invoice_VAT'] : 0;
        CommonBusiness::update_trans_record_current('pur', $this->info['Invoice_ID_Auto']);
        foreach ($this->info['Products'] as $item) {
            $item['UOM_ID'] = Product::get_product_default_uom($item['Product_ID']);
            $item['vat_percent'] = $vat_percent;
            $item['vat_val'] = $item['vat_percent'] * $item['Product_Total_Price'] / 100;
            $prod_ids_arr[] = $item['Product_ID'];
            $productID = $item['Product_ID'];
            $ProductQuantity = Product::getConvertedQuantity($item['UOM_ID'], $item['Item_Quantity'], $productID);
            $Product_Description = isset($item['product_description']) ? $item['product_description'] : '';

            $prod_arr[] = array("product_id" => $item['Product_ID'],
                "total_amount" => ($item['Product_Total_Price']),
                "description" => $Product_Description, "vat_amount" => $item['vat_val']);
            $new_cost = ($item['Item_Price'] / ($ProductQuantity / $item['Item_Quantity']) * (100 - $item['Item_Discount']) / 100);
            $expiry_date = !empty($item['expiry_date']) ? $item['expiry_date'] : null;
            $lot_nb = !empty($item['lot_nb']) ? $item['lot_nb'] : '';
            $serial_nb = !empty($item['serial_nb']) ? $item['serial_nb'] : '';
            $is_service = !empty($item['is_service']) ? $item['is_service'] : 0;
            $depot_detail_id = !empty($item['depot_id']) ? $item['depot_id'] : $this->info['Depot_ID'];
            $costdata = [
                "Product_ID" => $productID,
                "Quantity" => $ProductQuantity,
                "Unit_Cost" => $new_cost,
                "unit_price" => $item['Item_Price'],
                "Currency_ID" => $this->info['Currency_ID'],
                "date_time" => $old_date_time,
                "date_time_now" => $mydate,
                "current_rate" => $rate,
                "depot_id" => $depot_detail_id,
                "trans_date" => $this->info['Purchase_Date'],
                "current_quantity" => $item['Item_Quantity'],
                "uom_id" => $item['UOM_ID'],
                "is_actual" => $is_actual,
                "expiry_date" => $expiry_date,
                "lot_nb" => $lot_nb,
                "serial_nb" => $serial_nb,
                "main_id" => $this->info['Invoice_ID_Auto'],
                "is_service" => $is_service,
                "main_nb" => $pur_num,
                "supplier_id" => $this->info['Supplier_ID']
            ];
            //            $error = $this->db->error();
            //        die(print_r($costdata));
            CommonBusiness::addCostByType($costdata, "edit_purchase_new");
            $comp = implode(',', $item['compts']);

            $prod = [
                &$this->info['Invoice_ID_Auto'],
                &$productID,
                &$ProductQuantity,
                &$item['Item_Price'],
                &$item['Product_Total_Price'],
                &$item['Item_Discount'],
                &$item['vat_percent'],
                &$item['vat_val'],
                &$item['Item_Quantity'],
                &$item['UOM_ID'],
                &$Product_Description,
                &$new_cost, &$expiry_date, &$item['liter_abs'],
                &$item['coeff'],
                &$item['temp'],
                &$comp, &$lot_nb, &$serial_nb, &$depot_detail_id
            ];
            //            die("
            //                                        INSERT
            //                                        INTO
            //                                                tbl_inventory_purchase_items
            //                                        (
            //                                                Purchase_ID_Auto,
            //                                                Product_ID,
            //                                                Item_Quantity,
            //                                                Item_Price,
            //                                                Product_Total_Price,
            //                                                Item_Discount,
            //                                                vat_percent,
            //                                                vat_amount,
            //                                                Item_Quantity_Current,
            //                                                UOM_ID,
            //                                                product_description,real_cost,expiry_date,
            //                                                liter_abs,coeff,temp,compts
            //                                    )
            //                                                VALUES
            //                                        (
            //                                                '".$this->info['Invoice_ID_Auto']."',
            //                '".$productID."',
            //                '".$ProductQuantity."',
            //                '".$item['Item_Price']."',
            //                '".$item['Product_Total_Price']."',
            //                '".$item['Item_Discount']."',
            //                '".$item['vat_percent']."',
            //                '".$item['vat_val']."',
            //                '".$item['Item_Quantity']."',
            //               '".$item['UOM_ID']."',
            //                '".$Product_Description."',
            //                '".$new_cost."', '".$expiry_date."', '".$item['liter_abs']."',
            //                '".$item['coeff']."',
            //                '".$item['temp']."',
            //                '".$comp."'
            //                                        )
            //                                ");
            $this->db->prepare_Stmt("
                                        INSERT
                                        INTO
                                                tbl_inventory_purchase_items
                                        (
                                                Purchase_ID_Auto,
                                                Product_ID,
                                                Item_Quantity,
                                                Item_Price,
                                                Product_Total_Price,
                                                Item_Discount,
                                                vat_percent,
                                                vat_amount,
                                                Item_Quantity_Current,
                                                UOM_ID,
                                                product_description,real_cost,expiry_date,
                                                liter_abs,coeff,temp,compts,lot_nb,serial_nb,depot_id
                                    )
                                                VALUES
                                        (
                                                ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
                                        )
                                ", $prod);

            if ($is_service != 1) {

                $up_quan = [&$ProductQuantity, &$productID];
                $this->db->prepare_Stmt("UPDATE 
                                            tbl_stock_products 
                                    SET 
                                            Product_Quantity = Product_Quantity + ?
                                    WHERE 
                                            Product_ID = ? 
                                ", $up_quan);

                $dep_dat = [&$productID, &$depot_detail_id, &$ProductQuantity, &$ProductQuantity];
                $this->db->prepare_Stmt("INSERT INTO tbl_stock_product_location
                                                (
                                                        Location_Product_ID,
                                                        Product_Depot_ID,
                                                        Product_Depot_Quantity
                                                )
                                                        VALUES
                                                (
                                                        ?,?,?
                                                )
                                            ON DUPLICATE KEY
                                            UPDATE Product_Depot_Quantity = Product_Depot_Quantity + ?


                                                ", $dep_dat);
            }
        }
        $prod_str =implode( ',',$prod_ids_arr);
        $prod_trans_arr = CommonBusiness::get_item_acc_transactions($prod_arr, $prod_str, 'pur', $purchase_account, $this->info['Purchase_Discount'], $this->info['shipping_account'], $this->info['shipping']);

        $suppName = $this->info['Supplier_Name'];
        $pur_ref = "Pur." . $pur_num;
        $curr_symbol = $this->info['CurrencySymbole'];
        $desc = !empty($this->info['Invoice_Description']) ? $this->info['Invoice_Description'] : 'Purchased products with ' . round(($this->info['Purchase_Net_Total'] + $this->info['shipping']), 2) . ' ' . $curr_symbol . ' from ' . $suppName;


        $supp_vat_account = Supplier::returnSuppVATAccount($this->info['Supplier_ID'])['Account_ID'];
        $amount_novat = $this->info['Purchase_Net_Total'] - $this->info['Invoice_VAT'];
        foreach ($prod_trans_arr as $trans) {
            //            $trans_desc = $trans[]
            if (isset($trans['main'])) {
                $trans_main = $trans['main'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => (empty($trans_main['ref']) ? 'pur' : $trans_main['ref']),
                    "Transaction_Account" => $trans_main['trans_account'],
                    "Transaction_Type" => "Debit",
                    "Transaction_Amount" => $trans_main['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info['Logged_ID'],
                    "date_created" => $old_date_created,
                    "created_logged_id" => $old_created_logged_id,
                    "Transaction_Description" => (empty($trans_main['trans_desc']) ? $desc : $trans_main['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $this->info['Invoice_ID_Auto'],
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "subtype" => "pur",
                    "main_nb" => $pur_num,
                    "job_id" => $this->info['job_id'],
                    "project_id" => $this->info['project_id']
                ];
                JV::addTransaction($data_trans, $is_actual);
            }


            if (isset($trans['person'])) {
                $trans_person = $trans['person'];
                $data_trans = ["JV_ID" => $jv,
                    "Transaction_Reference" => $pur_ref,
                    "Transaction_Account" => $suppAccount,
                    "Transaction_Type" => "Credit",
                    "Transaction_Amount" => $trans_person['trans_amount'],
                    "Transaction_Date" => $this->info['Purchase_Date'],
                    "Currency_ID" => $this->info['Currency_ID'],
                    "Logged_ID" => $this->info['Logged_ID'],
                    "date_created" => $old_date_created,
                    "created_logged_id" => $old_created_logged_id,
                    "Transaction_Description" => (empty($trans_person['trans_desc']) ? $desc : $trans_person['trans_desc']),
                    "Current_Ex_Rate" => $rate,
                    "second_currency_rate" => $second_rate,
                    "main_id" => $this->info['Invoice_ID_Auto'],
                    "main_type" => "pur",
                    "branch_id" => $branch_id,
                    "due_date" => $this->info['Purchase_Due_Date'],
                    "main_nb" => $pur_num,
                    "job_id" => $this->info['job_id'],
                    "project_id" => $this->info['project_id']
                ];
                JV::addTransaction($data_trans, $is_actual);
                //                 $error = $this->db->error();
                //            die(print_r($error));
            }
        }

        $dat_3 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $supp_vat_account,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['Invoice_VAT'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $pur_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        );
        JV::addTransaction($dat_3, $is_actual);
        $dat_12 = array(
            "JV_ID" => $jv,
            "Transaction_Reference" => $pur_ref,
            "Transaction_Account" => $suppAccount,
            "Transaction_Type" => "Debit",
            "Transaction_Amount" => $this->info['Purchase_Net_Total'] - $remaining,
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "main_nb" => $pur_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        );
        JV::addTransaction($dat_12, $is_actual);
        $dat_4 = [
            "JV_ID" => $jv,
            "Transaction_Reference" => 'credit',
            "Transaction_Account" => $this->info['Card_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Card_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "subtype" => "credit",
            "main_nb" => $pur_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_4, $is_actual);
        $dat_5 = [
            "JV_ID" => $jv,
            "Transaction_Reference" => 'cash',
            "Transaction_Account" => $this->info['Cash_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Cash_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => $this->info['Purchase_Due_Date'],
            "subtype" => "cash",
            "main_nb" => $pur_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_5, $is_actual);
        $dat_6 = ["JV_ID" => $jv,
            "Transaction_Reference" => 'check',
            "Transaction_Account" => $this->info['Check_Account'],
            "Transaction_Type" => "Credit",
            "Transaction_Amount" => $this->info['Check_Amount'],
            "Transaction_Date" => $this->info['Purchase_Date'],
            "Currency_ID" => $this->info['Currency_ID'],
            "Logged_ID" => $this->info['Logged_ID'],
            "date_created" => $old_date_created,
            "created_logged_id" => $old_created_logged_id,
            "Transaction_Description" => $desc,
            "Current_Ex_Rate" => $rate,
            "second_currency_rate" => $second_rate,
            "main_id" => $this->info['Invoice_ID_Auto'],
            "main_type" => "pur",
            "branch_id" => $branch_id,
            "due_date" => (!empty($this->info['check_due_date']) ? $this->info['check_due_date'] : $this->info['Purchase_Due_Date']),
            "value_date" => $this->info['value_date'],
            "check_nb" => $this->info['Check_Num'],
            "subtype" => "check",
            "main_nb" => $pur_num,
            "job_id" => $this->info['job_id'],
            "project_id" => $this->info['project_id']
        ];
        JV::addTransaction($dat_6, $is_actual);

        $error = $this->db->error();
        if (empty($error)) {
            if (!$this->stop_transaction_start_end)
                $this->db->query('COMMIT');
            return $return_inv_num ? [$this->info['Invoice_ID_Auto'], $pur_num] : $this->info['Invoice_ID_Auto'];
        } else {
            if (!$this->stop_transaction_start_end)
                $this->db->query('ROLLBACK');
            return $return_inv_num ? [array_unique($error)] : array_unique($error);
        }
        return array_unique($error);
    }

    public function change_purchase_actual($id_arr, $is_actual) {
        $this->db->query('START TRANSACTION');
        //        $query = $this->db->query('select invoice_prefix from tbl_invoices where Invoice_ID_Auto = "'.$id.'"');
        //        $prefix = $this->db->assoc($query)['invoice_prefix'];
        foreach ($id_arr as $id) {
            $purch_num = self::getMaxPurchase($is_actual);
            $this->db->prepare_Stmt('update tbl_inventory_purchases set Purchase_ID = ?,is_actual=?
            where Purchase_ID_Auto = ?', [&$purch_num, &$is_actual, &$id]);
            $jv = JV::returnJV($is_actual);
            $ref = "Pur." . $purch_num;
            $this->db->prepare_Stmt('update tbl_accounting_transactions set main_nb= ?, 
            is_actual = ?,JV_ID = ?
            where main_id = ? and main_type="pur"', [&$purch_num, &$is_actual, &$jv, &$id]);
            $this->db->prepare_Stmt('update tbl_accounting_transactions set Transaction_Reference = ?
            where main_id = ? and main_type="pur" and subtype=""', [&$ref, &$id]);
            $this->db->prepare_Stmt('update tbl_stock_product_transactions set is_actual = ?
            where main_id = ? and Transaction_Type_ID in (1,12) ', [&$is_actual, &$id]);
        }
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return $error;
    }

    public function get_purchase_item_ids($id) {
        $data = array();
        $query = $this->db->query('select distinct Product_ID 
            from tbl_inventory_purchase_items where Purchase_ID_Auto = "' . $id . '"');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row['Product_ID'];
        }
        return (implode(',', $data));
    }

    //public function change_purchase_actual($id_arr, $is_actual) {
    //        $this->db->query('START TRANSACTION');
    //        foreach ($id_arr as $id) {
    //            $inv_nb = self::getMaxPurchase($is_actual);
    //            $this->db->prepare_Stmt('update tbl_inventory_purchases set Purchase_ID = ?,is_actual=?
    //            where Purchase_ID_Auto = ?', [&$inv_nb, &$is_actual, &$id]);
    //            $jv = JV::returnJV($is_actual);
    //            $ref = "Inv." .  $inv_nb;
    //            $this->db->prepare_Stmt('update tbl_accounting_transactions set main_nb= ?, 
    //            is_actual = ?,JV_ID = ?
    //            where main_id = ? and main_type="pur"', [&$inv_nb, &$is_actual, &$jv, &$id]);
    //            $this->db->prepare_Stmt('update tbl_accounting_transactions set Transaction_Reference = ?
    //            where main_id = ? and main_type="pur" and subtype=""', [&$ref, &$id]);
    //            $this->db->prepare_Stmt('update tbl_stock_product_transactions set is_actual = ?
    //            where main_id = ? and Transaction_Type_ID in (1,12) ', [&$is_actual, &$id]);
    //        }
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            $this->db->query('COMMIT');
    //        } else {
    //            $this->db->query('ROLLBACK');
    //        }
    //        return $error;
    //    }

    public function get_purchase_from_sales_order($id) {
        $data = array();
        $query = $this->db->query('select  d.*,
            uc.Bar_Code,ps.Product_Code,ps.Product_Name,
            s.Supplier_ID,s.Supplier_Name,pc.Class_Name,
            ifnull(ip.Product_Price,0) as Product_Price,pc.Currency_ID,
             GROUP_CONCAT(uom_from separator "/") AS Product_UOM
            from tbl_purchase_order_details d join tbl_purchase_order o
            on o.Order_ID = d.Order_ID
            join uom_conversions uc
            on uc.Product_ID = d.Item_ID
            left join tbl_stock_products ps 
            on ps.Product_ID = d.Item_ID
            left join tbl_pricing_class pc on pc.Class_ID = d.supp_class_id
            left join tbl_stock_suppliers s on s.Supplier_ID = pc.supplier_id
            left join tbl_item_price_by_classes ip 
            on ip.Class_ID = d.supp_class_id and d.Item_ID = ip.Product_ID and d.UOM_ID = ip.UOM_ID
            where d.Order_ID = "' . $id . '"
            group by d.Entry_ID
        ');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function convert_sales_to_multi_purchase($products) {
        $this->stop_transaction_start_end = true;
        $data = array();
        foreach ($products as $row) {
            $data[$row['supplier_id']][$row['Currency_ID']][] = $row;
        }
        //        echo"<pre>";
        //        die(print_r($data));
        foreach ($data as $supplier_id => $cur_row) {

            foreach ($cur_row as $currency_id => $item) {
                $submit_data = array();
                $submit_data['Products'] = array();
                $submit_data['Invoice_Net_Total'] = 0;
                $submit_data['Invoice_Sub_Total'] = 0;
                $submit_data['total_cost'] = 0;
                foreach ($item as $row) {
                    $submit_data['is_actual'] = $row['is_actual'];
                    $submit_data['Depot_ID'] = $row['Depot_ID'];
                    $submit_data['Logged_ID'] = smc_session()['user_logged_id'];
                    $submit_data['Customer_ID'] = $supplier_id;
                    $submit_data['Invoice_Due_Date'] = $row['Invoice_Due_Date'];
                    $submit_data['Invoice_Date'] = $row['Invoice_Date'];
                    $submit_data['Invoice_Currency'] = $currency_id;
                    $submit_data['IsSales'] = 0;
                    $submit_data['is_quotation'] = 0;
                    $submit_data['Invoice_VAT'] = 0;
                    $submit_data['Invoice_Discount'] = 0;
                    $submit_data['discount_amount'] = 0;
                    $submit_data['Class_ID'] = 0;
                    $submit_data['supp_class_id'] = $row['class_id'];
                    $submit_data['job_id'] = $row['job_id'];
                    $submit_data['project_id'] = $row['project_id'];
                    $submit_data['sales_pur_order_id'] = $row['sales_order_id'];
                    $submit_data['quotation_id'] = 0;
                    //                foreach ($row['Products'] as $item) {
                    $submit_data['Products'][] = array(
                        'Product_ID' => $row['Product_ID'],
                        'UOM_ID' => $row['UOM_ID'],
                        'Item_Quantity' => $row['Item_Quantity'],
                        'Item_Discount' => 0,
                        'Item_Price' => $row['item_cost'],
                        'item_cost' => $row['item_cost'],
                        'other_cost' => 0,
                        'Product_Total_Price' => $row['Product_Total_Price'],
                        'vat_percent' => 0,
                        'vat_val' => 0,
                        'class_id' => $row['class_id'],
                        'depot_id' => $row['depot_id'],
                    );
                    //                }
                    $submit_data['Invoice_Net_Total'] += $row['Product_Total_Price'];
                    $submit_data['Invoice_Sub_Total'] += $row['Product_Total_Price'];
                    $submit_data['total_cost'] += $row['Product_Total_Price'];
                }
            }
            $this->setData($submit_data)->addPurchaseOrder();
            //            echo "<pre>";
            //            print_r($submit_data);
            //            echo"===================================";
        }
        $error = $this->db->error();
        if (empty($error))
            $this->db->query('COMMIT');
        else
            $this->db->query('ROLLBACK');
        return $error;
    }

    public function get_quotation_revision($version_id) {
        $data = array();
        $query = $this->db->query('select version_array from tbl_versions where version_id = "' . $version_id . '"');
        $json_arr = $this->db->assoc($query)['version_array'];
        $data = json_decode($json_arr, true);
        return $data;
    }

    public function get_total_sales_ordered_items_totals() {
        $cond = ' where current_year_id="' . $this->year_id . '"';
        if (!empty($this->info['date_created_from']) && !empty($this->info['date_created_to'])) {
            $cond .= ' AND date_created between "' . $this->info['date_created_from'] . '" AND  "' . $this->info['date_created_to'] . '"';
        }
        if (!empty($this->info['From_Date']) && !empty($this->info['To_Date'])) {
            $cond .= ' AND date(delivery_date) between "' . $this->info['From_Date'] . '" AND  "' . $this->info['To_Date'] . '"';
        }
        if (!empty($this->info['users'])) {
            $cond .= ' AND Logged_ID in (' . $this->info['users'] . ')';
        }
        if (is_numeric($this->info['customer_id'])) {
            $cond .= ' AND Supplier_ID = "' . $this->info['customer_id'] . '"';
        }
        if (!empty($this->info['branch_id'])) {
            $cond .= ' AND branch_id = "' . $this->info['branch_id'] . '"';
        }
        if (!empty($this->info['category'])) {
            $cond .= ' AND Category_ID = "' . $this->info['category'] . '"';
        }
        if (isset($this->info['is_sales'])) {
            $cond .= ' AND is_sales = "' . $this->info['is_sales'] . '" ';
        }
        if (!empty($this->info['status_id']) && $this->info['status_id'] != 0) {
            $cond .= ' and is_converted = "' . ($this->info['status_id'] == 1 ? '0' : '1') . '"';
        }
        //        if ($is_actual == 0) {
        $cond .= ' and is_actual = "' . $this->info['is_actual'] . '"';
        //        }

        $query_str = 'select delivery_date, sum(total_price * current_rate) as sub_total_price,
                sum(vat_amount * current_rate) as total_vat_price
                from  mov_sales_order u';
        $query = $this->db->query($query_str . $cond);


        $arr = array();
        $row = $this->db->assoc($query);
        $sub_total = ($row['sub_total_price']);
        $vat_total = ($row['total_vat_price']);
        $totals = CommonFunctions::formatNumber($row['sub_total_price'] + $row['total_vat_price']);
        $sub_total = CommonFunctions::formatNumber($sub_total);
        $vat_total = CommonFunctions::formatNumber($vat_total);
        //        $total_quantity = CommonFunctions::formatNumber($row['total_quantity']);
        $arr = array('total' => $totals, 'sub_total' => $sub_total,
            'vat_total' => $vat_total);

        return $arr;
    }

    public function search_orders($term = null, $page, $limit, $is_act = null, $is_sales = null) {
        $data = array();
        $data['is_more'] = false;
        $data['data'] = array();
        $cond = '';
        $data_filter = array();
        if (!is_null($term)) {
            $cond .= ' and (Person_Name LIKE ? or Order_Date LIKE ? or sale_nb LIKE ? )';
            $data_filter[] = "%" . $term . "%";
            $data_filter[] = "%" . $term . "%";
            $data_filter[] = "%" . $term . "%";
        }
        if (!is_null($is_act))
            $cond.=' and is_actual ="' . $is_act . '" ';
        $cond.=' and is_sales ="' . $is_sales . '" ';
        $query = $this->db->prepare_Stmt('select 
                                    concat_ws(" - ",Person_Name,Order_Date,sale_nb) as text,
                                    Order_ID as id 
                                from  purchase_order_list
                                where is_converted=0
                                ' . $cond . '
                                limit ' . ($page * $limit) . ',' . ($limit + 1), $data_filter);
        while ($row = $this->db->assoc($query)) {
            $data['data'][] = $row;
        }
        if (count($data['data']) > $limit) {
            array_pop($data['data']);
            $data['is_more'] = true;
        }
        return $data;
    }

    public function get_pending_order_count() {
        $cond ='';
        $user_id =smc_session()['user_details']['User_ID'];
        if (smc_session()['user_details']['limit_customer_invoice'] == 1) {
            $cond = ' and Logged_ID = '.$user_id.'';
        }
        if($this->permissions->hasPermission('Branches')){
            $cond .=  '';

        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
 
        }

        $data = array('actual' => 0, 'official' => 0);
        $query = $this->db->query('SELECT count(*) as order_count,is_actual FROM `tbl_purchase_order` 
            WHERE `is_sales`=1 and `is_quotation`=0 and `is_converted`=0 
            and `current_year_id` = "' . $this->year_id . '" '.$cond .' group by is_actual');
        while ($row = $this->db->assoc($query)) {
            if ($row['is_actual'] == 0)
                $data['official'] = $row['order_count'];
            else
                $data['actual'] = $row['order_count'];
        }
        return $data;
    }

    public function get_purchase_to_deliver($id) {
        $data = array("Main" => array(), "Details" => array(), "Person" => array());
        $query_main = $this->db->query('select r.Purchase_Net_Total,
            r.Purchase_Shipping as shipping,r.extra_cost,r.cost_dist_method,r.Currency_ID,r.current_rate,r.current_year_id,
         r.Depot_ID,r.`Supplier_ID` as Person_ID,r.job_id,r.project_id,j.job_name,p.project_name,
         cu.Currency_Name,cu.Currency_Symbol
            from tbl_inventory_purchases r left join tbl_accounting_jobs j 
            on j.job_id = r.job_id left join tbl_projects p on p.project_id = r.project_id
            join tbl_common_currency cu on cu.Currency_ID = r.Currency_ID
            where `Purchase_ID_Auto` = "' . smc_escape($id) . '" ');
        $row = $this->db->assoc($query_main);
        if (!empty($row)) {
            $data['Main'] = $row;

            $data['Person'] = Supplier::getSupplierByID($data['Main']['Person_ID']);
            $query_details = $this->db->query('select
                                                i.`Item_ID`,
                                                p.`Purchase_ID_Auto`,
                                                i.Item_Quantity_Current AS Item_Quantity_Current,
                                                ps.Product_Code AS Code,
                                                ps.Product_Name AS Name,ps.is_lot,ps.is_serial,ps.is_service,
                                                ps.Status_ID,
                                                (( if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity) /uc.conversion_amount)+ i.Item_Quantity_Current) as Product_Quantity,
                                                (( if(isnull(l.Product_Depot_Quantity),0,l.Product_Depot_Quantity) /uc.conversion_amount)+ i.Item_Quantity_Current) AS Quantity,
                                                i.Product_ID,
                                                i.product_description,
                                                uc.Bar_Code,
                                                (i.`Item_Price`*((100-`Item_Discount`)/100)*((100-p.Purchase_Discount)/100)) as unit_cost,
                                                i.cost_percent,
                                                (i.Item_Quantity/i.Item_Quantity_Current) AS uom_con,
                                                 i.UOM_ID,i.expiry_date,ps.is_expiry,i.lot_nb,i.serial_nb,
                                                 i.additional_cost,
                                                GROUP_CONCAT(uom_from separator "/") AS Product_UOM
                                            from tbl_inventory_purchase_items i 
                                            join tbl_inventory_purchases p 
                                            on p.`Purchase_ID_Auto` = i.`Purchase_ID_Auto`
                                            join uom_conversions uc ON uc.Product_ID = i.Product_ID
                                            join tbl_stock_products ps on ps.Product_ID = i.Product_ID
                                            left join tbl_stock_product_location l on l.Location_Product_ID = i.Product_ID and l.Product_Depot_ID = "' . $data['Main']['Depot_ID'] . '"
                                            where p.`Purchase_ID_Auto` = "' . $id . '"
                                            GROUP BY i.`Item_ID`
                                            order by i.`Item_ID`

                                            ');
            while ($row = $this->db->assoc($query_details)) {
                $row['cost_arr'] = array();
                $data['Details'][$row['Item_ID']] = $row;
            }
        }
        $data['extra_cost'] = array();
        $query_ex = $this->db->query('select c.*,
            ifnull(concat(deb.Account_Code," - ",deb.Account_Name),"") as debit_acc_name,
            ifnull(concat(cre.Account_Code," - ",cre.Account_Name),"") as credit_acc_name
            from tbl_purchase_extra_cost c
            left join tbl_chart_of_accounts deb on deb.Account_ID = c.debit_acc_id
            left join tbl_chart_of_accounts cre on cre.Account_ID = c.credit_acc_id
            where purchase_id = "' . $id . '"');
        while ($row = $this->db->assoc($query_ex)) {
            if (empty($row['purchase_detail_id'])) {
                $data['extra_cost'][] = $row;
            } else {
                $data['Details'][$row['purchase_detail_id']]['cost_arr'][] = $row;
            }
        }

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

    public static function getUnpaidInvoicesBySupplier($account, $currency, $pay_id = null, $is_actual = 0, $type = 'pay') {
        $db = DBConnectorFactory::loadDriver();
        $cust_query = $db->query('select main_id,main_type from
                            tbl_chart_of_accounts
                            where Account_ID = "' . $account . '" ');
        $crow = $db->assoc($cust_query);
        $cid = $crow['main_id'];
        $data = array();
        $local_currency = CurrencyFactory::returnLocalCurrency();
        //$pay_rate = CurrencyFactory::getLastExRate($currency);
        $fields = ' ';
        $cond = ' ';
        $where_cond = ' ';

        if (!empty($pay_id)) {
            $fields .= ' if(isnull(p.Payment_Amount),0,p.Payment_Amount) as inv_pay_amount, ';
            $cond .= ' left join tbl_invoice_payments p on i.Purchase_ID_Auto = p.inv_pur_id  and p.type = "' . $type . '"
                and p.record_id in(' . $pay_id . ') ';
        }
        if ($is_actual == 0) {
            $where_cond .= ' and is_actual = 0';
        }

        $query = $db->query('select   
                                    i.Purchase_ID_Auto as Invoice_ID_Auto,
                                    i.Purchase_ID as Invoice_ID,
                                    i.Purchase_Date as Invoice_Date, 
                                    i.current_rate,
                                    i.Currency_ID as Invoice_Currency,
                                    i.Purchase_Net_Total as Invoice_Net_Total,
                                    ' . $fields . '
                                    (i.Purchase_Paid_Amount + i.Payment_Paid_Amount-i.return_paid_amount) as Paid_Amount,
                                    ((i.Purchase_Net_Total+i.Purchase_Shipping) - i.Purchase_Paid_Amount - i.Payment_Paid_Amount-i.Return_Purchase_Total+i.return_paid_amount) as Remaining_Amount,
                                    supp.Supplier_Name as Customer_Name
                                from 
                                    tbl_inventory_purchases i
                                inner join tbl_stock_suppliers supp on supp.Supplier_ID = i.Supplier_ID    
                                    ' . $cond . '
                                where
                                   ( ((i.Purchase_Net_Total+i.Purchase_Shipping) - i.Purchase_Paid_Amount - i.Payment_Paid_Amount-i.Return_Purchase_Total+i.return_paid_amount) > 0 ' . (empty($pay_id) ? '' : ' || !isnull(Payment_Invoice_ID) ') . ')
                                and i.Supplier_ID = "' . $cid . '"  
                                    
            ' . $where_cond);
        while ($row = $db->assoc($query)) {
            $row['remaining_local'] = $row['Remaining_Amount'] * $row['current_rate'];
            if ($row['Invoice_Currency'] != $currency) {
                if ($currency == $local_currency) {
                    $row['Invoice_Net_Total'] = $row['Invoice_Net_Total'] * $row['current_rate'];
                    $row['Paid_Amount'] = $row['Paid_Amount'] * $row['current_rate'];
                    $row['Remaining_Amount'] = $row['Remaining_Amount'] * $row['current_rate'];
                } else {
                    $pay_rate = CurrencyFactory::getCurrencyTimeExchangeRate($currency, $local_currency, $row['Invoice_Date']);
                    $row['Invoice_Net_Total'] = ($row['Invoice_Net_Total'] * $row['current_rate']) / $pay_rate;
                    $row['Paid_Amount'] = ($row['Paid_Amount'] * $row['current_rate']) / $pay_rate;
                    $row['Remaining_Amount'] = ($row['Remaining_Amount'] * $row['current_rate']) / $pay_rate;
                }
            }
            $data[] = $row;
        }
//                die(print_r($data));
        return $data;
    }

}
