<?php

namespace App\Http\Controllers\Backend;

use App\Components\Functions;
use App\Jobs\SendNotifcationRentersMoney;
use App\Models\CollectSpend;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\ElectricWater;
use App\Models\Extra;
use App\Models\Hostel;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\RoomFee;
use App\Models\Transaction;
use App\User;
use Carbon\Carbon;
use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Yajra\Datatables\Datatables;

class MoneyController extends AdminController {
	//
	public function getMoneyByAttributeView( Request $request ) {
		return view( 'admin.money.list' );
	}



	public function getMoneySpendByAttributeView( Request $request ) {
		$hostels = Hostel::orderBy( 'id', 'desc' );

		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$hostels = $hostels->where( 'owner_id', auth( 'backend' )->user()->id )->get();
			}
		}

		return view( 'admin.money.spend', compact( 'hostels' ) );
	}

	public function getMoneyByAttributeView2( Request $request ) {
		$hostels = Hostel::orderBy( 'id', 'desc' );

		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$hostels = $hostels->where( 'owner_id', auth( 'backend' )->user()->id )->get();
			}
		}

		return view( 'admin.money.list_2', compact( 'hostels' ) );
	}

	public function getCurrentData( Request $request ) {
		$now = Carbon::now()->format( 'm/Y' );

		return response( [
			'table_data' => view( 'admin.money.data' )->render()
		] );
	}

	public function getSpendByAttribute( Request $request ) {
		$items = Transaction::select( DB::raw( 'transactions.*' ) )->where( 'transactions.type', Transaction::SPEND );
		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$items = $items->join( 'hostels', 'transactions.hostel_id', '=', 'hostels.id' )
				               ->where( 'hostels.owner_id', auth( 'backend' )->user()->id );
			}
		}
		$items = $items->orderBy( 'transactions.id', 'desc' );

		return Datatables::of( $items )
		                 ->editColumn( 'amount', function ( $item ) {
			                 return number_format( $item->amount, 0, '.', '.' );
		                 } )
		                 ->addColumn( 'hostel', function ( $item ) {
			                 if ( $item->hostel ) {
				                 return $item->hostel->name;
			                 }
		                 } )
		                 ->editColumn( 'date_action', function ( $item ) {
			                 if ( $item->date_action ) {
				                 return $item->date_action->format( 'd/m/Y' );
			                 }
		                 } )
		                 ->addColumn( 'action', function ( $item ) {

		                 } )
		                 ->make( true );
	}

	public function spend( Request $request ) {
		$data = $request->all();

		$amount = $data['amount'];

		if ( empty( $amount ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được bỏ trống số tiền'
			] );
		}

		if ( ! is_numeric( $amount ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Số tiền phải là số'
			] );
		}


		$hostelId = $data['hostel_id'];

		if ( empty( $amount ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được bỏ trống nhà trọ'
			] );
		}


		$dateAction = $data['date_action'];

		if ( empty( $dateAction ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được bỏ trống ngày chi'
			] );
		}


		$dateAction = Carbon::createFromFormat( 'd/m/Y', $dateAction )->toDateString();

		$userId = null;
		if ( auth( 'backend' )->check() ) {
			$userId = auth( 'backend' )->user()->id;
		}

		Transaction::create( [
			'amount'      => $amount,
			'hostel_id'   => $hostelId,
			'date_action' => $dateAction,
			'user_id'     => $userId,
			'type'        => Transaction::SPEND,
			'note'        => $data['note']
		] );

		return response( [
			'status'  => 1,
			'message' => 'Tạo chi thành công'
		] );
	}

	public function charge( Request $request ) {
		$data       = $request->all();
		$dateAction = $data['date_action'];
		$amount     = $data['amount'];

		if ( empty( trim( $dateAction ) ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được để trống ngày thanh toán'
			] );
		}

		if ( empty( trim( $amount ) ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được để trống số tiền thanh toán'
			] );
		}

		if ( ! is_numeric( $amount ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Số tiền không hợp lệ'
			] );
		}

		$id = $data['id'];
		if ( ! empty( $dateAction ) ) {
			$dateAction = Carbon::createFromFormat( 'd/m/Y', $dateAction )->toDateString();

		} else {
			$dateAction = Carbon::now()->toDateString();
		}

		$moneyInfo = MoneyInfo::find( $id );
		$type = 'phòng';
		if ( $moneyInfo->type == MoneyInfo::VOUCHER_SERVICE ) {
			$type = 'dịch vụ';
		}

		$remain = 0;

		$payload = json_encode( [
			'id'   => null,
			'type' => null
		] );

		if ( $moneyInfo ) {
			$userId = null;
			if ( auth( 'backend' )->check() ) {
				$userId = auth( 'backend' )->user()->id;
			}

			$currentRemain = $moneyInfo->remain;

			if ( $amount > $currentRemain ) {
				return response( [
					'status'  => 0,
					'message' => 'Vui lòng không thu quá số tiền còn lại'
				] );
			}

			$transaction = Transaction::create( [
				'amount'        => $amount,
				'hostel_id'     => $moneyInfo->hostel_id,
				'room_id'       => $moneyInfo->room_id,
				'date_action'   => $dateAction,
				'user_id'       => $userId,
				'type'          => CollectSpend::COLLECT,
				'money_info_id' => $moneyInfo->id
			] );

			$payload = json_encode( [
				'id'   => $moneyInfo->id,
				'type' => config( 'constants.TRANSACTION' )
			] );

			$remain = $moneyInfo->remain - $amount;

			$moneyInfo->pay    = $moneyInfo->pay + $amount;
			$moneyInfo->remain = $remain;
			$moneyInfo->save();
		}

		$room = Room::find( $moneyInfo->room_id );

		if ( $room ) {
			$room->debt = $remain;
			$room->save();

			$notiDate = $moneyInfo->date_action->format( 'm/Y' );

			$renters = RenterRoom::where( 'room_id', $room->id )->get();

			foreach ( $renters as $renter ) {

				if ( $remain > 0 ) {
					Notification::create( [
						'image'     => auth( 'backend' )->user()->image,
						'to_user'   => $renter->user_id,
						'hostel_id' => $room->hostel->id,
						'room_id'   => $room->id,
						'title'     => 'Thông báo từ itro.vn',
						'payload'   => $payload,
						'user_id'   => auth( 'backend' )->user()->id,
						'content'   => 'Đã đóng ' . number_format( $amount, 0, '.', '.' ) . ' đ tiền '.$type.' tháng ' . $notiDate . '. Số tiền còn lại phải đóng là ' . number_format( $remain, 0, '.', '.' ) . 'đ',
					] );
				} else {
					Notification::create( [
						'image'     => auth( 'backend' )->user()->image,
						'to_user'   => $renter->user_id,
						'hostel_id' => $room->hostel->id,
						'room_id'   => $room->id,
						'title'     => 'Thông báo từ itro.vn',
						'payload'   => $payload,
						'user_id'   => auth( 'backend' )->user()->id,
						'content'   => 'Đã đóng đủ tiền '.$type.' tháng ' . $notiDate . '. Số tiền ' . number_format( $moneyInfo->pay, 0, '.', '.' ) . 'đ'
					] );
				}
			}
		}

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


	public function getMoneyByAttribute( Request $request ) {
		$items = CollectSpend::query()->orderBy( 'id', 'desc' );

		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$hostels = Hostel::query()->where( 'owner_id', auth( 'backend' )->user()->id )->pluck( 'id' )->toArray();
				$items   = $items->whereIn( 'hostel_id', $hostels );
			}
		}

		$startTime = $request->input( 'start_time' );
		$endTime   = $request->input( 'end_time' );
		$timeRange = $request->input( 'time_range' );

		return Datatables::of( $items )
		                 ->editColumn( 'type', function ( $item ) {
			                 return $item->type_text;
		                 } )
		                 ->editColumn( 'amount', function ( $item ) {
			                 return number_format( $item->amount, 0, '.', '.' );
		                 } )
		                 ->editColumn( 'date_action', function ( $item ) {
			                 return $item->date_action->format( 'd/m/Y' );
		                 } )
		                 ->editColumn( 'created_at', function ( $item ) {
			                 return $item->created_at->format( 'd/m/Y' );
		                 } )
		                 ->addColumn( 'action', function ( $item ) {


		                 } )->make( true );
	}

	public function createMoneyChange( Request $request ) {

	}

	public function calculateFee( $hostelId, $rooms, $dateAction ) {
		if ( empty( $dateAction ) ) {
			$startDate = Carbon::now()->startOfMonth()->toDateString();
			$endDate   = Carbon::now()->endOfMonth()->toDateString();
		} else {
			$startDate = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->startOfMonth()->toDateString();
			$endDate   = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->endOfMonth()->toDateString();
		}

		foreach ( $rooms as $room ) {

			$pay          = 0;
			$amountNumber = 0;
			$remain       = 0;

			$moneyInfo = MoneyInfo::where( 'room_id', $room->id )->where( 'date_action', '>=', $startDate )->where( 'date_action', '<=', $endDate )->first();

			$amount = Functions::calculateAmountMonthForRoom( $room, $dateAction );
			if ( $moneyInfo ) {
				$payBefore = Transaction::where( 'room_id', $room->id )
				                        ->where( 'type', '<>', CollectSpend::SPEND )
				                        ->where( 'date_action', '>=', $startDate )->where( 'date_action', '<=', $endDate )
				                        ->sum( 'amount' );

				$pay          = $payBefore + $amount['pay'];
				$amountNumber = $amount['amount'];
				$remain       = $amount['amount'] - $pay;

				$moneyInfo->update( [
					'amount' => $amount['amount'],
					'pay'    => $pay,
					'remain' => $amount['amount'] - $pay
				] );

				$moneyInfo->save();

				if ( $room ) {
					$room->debt = $amount['amount'] - $pay;
					$room->save();
				}
			} else {

				$pay          = $amount['pay'];
				$amountNumber = $amount['amount'];
				$remain       = $amount['amount'] - $amount['pay'];


				$moneyInfo = MoneyInfo::create( [
					'hostel_id'   => $hostelId,
					'room_id'     => $room->id,
					'amount'      => $amount['amount'],
					'pay'         => $amount['pay'],
					'remain'      => $amount['amount'] - $amount['pay'],
					'date_action' => Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->toDateString(),
				] );

				if ( $room ) {
					$room->debt = $amount['amount'] - $amount['pay'];
					$room->save();
				}

			}

			dispatch( new SendNotifcationRentersMoney( $room, $remain, $dateAction ) );

			MoneyDetail::where( 'money_info_id', $moneyInfo->id )->delete();
			$fees = RoomFee::where( 'room_id', $room->id )->get();

			$extras = Extra::where( 'room_id', $room->id )
			               ->where( 'date_action', '>=', $startDate )
			               ->where( 'date_action', '<=', $endDate )->get();

			$ew = ElectricWater::where( 'room_id', $room->id )->where( 'date_action', '>=', $startDate )->where( 'date_action', '<=', $endDate )->first();

			$hostel = $room->hostel;

			MoneyDetail::create( [
				'room_id'       => $room->id,
				'hostel_id'     => $hostelId,
				'name'          => 'Tiền phòng',
				'value'         => $room->price,
				'money_info_id' => $moneyInfo->id,
				'qty'           => 1,
				'amount'        => $room->price,
				'is_electric'   => true,
			] );

			if ( $ew ) {

				$ewPrice          = Functions::getEwRoom( $room );
				$deltaWater       = $ew->delta_water;
				$deltaElectric    = $ew->delta_electric;
				$ewAmountElectric = $deltaElectric * $ewPrice['electric'];
				$ewAmountWater    = $deltaWater * $ewPrice['water'];

				MoneyDetail::create( [
					'room_id'       => $room->id,
					'hostel_id'     => $hostelId,
					'name'          => 'Điện',
					'value'         => $ewPrice['electric'],
					'money_info_id' => $moneyInfo->id,
					'qty'           => json_encode( [
						'start'   => $ew->start_electric,
						'end'     => $ew->end_electric,
						'item_id' => $ew->id
					] ),
					'amount'        => $ewAmountElectric,
					'is_electric'   => true,

				] );

				MoneyDetail::create( [
					'room_id'       => $room->id,
					'hostel_id'     => $hostelId,
					'name'          => 'Nước',
					'value'         => $ewPrice['water'],
					'money_info_id' => $moneyInfo->id,
					'qty'           => json_encode( [
						'start'   => $ew->start_water,
						'end'     => $ew->end_water,
						'item_id' => $ew->id
					] ),
					'amount'        => $ewAmountWater,
					'is_water'      => true
				] );
			}

			foreach ( $fees as $fee ) {
				MoneyDetail::create( [
					'room_id'       => $room->id,
					'hostel_id'     => $hostelId,
					'name'          => $fee->name,
					'value'         => $fee->fee,
					'amount'        => $fee->fee,
					'qty'           => 1,
					'money_info_id' => $moneyInfo->id
				] );
			}

			foreach ( $extras as $extra ) {
				MoneyDetail::create( [
					'room_id'       => $room->id,
					'hostel_id'     => $hostelId,
					'name'          => $extra->name,
					'value'         => $extra->amount,
					'amount'        => $extra->amount,
					'qty'           => 1,
					'money_info_id' => $moneyInfo->id
				] );
			}

		}
	}

	public function calculateMoneyChange( Request $request ) {

		$dateAction = $request->input( 'date_action' );
		$hostels    = $request->input( 'hostels' );
		$rooms      = $request->input( 'rooms' );

		try {
			DB::beginTransaction();

			if ( empty( $hostels ) ) {
				$hostels = Hostel::all();
				foreach ( $hostels as $hostel ) {
					$rooms = Room::where( 'hostel_id', $hostel->id )->get();

					$this->calculateFee( $hostel->id, $rooms, $dateAction );
				}
			}

			if ( ! empty( $hostels ) ) {

				if ( ! empty( $rooms ) ) {
					$rooms = Room::whereIn( 'id', $rooms )->get();
				} else {
					$rooms = Room::whereIn( 'hostel_id', $hostels )->get();
				}

				if ( is_array( $hostels ) ) {
					foreach ( $hostels as $hostel ) {
						$this->calculateFee( $hostel, $rooms, $dateAction );
					}
				}
			}

			DB::commit();

			return response( [
				'status'  => 1,
				'message' => 'Success'
			] );
		} catch ( \Exception $ex ) {
			DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra vui lòng thử lại sau',
				'error'   => $ex->getMessage() . '|' . $ex->getTraceAsString()
			] );
		}
	}

	public function getMoneyChangeByAttribute( Request $request ) {
		$items = MoneyInfo::query();

		$dateAction = $request->input( 'date_action' );
		$hostelId   = $request->input( 'hostel_id' );
		$roomId     = $request->input( 'room_id' );

		if ( ! empty( $dateAction ) ) {
			$startDateAction = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->startOfMonth()->toDateString();
			$endDateAction   = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->endOfMonth()->toDateString();

		} else {
			$startDateAction = Carbon::now()->startOfMonth()->toDateString();
			$endDateAction   = Carbon::now()->endOfMonth()->toDateString();
		}

		$items = $items->whereBetween( 'date_action', [ $startDateAction, $endDateAction ] );

		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$hostels = Hostel::where( 'owner_id', auth( 'backend' )->user()->id )->pluck( 'id' )->toArray();
				$items   = $items->whereIn( 'hostel_id', $hostels );
			}
		}

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

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

		return Datatables::of( $items )
		                 ->addColumn( 'hostel', function ( $item ) {
			                 if ( $item->hostel ) {
				                 return $item->hostel->name;
			                 }
		                 } )
		                 ->addColumn( 'room', function ( $item ) {
			                 if ( $item->room ) {
				                 return $item->room->name;
			                 }
		                 } )
		                 ->editColumn( 'amount', function ( $item ) {
			                 return number_format( $item->amount, 0, '.', '.' );
		                 } )
		                 ->editColumn( 'pay', function ( $item ) {
			                 return number_format( $item->pay, 0, '.', '.' );
		                 } )
		                 ->editColumn( 'remain', function ( $item ) {
			                 return number_format( $item->remain, 0, '.', '.' );
		                 } )
		                 ->editColumn( 'date_action', function ( $item ) {
			                 return $item->date_action->format( 'd/m/Y' );
		                 } )
		                 ->editColumn( 'created_at', function ( $item ) {
			                 return $item->created_at->format( 'd/m/Y' );
		                 } )
		                 ->addColumn( 'action', function ( $item ) use ( $dateAction ) {
			                 return
				                 '<a href="#detail-money" data-id="' . $item->id . '" data-toggle="modal" class="btn btn-outline green btn-detail" >Chi tiết</a>' .
				                 '<a target="_blank" href="' . url( 'admin/money/print', [ 'id' => $item->id ] ) . '" class="btn btn-outline yellow-lemon" >In</a>' .
				                 '<a data-room-id="' . $item->room_id . '" href="#history-money" data-id="' . $item->id . '" data-toggle="modal" class="btn btn-outline blue btn-history" >Lịch sử</a>' .
				                 '<a  data-id="' . $item->id . '" data-date-action="' . $dateAction . '" href="#charge-money" data-toggle="modal" class="btn btn-outline red btn-charge" >Thu tiền</a>';

		                 } )->make( true );
	}

	public function getMoneyHistory( Request $request ) {
		$roomId = $request->input( 'room_id' );

		$room = Room::find( $roomId );

		if ( $room ) {

			$items = Transaction::where( 'room_id', $roomId )
			                    ->where( 'type', '<>', CollectSpend::SPEND )
			                    ->orderBy( 'id', 'desc' )
			                    ->get();

			$hostelName = $room->hostel->name;

			return response( [
				'title' => 'Lịch sử thu tiền phòng ' . $room->name . ' , nhà trọ ' . $hostelName,
				'html'  => view( 'admin.money.history_detail', compact( 'items' ) )->render()
			] );
		}

		return response( [
			'title' => '',
			'html'  => ''
		] );
	}

	public function getMoneyDetail( $id ) {
		$item       = MoneyInfo::find( $id );
		$details    = MoneyDetail::where( 'money_info_id', $id )->get();
		$room       = $item->room;
		$dateAction = $item->date_action->format( 'm/Y' );
		$pay        = Functions::calculateAmountMonthForRoom( $room, $dateAction )['pay'];

		return response( [
			'html' => view( 'admin.money.detail', compact( 'item', 'details', 'pay' ) )->render()
		] );
	}

	public function printBill( $id ) {
		$item       = MoneyInfo::find( $id );
		$details    = MoneyDetail::where( 'money_info_id', $id )->get();
		$room       = $item->room;
		$dateAction = $item->date_action->format( 'm/Y' );
		$pay        = $item->pay;

		locale_set_default( 'vi_VN' );

		$f = new \NumberFormatter( 'vi_VN', \NumberFormatter::SPELLOUT );

		$text    = null;
		$config  = Config::query()->where( 'owner_id', auth( 'backend' )->user()->id )->first();
		$ownerId = auth( 'backend' )->user()->id;
		if ( auth( 'backend' )->user()->type == User::STAFF ) {
			$config  = Config::query()->where( 'owner_id', auth( 'backend' )->user()->staff_owner_id )->first();
			$ownerId = auth( 'backend' )->user()->staff_owner_id;
		}

		if ( $config ) {
			$text = $config->voucher;
		}

		$configHostel = ConfigHostel::query()
		                            ->where( 'owner_id', $ownerId )
		                            ->where( 'hostel_id', $item->hostel_id )
		                            ->first();

		if ( $configHostel ) {
			$text = $configHostel->voucher;
		}

		if ( auth( 'backend' )->user()->id == 6875 || auth( 'backend' )->user()->staff_owner_id == 6875 ) {
			return view( 'admin2.money.bill_dung_eng', compact( 'item', 'details', 'pay', 'f', 'text' ) );
		}

		return view( 'admin.money.bill_v2', compact( 'item', 'details', 'pay', 'f', 'text' ) );
	}


	public function printAllBill( $id ) {
		$item = MoneyInfo::find( $id );

		$items = MoneyInfo::query()->whereBetween( 'date_action', [
			$item->date_action->startOfMonth()->startOfDay(),
			$item->date_action->endOfMonth()->endOfDay()
		] )
		                  ->where( 'contract_id', $item->contract_id )
		                  ->where( 'room_id', $item->room_id )
		                  ->get();
		//	dd($items);
		$ids     = $items->pluck( 'id' )->toArray();
		$details = MoneyDetail::whereIn( 'money_info_id', $ids )->get();
		//	dd($details);
		$room = $item->room;
		$pay  = MoneyInfo::query()->whereBetween( 'date_action', [
			$item->date_action->startOfMonth()->startOfDay(),
			$item->date_action->endOfMonth()->endOfDay()
		] )
		                 ->where( 'contract_id', $item->contract_id )
		                 ->where( 'room_id', $item->room_id )
		                 ->sum( 'pay' );

		$discount = MoneyInfo::query()->whereBetween( 'date_action', [
			$item->date_action->startOfMonth()->startOfDay(),
			$item->date_action->endOfMonth()->endOfDay()
		] )
		                     ->where( 'contract_id', $item->contract_id )
		                     ->where( 'room_id', $item->room_id )
//                             ->where('remain', '>', 0)
                             ->sum( 'discount' );
		locale_set_default( 'vi_VN' );

		$f = new \NumberFormatter( 'vi_VN', \NumberFormatter::SPELLOUT );

		$text    = null;
		$config  = Config::where( 'owner_id', auth( 'backend' )->user()->id )->first();
		$ownerId = auth( 'backend' )->user()->id;
		if ( auth( 'backend' )->user()->type == User::STAFF ) {
			$config  = Config::where( 'owner_id', auth( 'backend' )->user()->staff_owner_id )->first();
			$ownerId = auth( 'backend' )->user()->staff_owner_id;
		}
		if ( $config ) {
			$text = $config->voucher;
		}

		$configHostel = ConfigHostel::query()
		                            ->where( 'owner_id', $ownerId )
		                            ->where( 'hostel_id', $item->hostel_id )
		                            ->first();

		if ( $configHostel ) {
			$text = $configHostel->voucher;
		}


		if ( auth( 'backend' )->user()->id == 6875 || auth( 'backend' )->user()->staff_owner_id == 6875 ) {
			return view( 'admin2.money.bill_dung_eng', compact( 'item', 'details', 'pay', 'f', 'text' ) );
		}

		return view( 'admin.money.bill_v2', compact( 'item', 'details', 'pay', 'f', 'text', 'discount' ) );
	}

	public function printAllBillUnpaid( Request $request ) {
		$hostel_id   = $request->input( 'hostel_id' );
		$data_unpaid = MoneyInfo::where( 'hostel_id', $hostel_id )->get();
		foreach ( $data_unpaid as $data ) {
			$item = MoneyInfo::find( $data->id );

			$items   = MoneyInfo::query()->whereBetween( 'date_action', [
				$item->date_action->startOfMonth()->startOfDay(),
				$item->date_action->endOfMonth()->endOfDay()
			] )
			                    ->where( 'contract_id', $item->contract_id )
			                    ->where( 'room_id', $item->room_id )
			                    ->where( 'remain', '=', 0 )
			                    ->get();
			$ids     = $items->pluck( 'id' )->toArray();
			$details = MoneyDetail::whereIn( 'money_info_id', $ids )->get();
			//	dd($details);
			$room = $item->room;
			$pay  = MoneyInfo::query()->whereBetween( 'date_action', [
				$item->date_action->startOfMonth()->startOfDay(),
				$item->date_action->endOfMonth()->endOfDay()
			] )
			                 ->where( 'contract_id', $item->contract_id )
			                 ->where( 'room_id', $item->room_id )
			                 ->sum( 'pay' );

			$discount = MoneyInfo::query()->whereBetween( 'date_action', [
				$item->date_action->startOfMonth()->startOfDay(),
				$item->date_action->endOfMonth()->endOfDay()
			] )
			                     ->where( 'contract_id', $item->contract_id )
			                     ->where( 'room_id', $item->room_id )
//                             ->where('remain', '>', 0)
                                 ->sum( 'discount' );
			locale_set_default( 'vi_VN' );

			$f = new \NumberFormatter( 'vi_VN', \NumberFormatter::SPELLOUT );

			$text   = null;
			$config = Config::where( 'owner_id', auth( 'backend' )->user()->id )->first();
			$ownerId = auth( 'backend' )->user()->id;
			if ( auth( 'backend' )->user()->type == User::STAFF ) {
				$config = Config::where( 'owner_id', auth( 'backend' )->user()->staff_owner_id )->first();
				$ownerId = auth( 'backend' )->user()->staff_owner_id;
			}
			if ( $config ) {
				$text = $config->voucher;
			}

			$configHostel = ConfigHostel::query()
			                            ->where( 'owner_id', $ownerId )
			                            ->where( 'hostel_id', $item->hostel_id )
			                            ->first();

			if ( $configHostel ) {
				$text = $configHostel->voucher;
			}


		}


		if ( auth( 'backend' )->user()->id == 6875 || auth( 'backend' )->user()->staff_owner_id == 6875 ) {
			return view( 'admin2.money.bill_dung_eng', compact( 'item', 'details', 'pay', 'f', 'text' ) );
		}

		return view( 'admin.money.bill_v2', compact( 'item', 'details', 'pay', 'f', 'text', 'discount' ) );
	}

	public function getMoneyStat( Request $request ) {

		$dateAction = $request->input( 'date_action' );
		$hostelId   = $request->input( 'hostel_id' );
		$roomId     = $request->input( 'room_id' );

		if ( empty( $dateAction ) ) {
			$startDate = Carbon::now()->startOfMonth()->toDateString();
			$endDate   = Carbon::now()->endOfMonth()->toDateString();
		} else {
			$startDate = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->startOfMonth()->toDateString();
			$endDate   = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->endOfMonth()->toDateString();
		}

		$items  = MoneyInfo::where( 'date_action', '>=', $startDate )->where( 'date_action', '<=', $endDate );


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

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

		if ( auth( 'backend' )->check() ) {
			if ( auth( 'backend' )->user()->type == User::OWNER ) {
				$hostels = Hostel::query()->where( 'owner_id', auth( 'backend' )->user()->id )->pluck( 'id' )->toArray();
				$items   = $items->whereIn( 'hostel_id', $hostels );
			}
		}
		$items2 = clone $items;
		$items3 = clone $items;

		$amount = $items->sum( 'amount' );
		$pay    = $items2->sum( 'pay' );
		$discount = $items3->sum( 'discount' );

		return response( [
			'status' => 1,
			'data'   => [
				'amount' => number_format( $amount, 0, '.', '.' ),
				'pay'    => number_format( $pay, 0, '.', '.' ),
				'remain' => number_format( $amount - $pay - $discount, 0, '.', '.' )
			]
		] );
	}

	public function store( Request $request ) {
		$data = $request->all();

		if ( empty( $data['amount'] ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được để trống số tiền'
			] );
		}

		if ( ! empty( $data['date_action'] ) ) {
			try {

				$data['date_action'] = Carbon::createFromFormat( 'd/m/Y', $data['date_action'] )->toDateTimeString();

			} catch ( \Exception $ex ) {
				$data['date_action'] = Carbon::now()->toDateTimeString();

			}
		} else {
			$data['date_action'] = Carbon::now()->toDateTimeString();
		}

		CollectSpend::create( $data );

		if ( $data['type'] == CollectSpend::COLLECT ) {

		} else {

		}

		if ( $request->ajax() ) {
			return response( [
				'status'  => 1,
				'message' => 'Thành công'
			] );
		}

	}


	public function update( Request $request ) {
		$qtys    = $request->input( 'qty' );
		$ids     = $request->input( 'id' );
		$itemIds = $request->input( 'item_id' );
		$notes   = $request->input( 'note' );
		$types   = $request->input( 'type' );

		$sum    = 0;
		$infoId = '';
		DB::beginTransaction();
		try {
			foreach ( $ids as $key => $id ) {
				if ( $qtys[ $key ] < 0 ) {
					return response( [
						'status'  => 0,
						'message' => 'Số lượng không hợp lệ'
					] );
				}
				$item   = MoneyDetail::find( $id );
				$qty    = 1;
				$amount = 0;


				if ( $item ) {
					$infoId = $item->money_info_id;
					$note   = $notes[ $key ];
					if ( $itemIds[ $key ] > 0 ) {

						$itemId = $itemIds[ $key ];
						$ew     = ElectricWater::find( $itemId );

						if ( $types[ $key ] == 'electric' ) {
							$lastElectric = $qtys[ $key ];

							$currQty        = json_decode( $item->qty, true );
							$currQty['end'] = $lastElectric;
							$startElectric  = $currQty['start'];
							$amount         = ( $lastElectric - $startElectric ) * $item->hostel->electric_price;

							$ew->end_electric   = $lastElectric;
							$ew->delta_electric = $lastElectric - $ew->start_electric;

						} else if ( $types[ $key ] == 'water' ) {
							$lastWater      = $qtys[ $key ];
							$currQty        = json_decode( $item->qty, true );
							$currQty['end'] = $lastWater;

							$startWater = $currQty['start'];
							$amount     = ( $lastWater - $startWater ) * $item->hostel->water_price;

							$ew->end_water   = $lastWater;
							$ew->delta_water = $lastWater - $ew->start_water;
						}
						$qty = json_encode( $currQty );

						$ew->save();

					} else {
						$qty    = $qtys[ $key ];
						$amount = $item->value * $qty;
					}

					$item->qty    = $qty;
					$item->note   = $note;
					$item->amount = $amount;
					$item->save();

					DB::commit();

					$sum += $amount;
				}


			}
			$info         = MoneyInfo::find( $infoId );
			$info->amount = $sum;
			$info->remain = $sum - $info->pay;
			$info->save();

			$room = Room::find( $info->room_id );
			if ( $room ) {
				$room->debt = $sum - $info->pay;
				$room->save();
			}
		} catch ( Exception $ex ) {
			DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
			] );
		}


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

}
