<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Models\Category;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\Deposit;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\MoneyInfo;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\ReportBreak;
use App\Models\Room;
use App\Models\StatisticLog;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DashboardController extends BaseController {
	//
	/**
	 * @api {get} /dashboard-data Lấy thông tin thống kê dashboard
	 * @apiName dashboard-data
	 * @apiGroup Hostel
	 * @apiDescription Api Lấy thông tin thống kê dashboard
	 * @apiParam {String} hostel_id
	 * @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 getDashboard( Request $request ) {
		$hostelId = $request->input( 'hostel_id' );

		$startDate = Carbon::now()->startOfMonth()->toDateString();
		$endDate   = Carbon::now()->endOfMonth()->toDateString();


		if ( empty( $hostelId ) ) {
			$hostels    = Hostel::where( 'owner_id', $this->user->id )->get();
			$hostelArrs = $hostels->pluck( 'id' )->toArray();
//            $paids = MoneyInfo::where('remain', 0)->whereIn('hostel_id', $hostelArrs)->whereBetween('date_action', [$startDate, $endDate])->count();
//            $unpaids = MoneyInfo::where('remain', '>', 0)->whereIn('hostel_id', $hostelArrs)->whereBetween('date_action', [$startDate, $endDate])->count();
//
//            $paidAmount = MoneyInfo::where('remain', 0)->whereIn('hostel_id', $hostelArrs)->whereBetween('date_action', [$startDate, $endDate])->sum('amount');
//            $unpaidAmount = MoneyInfo::where('remain', '>', 0)->whereIn('hostel_id', $hostelArrs)->whereBetween('date_action', [$startDate, $endDate])->sum('amount');

			$numberRenters = RenterRoom::whereIn( 'hostel_id', $hostelArrs )->count();

			$numberContracts30 = Contract::whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 30 )->toDateString()
			                             ] )->count();
			$numberContracts60 = Contract::whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 60 )->toDateString()
			                             ] )->count();
			$numberContracts90 = Contract::whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 90 )->toDateString()
			                             ] )->count();

			$numberContracts = Contract::whereIn( 'hostel_id', $hostelArrs )->count();
			$numberRooms     = Room::whereIn( 'hostel_id', $hostelArrs )->count();

			$usedRooms  = RenterRoom::whereIn( 'hostel_id', $hostelArrs )->whereNotNull( 'user_id' )->groupBy( 'room_id' )->get()->count();
			$emptyRooms = $numberRooms - $usedRooms;

			$rentersNotDeclareResidence = RenterRoom::where( 'residence_status', RenterRoom::RESIDENCE_NOT_DECLARE )->whereIn( 'hostel_id', $hostelArrs )->count();

			$date                    = Carbon::now()->addDay( 30 )->toDateString();
			$rentersResidenceWarning = RenterRoom::where( 'residence_status', RenterRoom::RESIDENCE_LIMIT )
			                                     ->where( 'hostel_id', $hostelId )
			                                     ->where( 'date_end_residence', '<', $date )->count();

			$numberHostels = Hostel::where( 'owner_id', $this->user->id )->count();
			$chartRevenue  = Functions::getIncomeMonthByOwnerApi( $this->user->id );




		} else {
			$numberHostels = 1;
			$hostel        = Hostel::find( $hostelId );
			if ( ! $hostel ) {
				return response( [
					'status' => 0,
					'data'   => null
				] );
			}

//            $paids = MoneyInfo::where('remain', 0)->where('hostel_id', $hostelId)->whereBetween('date_action', [$startDate, $endDate])->count();
//            $unpaids = MoneyInfo::where('remain', '>', 0)->where('hostel_id', $hostelId)->whereBetween('date_action', [$startDate, $endDate])->count();
//
//            $paidAmount = MoneyInfo::where('remain', 0)->where('hostel_id', $hostelId)->whereBetween('date_action', [$startDate, $endDate])->sum('amount');
//            $unpaidAmount = MoneyInfo::where('remain', '>', 0)->where('hostel_id', $hostelId)->whereBetween('date_action', [$startDate, $endDate])->sum('amount');

			$numberRenters = RenterRoom::where( 'hostel_id', $hostelId )->count();

			$numberContracts30 = Contract::where( 'hostel_id', $hostelId )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 30 )->toDateString()
			                             ] )->count();
			$numberContracts60 = Contract::where( 'hostel_id', $hostelId )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 60 )->toDateString()
			                             ] )->count();
			$numberContracts90 = Contract::where( 'hostel_id', $hostelId )->where( 'status', '<>', Contract::LIQUIDATED )
			                             ->whereBetween( 'end_date', [
				                             Carbon::now()->toDateString(),
				                             Carbon::now()->addDay( 90 )->toDateString()
			                             ] )->count();
			$numberContracts   = Contract::where( 'hostel_id', $hostelId )->count();

			$numberRooms                = Room::where( 'hostel_id', $hostelId )->count();
			$usedRooms                  = RenterRoom::where( 'hostel_id', $hostelId )->whereNotNull( 'user_id' )->groupBy( 'room_id' )->get()->count();
			$emptyRooms                 = $numberRooms - $usedRooms;
			$rentersNotDeclareResidence = RenterRoom::where( 'residence_status', RenterRoom::RESIDENCE_NOT_DECLARE )->where( 'hostel_id', $hostelId )->count();
			$date                       = Carbon::now()->addDay( 30 )->toDateString();
			$rentersResidenceWarning    = RenterRoom::where( 'residence_status', RenterRoom::RESIDENCE_LIMIT )
			                                        ->where( 'hostel_id', $hostelId )
			                                        ->where( 'date_end_residence', '<', $date )->count();

			$chartRevenue = Functions::getIncomeMonthByHostel( $hostel );


		}

		$chartContract = [
			'number_contracts_30' => $numberContracts30,
			'number_contracts_60' => $numberContracts60,
			'number_contracts_90' => $numberContracts90,
			'number_contracts'    => $numberContracts,
		];

		$chartPayment = Functions::chartPayment( $hostelId, $this->user->id );

		return response( [
			'status' => 1,
			'data'   => [
				'number_hostel'                        => $numberHostels,
				'number_rooms'                         => $numberRooms,
				'empty_rooms'                          => $emptyRooms,
				'number_renters'                       => $numberRenters,
				'number_renters_not_declare_residence' => $rentersNotDeclareResidence,
				'number_renters_residence_warning'     => $rentersResidenceWarning,
				'chart_revenue'                        => $chartRevenue,
				'chart_payment'                        => $chartPayment,
				'chart_contract'                       => $chartContract
			]
		] );
	}


	public function getDashboardByHostel( Request $request ) {
		$hostelId  = $request->input( 'hostel_id' );
		$startDate = $request->input( 'start_date' );
		$endDate   = $request->input( 'end_date' );

		$hostel = Hostel::find( $hostelId );

		if ( ! $hostel ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}
		$total = Functions::getTotalRoomHostel( $hostel, $startDate, $endDate );
		$owe   = Functions::calculateOweHostel( $hostel, $startDate, $endDate );

		return response( [
			'status'  => 1,
			'message' => 'Thành công',
			'data'    => [
				'total_renter'     => $total['renters'],
				'total_room'       => $total['total_rooms'],
				'total_empty_room' => $total['total_rooms'] - $total['total_room_user'],
				'total_electric'   => $total['kwh'],
				'total_water'      => $total['waters'],
				'total_debt'       => $owe,
				'chart'            => Functions::getIncomeMonthByHostelApi( $hostel, $startDate, $endDate )
			]
		] );
	}

	/**
	 * @api {get} /stat-hostel Lấy thông tin thống kê về nhà trọ
	 * @apiName stat-hostel
	 * @apiGroup Dashboard
	 * @apiDescription Api Lấy thông tin thống kê về nhà trọ
	 * @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 getDashboardRoom( Request $request ) {
		$numberHostels = 0;
		$numberRooms   = 0;
		$numberRenters = 0;
		$numberReports = 0;
		$hostelArrs    = null;


		if ( $this->user->type == User::STAFF ) {
			$hostelArrs = Functions::getHostelArrStaffApi( $this->user );
		} else if ( $this->user->type == User::OWNER ) {
			$hostelArrs = Hostel::where( 'owner_id', $this->user->id )->pluck( 'id' )->toArray();
		}

		if ( ! empty( $hostelArrs ) ) {
			$numberHostels = count( $hostelArrs );
			$numberRooms   = Room::whereIn( 'hostel_id', $hostelArrs )->count();
			$numberRenters = RenterRoom::whereIn( 'hostel_id', $hostelArrs )->count();
			$numberReports = ReportBreak::whereIn( 'hostel_id', $hostelArrs )->count();
		}

		return response( [
			'status' => 1,
			'data'   => [
				'number_hostels' => $numberHostels,
				'number_rooms'   => $numberRooms,
				'number_renters' => $numberRenters,
				'number_reports' => $numberReports
			]
		] );
	}

	/**
	 * @api {get} /stat-payment Lấy thông tin thống kê về thanh toán
	 * @apiName stat-payment
	 * @apiGroup Dashboard
	 * @apiParam {String} date
	 * @apiParam {String} hostel_id
	 * @apiDescription Api Lấy thông tin thống kê về thanh toá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 getDashboardPayment( Request $request ) {
		$date     = $request->input( 'date' );
		$hostelId = $request->input( 'hostel_id' );

		try {
			$dateCarbon = Carbon::createFromFormat( 'm/Y', $date );
		} catch ( \Exception $exception ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$month = Carbon::createFromFormat( 'm/Y', $date )->month;
		$year  = Carbon::createFromFormat( 'm/Y', $date )->year;

		$paids   = MoneyInfo::where( 'remain', 0 );
		$unpaids = MoneyInfo::where( 'remain', '>', 0 );

		if ( ! empty( $month ) && ! empty( $year ) ) {
			$startDate = Carbon::createFromFormat( 'm/Y', $month . '/' . $year )->startOfMonth()->toDateString();
			$endDate   = Carbon::createFromFormat( 'm/Y', $month . '/' . $year )->endOfMonth()->toDateString();

			$paids   = $paids->whereBetween( 'date_action', [ $startDate, $endDate ] );
			$unpaids = $unpaids->whereBetween( 'date_action', [ $startDate, $endDate ] );
		}


		if ( ! empty( $hostelId ) ) {
			$paids   = $paids->where( 'hostel_id', $hostelId );
			$unpaids = $unpaids->where( 'hostel_id', $hostelId );
		} else {
			if ( $this->user->type == User::STAFF ) {
				$hostels = Functions::getHostelArrStaffApi( $this->user );
			} else {
				$hostels = Hostel::where( 'owner_id', $this->user->id )->pluck( 'id' )->toArray();
			}

			$paids   = $paids->whereIn( 'hostel_id', $hostels );
			$unpaids = $unpaids->whereIn( 'hostel_id', $hostels );
		}

		$paidCnt      = $paids->count();
		$unPaidCnt    = $unpaids->count();
		$paidAmount   = $paids->sum( 'amount' );
		$unpaidAmount = $unpaids->sum( 'amount' );

		return response( [
			'status' => 1,
			'data'   => [
				'sum'    => [
					'amount' => $paidAmount + $unpaidAmount,
					'cnt'    => $paidCnt + $unPaidCnt,
				],
				'paid'   => [
					'amount' => $paidAmount,
					'cnt'    => $paidCnt,
				],
				'unpaid' => [
					'amount' => $unpaidAmount,
					'cnt'    => $unPaidCnt,
				]
			]
		] );

	}

	/**
	 * @api {get} /stat-room Lấy thông tin thống kê về phòng
	 * @apiName stat-room
	 * @apiGroup Dashboard
	 * @apiParam {String} hostel_id
	 * @apiDescription Api Lấy thông tin thống kê về thanh toá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 getDashboardRoomStatus( Request $request ) {
		$hostelId = $request->input( 'hostel_id' );

		$ownerId   = $this->user->id;
		$dayRemind = $this->user->day_remind_empty_room;
		if ( $this->user->type == User::STAFF ) {
			$ownerId   = $this->user->staff_owner_id;
			$owner     = User::find( $ownerId );
			$dayRemind = $owner->day_remind_empty_room;
		}

		if ( empty( $hostelId ) ) {
			$hostelArrs = Hostel::where( 'owner_id', $ownerId )->pluck( 'id' )->toArray();

			if ( $this->user->type == User::STAFF ) {
				$hostelArrs = Functions::getHostelArrStaffApi( $this->user );
			}
		} else {
			$hostelArrs = Hostel::where( 'id', $hostelId )->pluck( 'id' )->toArray();
		}

		$numberRooms = Room::whereIn( 'hostel_id', $hostelArrs )->count();

		$usedRooms  = RenterRoom::whereIn( 'hostel_id', $hostelArrs )->whereNotNull( 'user_id' )->groupBy( 'room_id' )->get()->count();
		$emptyRooms = $numberRooms - $usedRooms;

		$numberRoomsNearEmpty = Room::where( 'date_available', '>=', Carbon::now()->subDay( $dayRemind ) )
		                            ->whereIn( 'hostel_id', $hostelArrs )->count();

		return response( [
			'status' => 1,
			'data'   => [
				'number_rooms'     => $numberRooms,
				'used_rooms'       => $usedRooms - $numberRoomsNearEmpty,
				'empty_rooms'      => $emptyRooms,
				'near_empty_rooms' => $numberRoomsNearEmpty
			]
		] );
	}

	/**
	 * @api {get} /stat-ew Lấy thông tin thống kê về điện nước
	 * @apiName stat-ew
	 * @apiGroup Dashboard
	 * @apiParam {String} date
	 * @apiParam {String} hostel_id
	 * @apiDescription Api Lấy thông tin thống kê về điện nước
	 * @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 getEwStat( Request $request ) {
		$hostelId  = $request->input( 'hostel_id' );
		$date      = $request->input( 'date' );
		$startDate = null;
		$endDate   = null;
		try {
			$dateCarbon = Carbon::createFromFormat( 'm/Y', $date );
		} catch ( \Exception $exception ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$startDate = Carbon::createFromFormat( 'm/Y', $date )->startOfDay()->startOfMonth()->toDateTimeString();
		$endDate   = Carbon::createFromFormat( 'm/Y', $date )->endOfDay()->endOfMonth()->toDateTimeString();

		$hostelArrs = null;
		$ownerId    = $this->user->id;
		if ( empty( $hostelId ) ) {
			$hostelArrs = Hostel::where( 'owner_id', $ownerId )->pluck( 'id' )->toArray();

			if ( $this->user->type == User::STAFF ) {
				$hostelArrs = Functions::getHostelArrStaffApi( $this->user );
			}
		} else {
			$hostelArrs = Hostel::where( 'id', $hostelId )->pluck( 'id' )->toArray();
		}

		$numberRooms      = Room::whereIn( 'hostel_id', $hostelArrs )->count();
		$numberRoomsEw    = ElectricWater::whereBetween( 'date_action', [
			$startDate,
			$endDate
		] )->groupBy( 'room_id' )->get()->count();
		$numberRoomsNotEw = $numberRooms - $numberRoomsEw;

		return response( [
			'status' => 1,
			'data'   => [
				'number_rooms'       => $numberRooms,
				'number_room_not_ew' => $numberRoomsNotEw,
				'number_room_ew'     => $numberRoomsEw
			]
		] );

	}

	/**
	 * @api {get} /stat-2 Lấy thông tin thống kê
	 * @apiName stat-2
	 * @apiGroup Dashboard
	 * @apiParam {String} start_date d/m/Y
	 * @apiParam {String} end_date d/m/Y
	 * @apiParam {String} hostel_id (Truong hop tat ca thi ko gui len)
	 * @apiDescription Api Lấy thông tin thống kê
	 * @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 getDashboard2( Request $request ) {
		$hostelId  = $request->input( 'hostel_id' );
		$startDate = $request->input( 'start_date' );
		$endDate   = $request->input( 'end_date' );

		$ownerId = $this->user->id;
		if ( $this->user->type == User::STAFF ) {
			$ownerId = $this->user->staff_owner_id;
		}
		$user = $this->user;
		if ( empty( $hostelId ) ) {
			$hostels = Hostel::query()
			                 ->where( 'owner_id', $ownerId )
			                 ->when( $this->user->type == User::STAFF, function ( $q ) use ( $user ) {
				                 $hostelArr = Functions::getHostelArrStaffApi( $user );
				                 $q->whereIn( 'id', $hostelArr );
			                 } )
			                 ->get();
		} else {
			$hostels = Hostel::query()
			                 ->where( 'id', $hostelId )
			                 ->get();
		}

		$owner     = User::find( $ownerId );
		$dayRemind = $owner->day_remind_empty_room;

		$hostelArrs = $hostels->pluck( 'id' )->toArray();

		if ( ! empty( $startDate ) ) {
			$startDate = Carbon::createFromFormat( 'd/m/Y', $startDate );
		}

		if ( ! empty( $endDate ) ) {
			$endDate = Carbon::createFromFormat( 'd/m/Y', $endDate );
		}

		$numberRoomsNearEmpty = Room::query()->whereIn( 'hostel_id', $hostelArrs );
		if ( empty( $startDate ) && empty( $endDate ) ) {
			$numberRoomsNearEmpty = Room::query()->where( 'date_available', '>=', Carbon::now()->subDay( $dayRemind ) )->whereIn( 'hostel_id', $hostelArrs );
		}
		if ( ! empty( $startDate ) ) {
			$numberRoomsNearEmpty = $numberRoomsNearEmpty->where( 'date_available', '>=', $startDate->copy()->toDateString() );
		}

		if ( ! empty( $endDate ) ) {
			$numberRoomsNearEmpty = $numberRoomsNearEmpty->where( 'date_available', '<=', $endDate->copy()->toDateString() );
		}

		$numberRoomsNearEmpty = $numberRoomsNearEmpty->count();

		$numberEmptyRooms = 0;


		foreach ( $hostels as $hostel ) {
//            $rooms = Room::where('hostel_id', $hostel->id)->get();
//            foreach ($rooms as $room) {
//                if(Functions::checkIsEmpty($room, $hostel->type_rent))
//                {
//                    $numberEmptyRooms++;
//                }
//            }

			if ( $hostel->type_rent == Hostel::TYPE_RENT_ALL ) {
				$numberRooms = Room::where( 'hostel_id', $hostel->id )->count();
				$usedRooms   = RenterRoom::where( 'hostel_id', $hostel->id )
				                         ->whereNotNull( 'user_id' )->groupBy( 'room_id' )
				                         ->get()
				                         ->count();

				$numberEmptyRooms += ( $numberRooms - $usedRooms );


			} else {
				$numberBeds = Room::where( 'hostel_id', $hostel->id )->sum( 'max_renters' );
				$usedBeds   = RenterRoom::where( 'hostel_id', $hostel->id )
				                        ->count();
				$remain     = $numberBeds - $usedBeds;
				if ( $remain < 0 ) {
					$remain = 0;
				}
				$numberEmptyRooms += $remain;

			}


		}


		$paids   = MoneyInfo::query()->where( 'pay', '>', 0 )->whereIn( 'hostel_id', $hostelArrs );
		$unpaids = MoneyInfo::where( 'remain', '>', 0 )->whereIn( 'hostel_id', $hostelArrs );

		$items    = CollectSpend::query();
		$statLogs = StatisticLog::query()->whereIn( 'hostel_id', $hostelArrs )
			->where( function ( $q ) {
				$q->orWhereNull( 'collect_spend_id' );
				$q->orWhere( function ( $q ) {
					$q->has( 'collectSpend' );
				} );
			} );
		$ew       = ElectricWater::query()
		                         ->has( 'room' )
		                         ->whereIn( 'hostel_id', $hostelArrs );
		if ( ! empty( $startDate ) ) {
			$items    = $items->where( 'date_action', '>=', $startDate->copy()->startOfDay()->toDateString() );
			$statLogs = $statLogs->where( 'statistic_logs.month', '>=', $startDate->copy()->month )
			                     ->where( 'statistic_logs.year', '>=', $startDate->copy()->year );
			$ew       = $ew->where( 'date_action', '>=', $startDate->copy()->startOfDay()->toDateTimeString() );
			$paids    = $paids->where( 'date_action', '>=', $startDate->copy()->startOfDay()->toDateTimeString() );
			$unpaids  = $unpaids->where( 'date_action', '>=', $startDate->copy()->startOfDay()->toDateTimeString() );
		}

		if ( ! empty( $endDate ) ) {
			$items    = $items->where( 'date_action', '<=', $endDate->copy()->endOfDay()->toDateString() );
			$statLogs = $statLogs->where( 'statistic_logs.month', '<=', $endDate->copy()->month )
			                     ->where( 'statistic_logs.year', '<=', $endDate->copy()->year );
			$ew       = $ew->where( 'date_action', '<=', $endDate->copy()->endOfDay()->toDateTimeString() );
			$paids    = $paids->where( 'date_action', '<=', $endDate->copy()->endOfDay()->toDateTimeString() );
			$unpaids  = $unpaids->where( 'date_action', '<=', $endDate->copy()->endOfDay()->toDateTimeString() );
		}


		$collect = clone $statLogs;
		$collect = $collect->where( 'type', CollectSpend::COLLECT );

		$spend = clone $statLogs;
		$spend = $spend->where( 'type', CollectSpend::SPEND );

		$deposit = clone $items;
		$deposit = $deposit->where( 'type', CollectSpend::COLLECT )
		                   ->whereIn( 'hostel_id', $hostelArrs )
		                   ->where( 'is_deposit', true );

		$returnDeposit = clone $items;
		$returnDeposit = $returnDeposit->where( 'type', CollectSpend::SPEND )
		                               ->whereIn( 'hostel_id', $hostelArrs )
		                               ->where( 'is_deposit', true )
		                               ->where( 'is_return_deposit', true );


		$paids   = $paids->sum( 'pay' );
		$unpaids = $unpaids->sum( 'remain' );

		$collect       = $collect->sum( 'amount' );
		$spend         = $spend->sum( 'amount' );
		$deposit       = $deposit->sum( 'amount' );
		$returnDeposit = $returnDeposit->sum( 'amount' );

		$reportBreaks = ReportBreak::query()->whereIn( 'hostel_id', $hostelArrs );

		if ( ! empty( $startDate ) ) {
			$reportBreaks = $reportBreaks->where( 'created_at', '>=', $startDate->copy()->startOfDay()->toDateTimeString() );
		}

		if ( ! empty( $endDate ) ) {
			$reportBreaks = $reportBreaks->where( 'created_at', '<=', $endDate->copy()->endOfDay()->toDateTimeString() );

		}

		//dd($reportBreaks->pluck('id')->toArray());

		$reportBreaksNew = clone $reportBreaks;
		$reportBreaksNew = $reportBreaksNew->where( 'status', ReportBreak::NOT_PROCESS )->count();

		$reportBreaksProcessing = clone $reportBreaks;
		$reportBreaksProcessing = $reportBreaksProcessing->where( 'status', ReportBreak::PROCESSING )->count();

		$reportBreaksProcessed = clone $reportBreaks;
		$reportBreaksProcessed = $reportBreaksProcessed->where( 'status', ReportBreak::PROCESSED )->count();

		$numberRenters = RenterRoom::query()->whereIn( 'hostel_id', $hostelArrs );

		if ( ! empty( $startDate ) ) {
			$numberRenters = $numberRenters->where( 'created_at', '>=', $startDate->copy()->startOfDay()->toDateTimeString() );
		}

		if ( ! empty( $endDate ) ) {
			$numberRenters = $numberRenters->where( 'created_at', '<=', $endDate->copy()->endOfDay()->toDateTimeString() );

		}

		$numberRenters = $numberRenters->count();

		$numberContracts30 = Contract::query()->whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
            ->where(function($q) {

                $q->orWhere(function($q) {
                    $q->whereNotNull('end_date')->whereBetween( 'end_date', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 30 )->toDateString()
                    ] );
                });

                $q->orWhere(function($q) {
                    $q->whereNotNull('leave_day')->whereBetween( 'leave_day', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 30 )->toDateString()
                    ] );
                });

            })
		                            ->count();
		$numberContracts60 = Contract::query()->whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
            ->where(function($q) {

                $q->orWhere(function($q) {
                    $q->whereNotNull('end_date')->whereBetween( 'end_date', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 60 )->toDateString()
                    ] );
                });

                $q->orWhere(function($q) {
                    $q->whereNotNull('leave_day')->whereBetween( 'leave_day', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 60 )->toDateString()
                    ] );
                });

            })->count();
		$numberContracts90 = Contract::query()->whereIn( 'hostel_id', $hostelArrs )->where( 'status', '<>', Contract::LIQUIDATED )
            ->where(function($q) {

                $q->orWhere(function($q) {
                    $q->whereNotNull('end_date')->whereBetween( 'end_date', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 90 )->toDateString()
                    ] );
                });

                $q->orWhere(function($q) {
                    $q->whereNotNull('leave_day')->whereBetween( 'leave_day', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay( 90 )->toDateString()
                    ] );
                });

            })->count();
		$numberContracts   = Contract::query()->whereIn( 'hostel_id', $hostelArrs )->count();

		$electrics = clone $ew;
		$waters    = clone $ew;

		$numberElectric = $electrics->sum( 'delta_electric' );
		$numberWater    = $waters->sum( 'delta_water' );

		$currentDeposit = Deposit::query()->whereIn( 'hostel_id', $hostelArrs )->has( 'room' )->sum( 'amount' );

		return response( [
			'status' => 1,
			'data'   => [
				'number_empty_rooms'      => $numberEmptyRooms,
				'number_near_empty_rooms' => $numberRoomsNearEmpty,
				'amount_paid'             => $paids,
				'amount_unpaid'           => $unpaids,
				'collect'                 => $collect,
				'spend'                   => $spend,
				'deposit'                 => $currentDeposit,
				'report_break_new'        => $reportBreaksNew,
				'report_break_processing' => $reportBreaksProcessing,
				'report_break_processed'  => $reportBreaksProcessed,
				'number_renters'          => $numberRenters,
				'number_electric'         => intval( $numberElectric ),
				'number_water'            => intval( $numberWater ),
				'chart_contract'          => [
					'number_contracts_30' => $numberContracts30,
					'number_contracts_60' => $numberContracts60,
					'number_contracts_90' => $numberContracts90,
					'number_contracts'    => $numberContracts,
				]
			]
		] );

	}


	/**
	 * @api {get} /filter-payment Lấy thông tin hoa don chua thanh toan - da thanh toan
	 * @apiName filter-payment
	 * @apiGroup Dashboard
	 * @apiParam {String} start_date d/m/Y
	 * @apiParam {String} end_date d/m/Y
	 * @apiParam {String} limit
	 * @apiParam {String} offset
	 * @apiParam {String} hostel_id (Truong hop tat ca thi ko gui len)
	 * @apiParam {String} type (paid la da tra, not-paid la chua tra, ko gui la tat ca)
	 * @apiDescription Api Lấy thông tin thống kê
	 * @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 getFilterPaymentHistory( Request $request ) {
		$type      = $request->input( 'type' );
		$hostelId  = $request->input( 'hostel_id' );
        $roomId    = $request->input( 'room_id' );
		$startDate = $request->input( 'start_date' );
		$endDate   = $request->input( 'end_date' );
		$limit     = $request->input( 'limit', 10 );
		$offset    = $request->input( 'offset', 0 );


		$items = MoneyInfo::query()
		                  ->with( 'room' )
		                  ->with( 'hostel' )
		                  ->with( 'contract' );


		if ( ! empty( $hostelId ) ) {
			$items = $items->where( 'hostel_id', $hostelId );
		} else {
			if ( $this->user->type == User::STAFF ) {
				$hostels = Functions::getHostelArrStaffApi( $this->user );
			} else {
				$hostels = Hostel::where( 'owner_id', $this->user->id )->pluck( 'id' )->toArray();
			}

			$items = $items->whereIn( 'hostel_id', $hostels );
		}

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

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

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

		if ( $type == 'paid' ) {
			$items = $items->where( 'remain', 0 );
		} else if ( $type = 'not-paid' ) {
			$items = $items->where( 'remain', '>', 0 );
		}
		$sumItems = clone $items;
		$sum      = $sumItems->sum( 'amount' );
		if ( $type == 'not-paid' ) {
			$sum = $sumItems->sum( 'remain' );
		}

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

		foreach ( $items as $item ) {
			if ( $item->room_id ) {
				if ( $item->hostel->type_rent == Hostel::TYPE_RENT_ALL ) {
					$contract = Contract::where( 'room_id', $item->room_id )->where( 'status', '<>', Contract::LIQUIDATED )->first();
				} else {
					$contract = $item->contract;
				}
				if ( $contract ) {
					$users   = RenterRoom::selectRaw( 'users.*' )
					                     ->join( 'users', 'users.id', '=', 'renter_rooms.user_id' )
					                     ->where( 'renter_rooms.contract_id', $contract->id )->get();
					$userArr = [];
					foreach ( $users as $user ) {
						$userArr[] = [
							'id'    => $user->id,
							'name'  => $user->name,
							'phone' => $user->phone,
							'email' => $user->email
						];
					}

					$item->users = $userArr;
				}


				$room = $item->room;
				if ( $room ) {
					$item->room_name = $room->name;
				} else {
					$item->room_name = '';
				}
			} else {
				$item->room_name = '';
			}

			if($item->hostel)
            {
                $item->hostel_name = $item->hostel->name;
            } else {
			    $item->hostel_name =null;
            }

			unset( $item->room );
			unset( $item->hostel );
		}

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