<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\AddRenterConversation;
use App\Jobs\AddStaffConversation;
use App\Jobs\CleanData;
use App\Jobs\RemoveStaffConversation;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\Package;
use App\Models\UserPackage;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
use Yajra\Datatables\Datatables;

class UserController extends AdminController {
	//
	public function getStaffByAttributeView() {
		$remainStaff = 0;
		$userPackage = UserPackage::where( 'user_id', auth( 'backend' )->user()->id )->first();
		if ( $userPackage ) {
			$packageId = $userPackage->package_id;

			if ( $packageId <= 2 ) {
				abort( 403 );
			}

			$numberStaff = $userPackage->number_staffs;
			$useStaff    = User::where( 'staff_owner_id', auth( 'backend' )->user()->id )->count();
			$remainStaff = $numberStaff - $useStaff;
			if ( $remainStaff < 0 ) {
				$remainStaff = 0;
			}

		}

		return view( 'admin2.user.staffs', compact( 'remainStaff' ) );
	}

	public function me( Request $request ) {
		return view( 'admin2.user.me' );
	}

	public function getStaffByAttribute() {
		$items = User::query()->where( 'type', User::STAFF )
		             ->where( 'staff_owner_id', auth( 'backend' )->user()->id );

		return Datatables::of( $items )
		                 ->addIndexColumn()
		                 ->editColumn( 'name', function ( $item ) {
			                 return $item->name_text;
		                 } )
		                 ->editColumn( 'image', function ( $item ) {
			                 return '<img src="' . $item->image . '" class="img-circle" style="width: 150px; height: 150px" />';
		                 } )
		                 ->addColumn( 'action', function ( $item ) {
			                 return
				                 '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-staff" class="btn btn-sm btn-outline btn-editable btn-edit-staff dark black">
								<i class="fa fa-edit"></i> Sửa</a>' .
				                 '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-staff-permission" class="btn btn-sm btn-outline btn-editable btn-edit-permission dark black">
								<i class="fa fa-user"></i> Phân quyền</a>' .
				                 '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-staff dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
		                 } )->make( true );
	}

	public function deleteStaff( Request $request ) {
		$id = $request->input( 'id' );

		$user = User::find( $id );

		if ( $user ) {
			$user->delete();
		}

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

	}

	public function editStaffPermission( $id, Request $request ) {
		$user = User::find( $id );

		return response( [
			'status' => 1,
			'data'   => view( 'admin2.user.permission_2', compact( 'user' ) )->render()
		] );
	}

	public function updateStaffPermission( Request $request ) {
		$hostels = $request->input( 'hostels' );

		if ( empty( $hostels ) ) {
			return response( [
				'status'  => 2,
				'message' => 'Bạn phải chọn ít nhất một nhà trọ'
			] );
		}


		$id          = $request->input( 'id' );
		$permissions = $request->input( 'permissions' );
		$user        = User::find( $id );

		$currentHostels = \DB::table( 'staff_hostels' )
		                     ->where( 'user_id', $id )
		                     ->pluck( 'hostel_id' )
		                     ->toArray();

		$deletedHostels = array_diff( $currentHostels, $hostels );
		$newHostels     = array_diff( $hostels, $currentHostels );

		if ( ! empty( $currentHostels ) ) {
			foreach ( $newHostels as $newHostel ) {
				dispatch( new AddStaffConversation( $id, $newHostel ) );
			}

			foreach ( $deletedHostels as $deletedHostel ) {
                dispatch( new RemoveStaffConversation( $id, $deletedHostel ) );
			}
		} else {
			foreach ( $hostels as $hostel ) {
                dispatch( new AddStaffConversation( $id, $hostel ) );
			}
		}

		$user->syncPermissions( $permissions );
		$user->staffHostel()->sync( $hostels );

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

	}

