<?php

namespace App\Http\Controllers\Backend;

use App\Components\Functions;
use App\Models\District;
use App\Models\Hostel;
use App\Models\SearchLog;
use App\Models_v2\FindSession;
use App\Notifications\SearchHostel;
use App\Notifications\SearchHostelManageApp;
use App\Notifications\SearchHostelRenter;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;

class RequestFindController extends BaseController {
	//
	public function edit( Request $request ) {
		$id   = $request->input( 'id' );
		$item = FindSession::find( $id );

		return response( [
			'status' => 1,
			'data'   => view( 'admin.request_find.edit', compact( 'item' ) )->render()
		] );
	}

	public function getRequestByAttribute( Request $request ) {
		$userId = $request->input( 'user_id' );
		$items  = FindSession::query()->with( [
			'user'
		] )->has( 'user' )->withCount( 'conversations' )
		                     ->with( 'conversations' )
		                     ->when( ! empty( $userId ), function ( $q ) use ( $userId ) {
			                     $q->where( 'user_id', $userId );
		                     } )->when( ! $request->has( 'order' ), function ( $q ) {
				$q->orderBy( 'id', 'desc' );
			} );

		return \DataTables::of( $items )
		                  ->addColumn( 'province', function ( $item ) {
			                  return optional( Functions::getProvinceName( $item->properties['province_id'] ) )->name;
		                  } )
		                  ->filterColumn( 'name', function ( $query, $keyword ) {
			                  $query->whereHas( 'user', function ( $q ) use ( $keyword ) {
				                  $q->where( 'name', 'LIKE', '%' . $keyword . '%' );
			                  } );

		                  } )
		                  ->filterColumn( 'conversations_count', function ( $query, $keyword ) {

			                  if ( $keyword == 'not-have' ) {
				                  $query->has( 'conversations', '=', 0 );
			                  } else if ( $keyword == 'have' ) {

				                  $query->has( 'conversations', '>', 0 );
			                  }

		                  } )
		                  ->filterColumn( 'phone', function ( $query, $keyword ) {
			                  $query->whereHas( 'user', function ( $q ) use ( $keyword ) {
				                  $q->where( 'phone', 'LIKE', '%' . $keyword . '%' );
			                  } );

		                  } )
		                  ->filterColumn( 'province', function ( $query, $keyword ) {
			                  $query->whereJsonContains( 'properties', [
				                  'province_id' => $keyword
			                  ] );
		                  } )
		                  ->filterColumn( 'district', function ( $query, $keyword ) {
			                  $query->whereHas( 'districts', function ( $q ) use ( $keyword ) {
				                  $q->where( 'name', 'LIKE', '%' . $keyword . '%' );
			                  } );
		                  } )
		                  ->addColumn( 'district', function ( $item ) {
			                  if ( $item->districts ) {
				                  return $item->districts->pluck( 'name' )->toArray();
			                  }
		                  } )
		                  ->addColumn( 'name', function ( $item ) {
			                  return optional( $item->user )->name_text;
		                  } )
		                  ->editColumn( 'created_at', function ( $item ) {
			                  return $item->created_at->format( 'd/m/Y H:i' );
		                  } )
		                  ->addColumn( 'phone', function ( $item ) {
			                  return optional( $item->user )->phone;
		                  } )
		                  ->addColumn( 'min_price', function ( $item ) {
			                  return is_numeric( $item->properties['min_price'] ) ? number_format( $item->properties['min_price'], 0, '.', '.' ) : null;
		                  } )
		                  ->addColumn( 'max_price', function ( $item ) {
			                  return is_numeric( $item->properties['max_price'] ) ? number_format( $item->properties['max_price'], 0, '.', '.' ) : null;
		                  } )
		                  ->addColumn( 'type', function ( $item ) {
			                  return optional( $item->hostelType )->name;
		                  } )
		                  ->editColumn( 'status', function ( $item ) {
			                  if ( $item->status == FindSession::CANCEL ) {
				                  return '<label class="label label-danger">Đã hủy</label>';
			                  }
			                  if ( $item->status == FindSession::SEARCHING ) {
				                  return '<label class="label label-info">Đang tìm kiếm</label>';
			                  }
			                  if ( $item->status == FindSession::FOUND ) {
				                  return '<label class="label label-success">Đã tìm thấy</label>';
			                  }
			                  if ( $item->status == FindSession::NOT_FOUND ) {
				                  return '<label class="label label-warning">Không thấy</label>';
			                  }
		                  } )
		                  ->addColumn( 'action', function ( $item ) {
			                  $retVal = '<a data-id="' . $item->id . '" href="#edit" data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit purple"><i class="fa fa-edit"></i> Sửa</a>'
			                            . '<a data-id="' . $item->id . '"  class="btn btn-sm btn-outline btn-editable btn-delete dark black"><i class="fa fa-trash"></i> Xóa</a>';

			                  return $retVal;
		                  } )
		                  ->rawColumns( [
			                  'status',
			                  'type'
		                  ] )
		                  ->make( true );

	}

