<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class warehousesTransfer extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $warehousesTransfer = $this->db->query("SELECT * FROM `warehousesTransfer`")->result();
        $warehouse = $this->db->query("SELECT * FROM `warehouse`")->result();
        $products = $this->db->query("SELECT * FROM `products` WHERE `type` = 1")->result();
        // debug($products);
        $this->template
            ->set('view', 'admin/warehousesTransfer/index')
            ->set('warehousesTransfer', $warehousesTransfer)
            ->set('warehouse', $warehouse)
            ->set('products', $products)
            ->render();
    }
    public function transferWarehouse()
    {
        $data   = (object)$_POST;
        // $warehouse = $this->db->query("SELECT * FROM `warehouse_items` WHERE `warehouse_id` = `$data->from_warehouse` AND `product_id` =`$data->product_id`")->result();
        $instock = $this->db->query("SELECT `ID`,`quantity` FROM `warehouse_items` WHERE `warehouse_id` = $data->from_warehouse AND `product_id`= $data->product_id ")->row();
        $instock_to = $this->db->query("SELECT `ID`,`quantity` FROM `warehouse_items` WHERE `warehouse_id` = $data->to_warehouse AND `product_id`= $data->product_id ")->row();

        // debug($instock_to);
        $warehousesTransfer_data = array(
            'from_warehouse'          => $data->from_warehouse,
            'to_warehouse'            => $data->to_warehouse,
            'quantity'                => $data->quantity,
            'product_id'              => $data->product_id,
            'notes'                   => $data->notes,
            'dateCreation'            => date('Y-m-d H:i:s')
        );
        $result = $this->general_model->insertRow('warehousesTransfer', $warehousesTransfer_data);
        $updateItemMinus = array(
            'quantity'  => $instock->quantity - $data->quantity,

        );
        // debug($instock->product_id);
        $warehouse_items_Minus = $this->general_model->updateRowById('warehouse_items', 'ID', $instock->ID, $updateItemMinus);


        $updateItems = array(
            'quantity'  => $instock_to->quantity + $data->quantity,
        );
        // debug($updateItems);
        $warehouse_items = $this->general_model->updateRowById('warehouse_items', 'ID', $instock_to->ID, $updateItems);

        // debug($warehouse_items);
        redirect('admin/warehousesTransfer/index', 'refresh');
    }
    public function getItemQuantity(){
        $instock = $this->db->query("SELECT `ID` ,`quantity` FROM `warehouse_items` WHERE `warehouse_id` ")->result();
        // debug($instock);
    }
}

