<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\ImportExport;
use App\Models\ImportExportItem;
use App\Models\Item;
use App\Models\ItemType;
use App\Models\Room;
use App\Models\Warehouse;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WarehouseController extends BaseController {
	//
	/**
	 * @api {get} /list Lấy danh sách kho
	 * @apiName list
	 * @apiGroup Warehouse
	 * @apiDescription Lấy danh sách kho
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getWarehouses() {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}

		$warehouses = Warehouse::where( 'owner_id', $ownerId )->get();

		return response( [
			'status' => 1,
			'data'   => $warehouses
		] );
	}

	/**
	 * @api {get} /remain-detail Lấy chi tiết tồn kho
	 * @apiName remain-detail
	 * @apiGroup Warehouse
	 * @apiParam {String} warehouse_id
	 * @apiDescription Lấy chi tiết tồn kho
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getRemainDetail( Request $request ) {
		$warehouseId = $request->input( 'warehouse_id' );
		$items       = \DB::table( 'item_warehouses' )
		                  ->selectRaw( 'SUM(`item_warehouses`.`amount`) as remain, item_types.name as item_type_name' )
		                  ->join( 'item_types', 'item_warehouses.item_type_id', '=', 'item_types.id' )
		                  ->where( 'warehouse_id', $warehouseId )
		                  ->groupBy( 'item_type_id' )
		                  ->get();

		return response( [
			'status' => 1,
			'data'   => $items
		] );
	}

	/**
	 * @api {post} /create Tạo kho
	 * @apiName create
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} name
	 * @apiDescription Tạo kho
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function storeWarehouse( Request $request ) {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}
		$data             = $request->all();
		$data['owner_id'] = $ownerId;
		Warehouse::create( $data );

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}


	/**
	 * @api {post} /create-item-type Tạo loại tài sản
	 * @apiName create-item-type
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} name
	 * @apiParam {String} reference
	 * @apiDescription Tạo loại tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function storeItemType( Request $request ) {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}

		$data             = $request->all();
		$data['owner_id'] = $ownerId;
		$data['code']     = 'ITT-' . uniqid();
		ItemType::create( $data );

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}


	/**
	 * @api {post} /create-item Tạo tài sản
	 * @apiName create-item
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} item_type_id
	 * @apiParam {String} warehouse_id
	 * @apiParam {String} reference
	 * @apiParam {String} price
	 * @apiParam {String} status kiểu chuỗi
	 *
	 * @apiDescription Tạo tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function storeItem( Request $request ) {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}

		$data = $request->all();

		$numbers = 1;

		$itemTypeId = $data['item_type_id'];
		$itemType   = ItemType::find( $itemTypeId );
		if ( ! $itemType ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$warehouseId = $data['warehouse_id'];
		$warehouse   = Warehouse::find( $warehouseId );
		if ( ! $warehouse ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}
		//$createData = [];

		try {
			\DB::beginTransaction();

			$ie = ImportExport::create( [
				'item_type_id' => $itemType->id,
				'warehouse_id' => $warehouseId,
				'import'       => 1,
				'export'       => 0,
				'type'         => Warehouse::IMPORT,
				'user_id'      => $this->user->id,
			] );

			$createData = [
				'name'         => $itemType->name,
				'code'         => 'ITEM-' . uniqid(),
				'reference'    => isset( $data['reference'] ) ? $data['reference'] : null,
				'owner_id'     => $ownerId,
				'item_type_id' => $itemType->id,
				'price'        => isset( $data['price'] ) ? $data['price'] : null,
				'status'       => isset( $data['status'] ) ? $data['status'] : null,
			];

			$item = Item::create( $createData );

			ImportExportItem::create( [
				'item_type_id'     => $itemType->id,
				'item_id'          => $item->id,
				'import_export_id' => $ie->id,
			] );


			\DB::table( 'item_warehouses' )->insert( [
				'item_id'      => $item->id,
				'item_type_id' => $itemType->id,
				'warehouse_id' => $warehouseId,
				'amount'       => 1
			] );

			$itemType->remain = $itemType->remain + $numbers;
			$itemType->save();

			$warehouse->remain = $warehouse->remain + $numbers;
			$warehouse->save();


			\DB::commit();
		} catch ( \Exception $exception ) {
			\DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra'
			] );
		}

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}

	/**
	 * @api {post} /update Cập nhật kho
	 * @apiName update
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} name
	 * @apiParam {String} id
	 * @apiDescription Cập nhật kho
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function updateWarehouse( Request $request ) {
		$data = $request->all();
		$id   = $data['id'];
		$item = Warehouse::find( $id );
		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$item->update( $data );

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}

	/**
	 * @api {post} /room-item Lấy tài sản của phòng
	 * @apiName room-item
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} room_id
	 * @apiDescription Lấy tài sản của phòng
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getRoomItem( Request $request ) {
		$id        = $request->input( 'room_id' );
		$room = Room::find($id);
		$roomItems = $room->items;
		foreach ($roomItems as $item)
        {
            $warehouseArr  = null;
            $warehouseItem = \DB::table( 'item_warehouses' )->where( 'item_id', $item->id )->first();
            if ( $warehouseItem ) {
                $warehouseId = $warehouseItem->warehouse_id;
                $warehouse   = Warehouse::find( $warehouseId );
                if ( $warehouse ) {
                    $warehouseArr = [
                        'id'   => $warehouse->id,
                        'name' => $warehouse->name
                    ];

                }
            }
            $item->warehouse = $warehouseArr;

            $roomItem = \DB::table( 'room_items' )->where( 'item_id', $item->id )->first();

            $roomItemArr = null;
            if ( $roomItem ) {
                $roomId = $roomItem->room_id;
                $room   = Room::find( $roomId );
                if ( $room ) {
                    $roomItemArr = [
                        'id'   => $room->id,
                        'name' => $room->name
                    ];

                }
            }
            $item->room = $roomItemArr;

            $itemTypeArr = null;
            $itemTypeId  = $item->item_type_id;
            $itemType    = ItemType::find( $itemTypeId );
            if ( $itemType ) {
                $itemTypeArr = [
                    'id'   => $itemType->id,
                    'name' => $itemType->name
                ];
            }

            $item->item_type = $itemTypeArr;
        }

		return response( [
			'status' => 1,
			'data'   => $roomItems
		] );
	}


	/**
	 * @api {post} /update-item-type Cập nhật loại tài sản
	 * @apiName update-item-type
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} name
	 * @apiParam {String} reference
	 * @apiParam {String} id
	 * @apiDescription Cập nhật loại tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */

	public function updateItemType( Request $request ) {
		$data = $request->all();
		$id   = $data['id'];
		$item = ItemType::find( $id );
		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$item->update( $data );

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}


	/**
	 * @api {get} /item-type Lấy danh sách loại tài sản
	 * @apiName item-type
	 * @apiGroup Warehouse
	 * @apiDescription Lấy danh sách loại tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */

	public function getItemTypes() {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}

		$itemTypes = ItemType::where( 'owner_id', $ownerId )->get();

		foreach ( $itemTypes as $itemType ) {
			$cnt           = Item::where( 'item_type_id', $itemType->id )->count();
			$itemType->cnt = $cnt;
		}

		return response( [
			'status' => 1,
			'data'   => $itemTypes
		] );
	}

	/**
	 * @api {get} /item Lấy danh sách tài sản
	 * @apiName item
	 * @apiGroup Warehouse
	 * @apiDescription Lấy danh sách tài sản
	 *
	 * @apiParam {String} limit
	 * @apiParam {String} offset
	 * @apiParam {String} item_type_id
	 * @apiParam {String} warehouse_id
	 * @apiParam {String} is_available 1 nếu muốn lấy các tài sản chưa bị thêm
	 *
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getItems( Request $request ) {
		$ownerId = $this->user->id;

		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}

		$limit       = $request->input( 'limit' );
		$offset      = $request->input( 'offset' );
		$itemTypeId  = $request->input( 'item_type_id' );
		$isAvailable = $request->input( 'is_available' );
		$warehouseId = $request->input( 'warehouse_id' );

		$items = Item::query()->where( 'owner_id', $ownerId );

		if ( ! empty( $itemTypeId ) ) {
			$items = $items->where( 'item_type_id', $itemTypeId );
		}

		$itemsSelected = \DB::table( 'room_items' )->pluck( 'item_id' )->toArray();
		$itemIds       = [];
		if ( ! empty( $warehouseId ) ) {
			$itemIds = \DB::table( 'item_warehouses' )
			              ->where( 'warehouse_id', $warehouseId );

			if ( ! empty( $itemTypeId ) ) {
				$itemIds = $itemIds->where( 'item_type_id', $itemTypeId );
			}

			$itemIds = $itemIds->pluck( 'item_id' )->toArray();
		}


		if ( $isAvailable == 1 ) {
			$items = $items->whereNotIn( 'id', $itemsSelected );
		}

		if ( ! empty( $warehouseId ) ) {
			$items = $items->whereIn( 'id', $itemIds );
		}

		$items = $items->limit( $limit )->offset( $offset )->get();

		foreach ( $items as $item ) {
			$warehouseArr  = null;
			$warehouseItem = \DB::table( 'item_warehouses' )->where( 'item_id', $item->id )->first();
			if ( $warehouseItem ) {
				$warehouseId = $warehouseItem->warehouse_id;
				$warehouse   = Warehouse::find( $warehouseId );
				if ( $warehouse ) {
					$warehouseArr = [
						'id'   => $warehouse->id,
						'name' => $warehouse->name
					];

				}
			}
			$item->warehouse = $warehouseArr;

			$roomItem = \DB::table( 'room_items' )->where( 'item_id', $item->id )->first();

			$roomItemArr = null;
			if ( $roomItem ) {
				$roomId = $roomItem->room_id;
				$room   = Room::find( $roomId );
				if ( $room ) {
					$roomItemArr = [
						'id'   => $room->id,
						'name' => $room->name
					];

				}
			}
			$item->room = $roomItemArr;

			$itemTypeArr = null;
			$itemTypeId  = $item->item_type_id;
			$itemType    = ItemType::find( $itemTypeId );
			if ( $itemType ) {
				$itemTypeArr = [
					'id'   => $itemType->id,
					'name' => $itemType->name
				];
			}

			$item->item_type = $itemTypeArr;
		}

		return response( [
			'status' => 1,
			'data'   => $items
		] );
	}

	/**
	 * @api {post} /update-item Cập nhật tài sản
	 * @apiName update-item
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id
	 * @apiParam {String} reference Mã tham chiếu
	 * @apiParam {String} item_type_id
	 * @apiParam {String} price
	 * @apiParam {String} status
	 *
	 * @apiDescription Lấy danh sách tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */

	public function updateItem( Request $request ) {
		$data = $request->all();
		$id   = $data['id'];
		$item = Item::find( $id );
		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		if ( isset( $data['warehouse_id'] ) ) {
			$currentWarehouseId = null;
			$currentWarehouse   = \DB::table( 'item_warehouses' )->where( 'item_id', $id )->first();
			if ( $currentWarehouse ) {
				$currentWarehouseId = $currentWarehouse->warehouse_id;
			}
			$newWarehouseId = $data['warehouse_id'];

			if ( $newWarehouseId != $currentWarehouseId ) {
				//nhập kho mới
				$newWarehouse = Warehouse::find( $newWarehouseId );

				if ( ! $newWarehouse ) {
					return response( [
						'status'  => 0,
						'message' => 'Dữ liệu không hợp lệ'
					] );
				}

				$newWarehouse->remain = $newWarehouse->remain + 1;
				$newWarehouse->save();

				$ie = ImportExport::create( [
					'item_type_id' => $item->item_type_id,
					'warehouse_id' => $newWarehouse->id,
					'import'       => 1,
					'export'       => 0,
					'type'         => Warehouse::IMPORT,
					'user_id'      => $this->user->id,
				] );

				ImportExportItem::create( [
					'item_type_id'     => $item->item_type_id,
					'item_id'          => $item->id,
					'import_export_id' => $ie->id,
				] );

				// xuất kho cũ

				$oldWarehouse = Warehouse::find( $currentWarehouseId );

				if ( ! $oldWarehouse ) {
					return response( [
						'status'  => 0,
						'message' => 'Dữ liệu không hợp lệ'
					] );
				}

				$oldWarehouse->remain = $oldWarehouse->remain - 1;
				$oldWarehouse->save();

				$ie = ImportExport::create( [
					'item_type_id' => $item->item_type_id,
					'warehouse_id' => $oldWarehouse->id,
					'import'       => 0,
					'export'       => 1,
					'type'         => Warehouse::EXPORT,
					'user_id'      => $this->user->id,
				] );

				ImportExportItem::create( [
					'item_type_id'     => $item->item_type_id,
					'item_id'          => $item->id,
					'import_export_id' => $ie->id,
				] );
			}
		}

		$item->update( $data );


		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );

	}


	/**
	 * @api {post} /create-item-room Thêm tài sản vào phòng
	 * @apiName create-item-room
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} item_id
	 * @apiParam {String} room_id
	 * @apiParam {String} warehouse_id
     * @apiParam {String} receiver
     * @apiParam {String} mover
	 *
	 * @apiDescription Lấy danh sách tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function storeItemRoom( Request $request ) {
		$itemId      = $request->input( 'item_id' );
		$itemTypeId  = $request->input( 'item_type_id' );
		$receiver    = $request->input( 'receiver' );
		$mover       = $request->input( 'mover' );
		$roomId      = $request->input( 'room_id' );
		$warehouseId = $request->input( 'warehouse_id' );
		$hostelId    = null;
		$number      = 1;

		$room = Room::find( $roomId );
		if ( ! $room ) {

			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$hostelId = $room->hostel->id;

		$item = Item::find( $itemId );
		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}
		try {
			\DB::beginTransaction();
			$warehouseItem = Warehouse::find( $warehouseId );
			if ( $warehouseItem ) {
				$warehouseItem->remain = $warehouseItem->remain - 1;
				$warehouseItem->save();
			}

			$check = \DB::table( 'room_items' )
			            ->where( 'room_id', $roomId )
			            ->where( 'item_id', $itemId )
			            ->count();

			if ( $check > 0 ) {

				\DB::table( 'room_items' )
				   ->where( 'room_id', $roomId )
				   ->where( 'item_id', $itemId )
				   ->where( 'warehouse_id', $warehouseId )
				   ->update( [
					   'receiver'   => $receiver,
					   'mover'      => $mover,
					   'number'     => $number,
					   'updated_at' => Carbon::now()->toDateTimeString()
				   ] );
			} else {
				\DB::table( 'room_items' )->insert( [
					'room_id'      => $roomId,
					'item_id'      => $itemId,
					'number'       => $number,
					'warehouse_id' => $warehouseId,
					'created_at'   => Carbon::now()->toDateTimeString(),
					'updated_at'   => Carbon::now()->toDateTimeString(),
					'receiver'     => $receiver,
					'mover'        => $mover,
				] );
			}


			$itemWarehouse = \DB::table( 'item_warehouses' )
			                    ->where( 'warehouse_id', $warehouseId )
			                    ->where( 'item_id', $itemId )->count();

			if ( $itemWarehouse ) {
				\DB::table( 'item_warehouses' )
				   ->where( 'warehouse_id', $warehouseId )
				   ->where( 'item_id', $itemId )
				   ->decrement( 'amount', $number, [
					   'updated_at' => Carbon::now()->toDateTimeString()
				   ] );
			} else {
				\DB::table( 'item_warehouses' )->insert( [
					'item_id'      => $itemId,
					'warehouse_id' => $warehouseId,
					'amount'       => 0 - $number,
					'created_at'   => Carbon::now()->toDateTimeString(),
					'updated_at'   => Carbon::now()->toDateTimeString()
				] );
			}

			$ie = ImportExport::create( [
				'item_type_id' => $item->item_type_id,
				'warehouse_id' => $warehouseId,
				'import'       => 0,
				'export'       => 1,
				'type'         => Warehouse::EXPORT,
				'user_id'      => $this->user->id,
				'hostel_id'    => $hostelId,
				'room_id'      => $roomId,
				'receiver'     => $receiver,
				'mover'        => $mover,
			] );

			ImportExportItem::create( [
				'item_type_id'     => $item->item_type_id,
				'item_id'          => $item->id,
				'import_export_id' => $ie->id,
			] );

			\DB::commit();
		} catch ( \Exception $exception ) {
			\DB::rollBack();

			// dd($exception->getTraceAsString());
			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra'
			] );
		}

		return response( [
			'status'  => 1,
			'message' => 'Thành công',
		] );

	}

    /**
     * @api {post} /move-item Chuyển tài sản
     * @apiName move-item
     * @apiGroup Warehouse
     *
     * @apiParam {String} item_id
     * @apiParam {String} room_id Phong nhan vao
     * @apiParam {String} room_export_id Phong xuat ra
     * @apiParam {String} receiver
     * @apiParam {String} mover
     *
     * @apiDescription Lấy danh sách tài sản
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function processMoveItem( Request $request ) {
        $itemId       = $request->input( 'item_id' );
        $hostelId     = $request->input( 'hostel_id' );
        $roomId       = $request->input( 'room_id' );
        $roomExportId = $request->input( 'room_export_id' );
        $roomExport   = Room::find( $roomExportId );
        $receiver     = $request->input( 'receiver' );
        $mover        = $request->input( 'mover' );

        $room = Room::find( $roomId );
        $item = Item::find( $itemId );

        if ( ! $room ) {
            return response( [
                'status'  => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ] );
        }

        if ( ! $item ) {
            return response( [
                'status'  => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ] );
        }

        $export = ImportExport::create( [
            'item_id'      => $item->id,
            'item_type_id' => $item->item_type_id,
            'warehouse_id' => null,
            'import'       => 0,
            'export'       => 1,
            'type'         => Warehouse::EXPORT,
            'user_id'      => $this->user->id,
            'hostel_id'    => $roomExport->hostel->id,
            'room_id'      => $roomExportId,
            'receiver'     => $receiver,
            'mover'        => $mover,
        ] );

        ImportExportItem::create( [
            'item_type_id'     => $item->item_type_id,
            'item_id'          => $itemId,
            'import_export_id' => $export->id,
        ] );

        $import = ImportExport::create( [
            'item_id'      => $item->id,
            'item_type_id' => $item->item_type_id,
            'warehouse_id' => null,
            'import'       => 1,
            'export'       => 0,
            'type'         => Warehouse::IMPORT,
            'user_id'      => $this->user->id,
            'hostel_id'    => $room->hostel->id,
            'room_id'      => $roomId,
            'receiver'     => $receiver,
            'mover'        => $mover,
        ] );

        ImportExportItem::create( [
            'item_type_id'     => $item->item_type_id,
            'item_id'          => $itemId,
            'import_export_id' => $import->id,
        ] );

        $roomExport->items()->detach($item->id, [
            'mover' => $mover,
            'receiver' => $receiver
        ]);

        $room->items()->attach($item->id, [
            'mover' => $mover,
            'receiver' => $receiver
        ]);

        return response( [
            'status' => 1
        ] );
    }

	/**
	 * @api {post} /delete-item-room Xóa tài sản khỏi phòng
	 * @apiName delete-item-room
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id id này là id của bảng item_rooms, ko phải item_id hay room_id
	 *
	 * @apiDescription Xóa tài sản khỏi phòng
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function deleteItemRoom( Request $request ) {
		$id          = $request->input( 'id' );
		$item        = \DB::table( 'room_items' )->where( 'id', $id )->first();
		$warehouseId = null;
		$itemId      = null;
		$roomId      = null;
		$hostelId    = null;
		$itemTypeId  = null;
		$number      = 1;
		if ( $item ) {
			$itemId    = $item->item_id;
			$itemModel = Item::find( $itemId );
			if ( $itemModel ) {
				$itemTypeId = $itemModel->item_type_id;
			}
			$warehouseId = $item->warehouse_id;
			$roomId      = $item->room_id;
			$room        = Room::find( $roomId );
			if ( $room ) {
				$hostelId = $room->hostel->id;
			}
		}

		try {
			\DB::beginTransaction();

			\DB::table( 'room_items' )->where( 'id', $id )->delete();

			if ( $item ) {
				\DB::table( 'item_warehouses' )
				   ->where( 'warehouse_id', $warehouseId )
				   ->where( 'item_id', $itemId )
				   ->increment( 'amount', $number, [
					   'updated_at' => Carbon::now()->toDateTimeString()
				   ] );

//                $item = Item::find($itemId);
//                if ($item) {
//                    $item->remain = $item->remain + $number;
//                    $item->save();
//                }

				$warehouseItem = Warehouse::find( $warehouseId );
				if ( $warehouseItem ) {
					$warehouseItem->remain = $warehouseItem->remain + $number;
					$warehouseItem->save();
				}

				$ie = ImportExport::create( [
					'item_id'      => $itemId,
					'item_type_id' => $itemTypeId,
					'warehouse_id' => $warehouseId,
					'import'       => $number,
					'export'       => 0,
					'type'         => Warehouse::IMPORT,
					'user_id'      => $this->user->id,
					'room_id'      => $roomId,
					'hostel_id'    => $hostelId
				] );

				ImportExportItem::create( [
					'item_type_id'     => $itemTypeId,
					'item_id'          => $itemId,
					'import_export_id' => $ie->id,
				] );
			}

			\DB::commit();

		} catch ( \Exception $exception ) {
			\DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra'
			] );
		}

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}

	/**
	 * @api {post} /delete-item-type Xóa loại tài sản
	 * @apiName delete-item-type
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id
	 *
	 * @apiDescription Xóa loại tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function deleteItemType( Request $request ) {
		$id = $request->input( 'id' );

		$item = ItemType::find( $id );

		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$cnt = Item::where( 'item_type_id', $id )->count();

		if ( $cnt > 0 ) {

			return response( [
				'status'  => 0,
				'message' => 'Bạn phải xóa hết tài sản liên quan'
			] );
		}

		$item->delete();

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}


	/**
	 * @api {post} /delete-warehouse Xóa kho
	 * @apiName delete-warehouse
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id
	 *
	 * @apiDescription Xóa kho
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function deleteWarehouse( Request $request ) {
		$id = $request->input( 'id' );

		$item = Warehouse::find( $id );

		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$cnt = \DB::table( 'item_warehouses' )->where( 'warehouse_id', $id )->count();
		if ( $cnt > 0 ) {
			return response( [
				'status'  => 0,
				'message' => 'Bạn phải xóa hết tài sản liên quan'
			] );
		}


		$item->delete();

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}

	/**
	 * @api {post} /delete-item Xóa tài sản
	 * @apiName delete-item
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id
	 *
	 * @apiDescription Xóa tài sản
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function deleteItem( Request $request ) {
		$id   = $request->input( 'id' );
		$item = Item::find( $id );
		if ( ! $item ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		\DB::table( 'room_items' )
		   ->where( 'item_id', $id )
		   ->delete();

		\DB::table( 'item_warehouses' )
		   ->where( 'item_id', $id )
		   ->delete();
		$item->delete();

		return response( [
			'status'  => 1,
			'message' => 'Thành công'
		] );
	}


	/**
	 * @api {get} /history Lấy lịch sử nhập xuất
	 * @apiName history
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} start_date gửi lên dạng d/m/Y
	 * @apiParam {String} end_date gửi lên dạng d/m/Y
	 * @apiParam {String} room_id
	 * @apiParam {String} hostel_id
	 * @apiParam {String} limit
	 * @apiParam {String} offset
	 *
	 *
	 * @apiDescription Lấy lịch sử nhập xuất
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getHistory( Request $request ) {
		$userId = $this->user->id;
		$type   = $this->user->type;
		if ( $type == User::STAFF ) {
			$userId = $this->user->staff_owner_id;
		}
		$limit     = $request->input( 'limit', 10 );
		$offset    = $request->input( 'offset', 0 );
		$startDate = $request->input( 'start_date' );
		$endDate   = $request->input( 'end_date' );
		$roomId    = $request->input( 'room_id' );
		$hostelId  = $request->input( 'hostel_id' );

		$items = ImportExport::where( 'owner_id', $userId )
		                     ->orderBy( 'id', 'desc' )
		                     ->limit( $limit )
		                     ->offset( $offset );

		if ( ! empty( $startDate ) ) {
			$startDate = Carbon::createFromFormat( 'd/m/Y', $startDate )->startOfDay()->toDateTimeString();
			$items     = $items->where( 'created_at', '>=', $startDate );
		}

		if ( ! empty( $endDate ) ) {
			$endDate = Carbon::createFromFormat( 'd/m/Y', $endDate )->endOfDay()->toDateTimeString();
			$items   = $items->where( 'created_at', '<=', $endDate );
		}

		if ( ! empty( $hostelId ) ) {
			$items = $items->where( 'hostel_id', $hostelId );
		}

		if ( ! empty( $roomId ) ) {
			$items = $items->where( 'room_id', $roomId );
		}

		$items = $items->get();

		return response( [
			'status' => 1,
			'data'   => $items
		] );

	}


	/**
	 * @api {get} /detail-history Lấy danh sách tài sản trong lần nhập xuất
	 * @apiName detail-history
	 * @apiGroup Warehouse
	 *
	 * @apiParam {String} id
	 * @apiDescription Lấy danh sách tài sản trong lần nhập xuất
	 * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
	 * @apiSuccess {String} message  Tin nhắn hệ thống.
	 * @apiSuccess {String} data
	 */
	public function getDetailHistory( Request $request ) {
		$ieId  = $request->input( 'id' );
		$items = ImportExportItem::selectRaw( 'items.*' )
		                         ->where( 'import_export_id', $ieId )
		                         ->join( 'items', 'import_export_table.item_id', '=', 'items.id' )
		                         ->get();

		return response( [
			'status' => 1,
			'data'   => $items
		] );
	}

}