	public function update( Request $request ) {

		$provinceId = $request->input( 'province_id' );
		$districtId = $request->input( 'district_id' );
		$wardId     = $request->input( 'ward_id' );
		$minPrice   = Functions::filterInputNumber( $request->input( 'min_price' ) );
		$maxPrice   = Functions::filterInputNumber( $request->input( 'max_price' ) );
		$type       = $request->input( 'type' );
		$typeRent   = $request->input( 'type_rent' );
		$id         = $request->input( 'id' );
		$note       = $request->input( 'note' );
		$properties = $request->all();

		if ( ! $request->has( 'type_rent' ) ) {
			$typeRent                = $type;
			$properties['type_rent'] = $type;
			$properties['type']      = null; // mặc định xếp vào là nhà trọ
			$type                    = null; // mặc định xếp vào là nhà trọ

		}

		$properties['min_price'] = $minPrice;
		$properties['max_price'] = $maxPrice;

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

		if ( in_array( $findSession->status, [ FindSession::CANCEL, FindSession::FOUND ] ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Phiên tìm kiếm đã hủy hoặc đã tìm thấy'
			] );
		}

		if ( empty( $provinceId ) || empty( $districtId ) || empty( $minPrice ) || empty( $maxPrice ) || ( $type == - 1 ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}


		if ( $maxPrice < $minPrice ) {
			return response( [
				'status'  => 0,
				'message' => 'Max ko được nhỏ hơn min'
			] );
		}

		$hostels = Hostel::query()
		                 ->when( ! empty( $provinceId ), function ( $q ) use ( $provinceId ) {
			                 $q->where( 'province_id', $provinceId );
		                 } )
		                 ->when( ! empty( $districtId ), function ( $q ) use ( $districtId ) {
			                 $q->whereIn( 'district_id', $districtId );
		                 } )
		                 ->when( ! empty( $wardId ), function ( $q ) use ( $wardId ) {
			                 $q->where( 'ward_id', $wardId );
		                 } )
//		                  ->when( ! empty( $minPrice ), function ( $q ) use ( $minPrice ) {
//			                  $q->where( 'smallest_price', '>=', $minPrice );
//		                  } )
//		                  ->when( ! empty( $maxPrice ), function ( $q ) use ( $maxPrice ) {
//			                  $q->where( 'greatest_price', '<=', $maxPrice );
//		                  } )
                         ->when( ! is_null( $typeRent ), function ( $q ) use ( $typeRent ) {
				$q->where( 'type_rent', $typeRent );
			} )
		                 ->when( ! is_null( $type ), function ( $q ) use ( $type ) {
			                 $q->where( 'type', $type );
		                 } )
		                 ->get();

		$ownerIds = $hostels->pluck( 'owner_id' )
		                    ->toArray();

		$owners = User::query()
		              ->whereIn( 'id', $ownerIds )
		              ->get();


		$logSent   = SearchLog::query()
		                      ->where( 'find_session_id', $findSession->id )
		                      ->get();
		$ownerSent = [];
		foreach ( $logSent as $log ) {
			$ownerSent = array_merge( $ownerSent, $log->owner_ids );
		}

		$findSession->update( [
			'properties' => $properties,
			'note'       => $note
		] );

		SearchLog::create( [
			'find_session_id' => $findSession->id,
			'properties'      => $properties,
			'owner_ids'       => $owners->pluck( 'id' )->toArray()
		] );

		if ( ! empty( $ownerSent ) ) {
			$ownerToSend = User::query()
			                   ->whereNotIn( 'id', $ownerSent )
			                   ->whereIn( 'id', $ownerIds )
			                   ->get();
		} else {
			$ownerToSend = $owners;
		}

		$districtsName = null;
		$addressName   = null;
		if ( is_array( $districtId ) ) {
			$districts     = District::query()
			                         ->whereIn( 'districtid', $districtId )
			                         ->pluck( 'name' )
			                         ->toArray();
			$districtsName = implode( ', ', $districts );
		}

		$addressName = $districtsName . ' ' . Functions::getProvinceName( $provinceId )->name;

		// bắn cho chủ trọ

		\Notification::send( $ownerToSend, new SearchHostel(
			$findSession->user,
			$districtsName,
			$findSession->id,
			$provinceId,
			$districtId
		) );


		\Notification::send( $ownerToSend, new SearchHostelManageApp(
			$findSession->user,
			$districtsName,
			$findSession->id,
			$provinceId,
			$districtId
		) );

		//bắn cho nhân viên của từng nhà trọ
		foreach ( $hostels as $hostel ) {
			$staffs = $hostel->staffs;
			if ( ! empty( $staffs ) ) {
				\Notification::send( $staffs, new SearchHostel(
					$findSession->user,
					$districtsName,
					$findSession->id,
					$provinceId,
					$districtId
				) );

				\Notification::send( $staffs, new SearchHostelManageApp(
					$findSession->user,
					$districtsName,
					$findSession->id,
					$provinceId,
					$districtId
				) );
			}
		}


		\Notification::send( $findSession->user, new SearchHostelRenter(
			$findSession,
			$addressName
		) );

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

	public function destroy( Request $request ) {
		$id   = $request->input( 'id' );
		$item = FindSession::find( $id );
		if ( $item ) {
			$item->delete();
		}

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