	public function updateStaff( Request $request ) {
		$data     = $request->all();
		$email    = $data['email'];
		$phone    = $data['phone'];
		$type     = $data['type'];
		$password = $request->input( 'password' );

		$user = User::find( $data['user_id'] );

		if ( $request->file( 'image' ) && $request->file( 'image' )->isValid() ) {
			$image         = Functions::uploadImage( $request->file( 'image' ) );
			$data['image'] = $image;
		}
		if ( empty( $type ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được bỏ trống loại người dùng'
			] );
		}
		if ( ! empty( $email ) ) {
			$check = User::query()->where( 'email', $email )->where( 'id', '<>', $user->id )->where( 'type', $user->type );
			if ( $check->count() > 0 ) {
				return response( [
					'status'  => 0,
					'message' => 'Email đã tồn tại'
				] );
			}
		}

		if ( ! empty( $phone ) ) {
			$checkPhone = User::query()->where( 'phone', $phone )
                ->where( 'id', '<>', $user->id )
                ->where( 'type', $user->type );
			if ( $checkPhone->count() > 0 ) {
				return response( [
					'status'  => 0,
					'message' => 'SĐT đã tồn tại'
				] );
			}

			$checkPhoneOwner = User::query()->where( 'phone', $phone )->where( 'type', User::OWNER )->first();
			if($checkPhoneOwner)
			{
				return response( [
					'status'  => 0,
					'message' => 'SĐT đã tồn tại vai trò chủ trọ'
				] );
			}
		}

		if ( isset( $data['province_id'] ) ) {
			$provinceId = $data['province_id'];
		}
		if ( isset( $data['district_id'] ) ) {
			$districtId = $data['district_id'];
		}

		if ( isset( $data['ward_id'] ) ) {
			$wardId = $data['ward_id'];
		}

		$provinceName = null;
		$districtName = null;
		$wardName     = null;

		if ( isset( $provinceId ) ) {
			$province = \DB::table( 'province' )->where( 'provinceid', $provinceId )->first();
			if ( $province ) {
				$provinceName = $province->name;
			}
		}

		if ( isset( $districtId ) ) {
			$district = \DB::table( 'district' )->where( 'districtid', $districtId )->first();
			if ( $district ) {
				$districtName = $district->name;
			}
		}

		if ( isset( $wardId ) ) {
			$ward = \DB::table( 'ward' )->where( 'wardid', $wardId )->first();
			if ( $ward ) {
				$wardName = $ward->name;
			}
		}

		$data['province_name'] = $provinceName;
		$data['district_name'] = $districtName;
		$data['ward_name']     = $wardName;

		if ( ! empty( $password ) ) {
			$data['password'] = \Hash::make( $password );
		}

		$user->update( $data );
		$user->code = \Vinkla\Hashids\Facades\Hashids::encode( '123456789' . $user->id );
		$user->save();

		if ( $request->ajax() ) {

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

		return redirect()->to( url( 'admin/login' ) )->with( 'success', 'Đăng ký thành công' );
	}

	public function editStaff( $id, Request $request ) {
		$user = User::find( $id );

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

		return response( [
			'status' => 1,
			'data'   => view( 'admin2.user.edit_staff', compact( 'user' ) )->render()
		] );
	}

	public function createStaff( Request $request ) {
		return response( [
			'status' => 1,
			'data'   => view( 'admin2.user.create_staff' )->render()
		] );
	}

	public function storeStaff( Request $request ) {
		$data  = $request->all();
		$email = $data['email'];
		$phone = $data['phone'];
		$type  = $data['type'];

		if ( empty( $type ) ) {
			return response( [
				'status'  => 0,
				'message' => 'Không được bỏ trống loại người dùng'
			] );
		}

		if ( ! empty( $email ) ) {
			$check = User::query()->where( 'email', $email )->where( 'type', $type );
			if ( $check->count() > 0 ) {
				return response( [
					'status'  => 0,
					'message' => 'Email đã tồn tại'
				] );

			}
		}


		$checkPhone = User::query()
            ->where( 'phone', $phone )
            ->where( 'type', $type );
		if ( $checkPhone->count() > 0 ) {

			return response( [
				'status'  => 0,
				'message' => 'SĐT đã tồn tại'
			] );

		}

		$data['password'] = \Hash::make( $data['password'] );

		$userOwnerId = null;
		if ( $type == User::STAFF ) {

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

			$data['staff_owner_id'] = $userOwnerId;
		}


		$user = User::create( $data );

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

	}
}
