<?php

class SettingClass {

    private $db;
    private $info = array();

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }

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

    public function enableDisableItem() {
        $this->db->query('START TRANSACTION');
        $this->db->prepare_Stmt('update tbl_' . $this->info['target_item'] . ' set Status_ID = ? where ' . $this->info['target_item_id'] . ' = ? ', [&$this->info['status_id'], &$this->info['target_item_value']]);
        if ($this->info['target_item'] == 'customers' || $this->info['target_item'] == 'stock_suppliers') {
            $subtype = $this->info['target_item'] == 'customers' ? 'cust' : 'supp';
            $this->db->prepare_Stmt('update tbl_chart_of_accounts set Status_ID = ? where  main_id = ?  and main_type= ?', [&$this->info['status_id'], &$this->info['target_item_value'], &$subtype]);
        }

        if ($this->info['target_item'] == 'stock_products' && $this->info['status_id'] == 0 && smc_session()['default_setting']['enable_when_disable_item_qty_zero'] == 1) {

            /*
            For Invoice
            */
            $mydate = date("Y-m-d H:i:s");
            $logged_id = smc_session()['user_logged_id'];
            $is_actual = "false";
            $assign_type = "1"; //adjust
            $Currency_ID = smc_session()['default_currency']['Currency_ID'];
            $WarehouseDepot = new WarehouseDepot();
            $assign_nb = $WarehouseDepot->get_assign_nb($is_actual, $assign_type);
            $rate = CurrencyFactory::getLastExRate($Currency_ID);
            $second_rate = CurrencyFactory::getSecondCurrencyLastExRate($Currency_ID);

            $Depot_ID = smc_session()['default_depot_id'];
            $assign_date = date("Y-m-d");
            $year_id = smc_session()['current_year_id'];
            $adjust_note = 'Adjust from disabled item';
            $data = [
                $assign_nb, $assign_date, $Depot_ID,$adjust_note,
                $assign_type, $year_id, $mydate, $mydate, $logged_id, $logged_id,
                $Currency_ID, $rate, $second_rate, $is_actual
            ];
                $this->db->prepare_Stmt('INSERT INTO `tbl_assign_product`(`assign_nb`, `assign_date`, `Depot_ID`,
               `assign_note`, `assign_type`, `current_year_id`, `date_created`, `date_time`, `created_logged_id`,
               `Logged_ID`,Currency_ID,current_rate,second_currency_rate,is_actual) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)', $data);
            $assign_id = $this->db->id();


                /*
                For item
                */

                $Product_ID =  $this->info['target_item_value'];

                $cmd = "99";
                $class = smc_session()['pricing_class_id'];
                $depot =  null;
                $customer_id =  null;
                $cat_id = null;
                $type = null;
                $supp_class = '';
                $is_sales =  0;
                $is_purchase = 0;
                $term = $Product_ID;

                $Product = new Product();
                $product_data = $Product->getProductsForCustomer($class, $cmd, $term, $depot, $cat_id, $type, $customer_id, $supp_class, $is_sales, $is_purchase)[$Product_ID];

                
                $diff_qty =  $product_data['Quantity'] *(-1);
                $product_quantity = Product::getConvertedQuantity($product_data['UOM_ID'], $product_data['Quantity'], $product_data['ID']);
                $real_prd_diff_qty = Product::getConvertedQuantity($product_data['UOM_ID'], $diff_qty, $product_data['ID']);
                $prd_diff_qty = abs($real_prd_diff_qty);
                //            $total += $product_quantity;
                //            $rate = CurrencyFactory::getLastExRate($item['Currency_ID']);
                $expiry_date =  null;
                $lot_nb = '';
                $serial_nb =  '';
                $new_cost =0;
                $item_note ='';
                $detail_data = [
                    $assign_id, $product_data['ID'], $product_data['UOM_ID'],  0, 0,
                    $diff_qty, $real_prd_diff_qty, $item_note, $product_data['current_cost'], $lot_nb, $serial_nb, $expiry_date
                ];
                $this->db->prepare_Stmt('INSERT INTO `tbl_assign_product_details`(`assign_id`, `Product_ID`, `UOM_ID`,
                `current_quantity`, `quantity`, `current_diff_qty`, `diff_qty`, `detail_note`, `unit_cost`, `lot_nb`, 
                `serial_nb`, `expiry_date`) values(?,?,?,?,?,?,?,?,?,?,?,?)', $detail_data);
                $costdata = [
                    "Product_ID" => $product_data['ID'],
                    "Quantity" => $prd_diff_qty,
                    "Unit_Cost" => $new_cost,
                    "Currency_ID" => $Currency_ID,
                    "date_time" => $mydate,
                    "date_time_now" => $mydate,
                    "current_rate" => $rate,
                    "depot_id" => $Depot_ID,
                    "trans_date" => $assign_date,
                    "current_quantity" => $product_data['Quantity'],
                    "uom_id" => $product_data['UOM_ID'],
                    "is_actual" => $is_actual,
                    "expiry_date" => $expiry_date,
                    "lot_nb" => $lot_nb,
                    "serial_nb" => $serial_nb,
                    "main_id" => $assign_id,
                    "is_service" => $product_data['is_service'],
                    "trans_note" => $item_note
                ];
                $type = $assign_type == 0 ? 'assign' : ($product_data['Quantity'] >= 0 ? 'adjust_positive' : 'adjust_negative');

                CommonBusiness::updateLinkQuantities($costdata, $type, ($product_data['Quantity'] >= 0 ? '-' : '+'));


        }



        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function submitDevice() {
        if ($this->info['device_id'] == 0) {
            $this->db->prepare_Stmt('insert into tbl_devices (device_name,device_ip,type_id,is_active,note) Values (?,?,?,?,?)', [&$this->info['device_name'], &$this->info['device_ip'], &$this->info['type_id'],
                &$this->info['is_active'], &$this->info['note']]);
        } else {
            $this->db->prepare_Stmt('update tbl_devices set device_name = ?,device_ip = ?,type_id = ?,is_active = ?,note = ?
            where device_id = ?', [&$this->info['device_name'], &$this->info['device_ip'], &$this->info['type_id'],
                &$this->info['is_active'], &$this->info['note'], &$this->info['device_id']]);
        }

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

    public function deleteDevice() {
        $this->db->prepare_Stmt('delete from tbl_devices where device_id = ? ', [&$this->info['device_id']]);
        $error = $this->db->error();
        return $error;
    }

    public function submitRegion() {
        if ($this->info['region_id'] == 0) {
            $this->db->prepare_Stmt('insert into tbl_regions (region_name) Values (?)', [&$this->info['region_name']]);
        } else {
            $this->db->prepare_Stmt('update tbl_regions set region_name = ? where region_id = ?', [&$this->info['region_name'], &$this->info['region_id']]);
        }

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

    public function deleteRegion() {
        $this->db->prepare_Stmt('delete from tbl_regions where region_id = ? ', [&$this->info['region_id']]);
        $error = $this->db->error();
        return $error;
    }

    public function submitUserSetting() {
        $this->db->query('START TRANSACTION');
        $user_data = '';
        $user_setting = $this->info['user_setting'];
        $user_options = $this->info['user_options'];
        if (in_array(1, $user_options)) {
            $user_data .= ' block_ids =?';
        }
        if (in_array(2, $user_options)) {
            $user_data .= ($user_data == '' ? '' : ',') . ' customer_group_ids =?';
        }
        if (in_array(3, $user_options)) {
            $user_data .= ($user_data == '' ? '' : ',') . ' notification_type_ids =?';
        }
        foreach ($user_setting as $setting) {
            $user_arr = [];
            $setting['block_ids'] = empty($setting['block_ids']) ? NULL : $setting['block_ids'];
            $setting['customer_group_ids'] = empty($setting['customer_group_ids']) ? NULL : $setting['customer_group_ids'];
            $setting['notification_type_ids'] = empty($setting['notification_type_ids']) ? NULL : $setting['notification_type_ids'];
            if (in_array(1, $user_options))
                $user_arr[] = &$setting['block_ids'];
            if (in_array(2, $user_options))
                $user_arr[] = &$setting['customer_group_ids'];
            if (in_array(3, $user_options))
                $user_arr[] = &$setting['notification_type_ids'];
            $user_arr[] = &$setting['user_id'];
            $this->db->prepare_Stmt('update tbl_common_users set ' . $user_data . ' where  User_ID = ?', $user_arr);
        }
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function submit_lock() {
        $logged_id = smc_session()['user_logged_id'];
        $date_time = date('Y-m-d H:i:s');
        if (empty($this->info['lock_id'])) {
            $data = [$this->info['lock_date'], $date_time, $logged_id, $date_time, $logged_id];
            $this->db->prepare_Stmt('insert into tbl_lock_data (lock_date,date_time,Logged_ID,
                date_created,created_logged_id) values(?,?,?,?,?)', $data);
        } else {
            $data = [$this->info['lock_date'], $date_time, $logged_id, $this->info['lock_id']];
            $this->db->prepare_Stmt('update tbl_lock_data set lock_date=?,date_time=?,Logged_ID=?
                where lock_id = ?', $data);
        }
        $error = $this->db->error();
        return $error;
    }
    public function delete_lock_data() {
        $this->db->prepare_Stmt('delete from tbl_lock_data where lock_id = ? ', [&$this->info['lock_id']]);
        $error = $this->db->error();
        return $error;
    }

}
