<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Jobs\SendMessageBot;
use App\Jobs\SendVoucherOwner;
use App\Models\Config;
use App\Models\Coupon;
use App\Models\CouponTransaction;
use App\Models\Package;
use App\Models\UserPackage;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PartnerController extends BaseController {
	//
	/**
	 * @api {get} /events Lấy danh sách event
	 * @apiName /events
	 * @apiGroup Partner
	 * @apiParam {String} is_active gửi 0 nếu lấy tất cả, mặc định chỉ lấy các coupon còn hạn
	 *
	 * @apiDescription Api Lấy danh sách event
	 * @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 getCoupons( Request $request ) {
		$currentDate = Carbon::now()->toDateTimeString();

		if ( empty( $this->user->partner_refer ) ) {
			$items = Coupon::where( 'partner_id', $this->user->id );
		} else {
			$partnerRefer = $this->user->partner_refer;
			$items        = Coupon::where( 'partner_id', $partnerRefer );
		}


		$isActive = $request->input( 'is_active', 1 );

		if ( $isActive == 1 ) {
			$items = $items->where( 'from_date_expire', '<=', $currentDate )
			               ->where( 'end_date_expire', '>=', $currentDate );
		}

		$items = $items->get();
		foreach ( $items as $item ) {
			if ( ! empty( $item->package_ids ) ) {
				$cp = Package::find( $item->package_ids );
				if ( $cp ) {
					$item->value = $cp->price_per_month * $item->number_month_more;
				}
			} else {
				$item->value = $item->number_month_more;
			}
		}

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

	/**
	 * @api {get} /owner-partner Lấy danh sách partner là owner
	 * @apiName /owner-partner
	 * @apiGroup Partner
	 *
	 * @apiDescription Api Lấy danh sách partner là owner
	 * @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 getOwnerPartner( Request $request ) {
		$users = User::query()->where( 'is_partner_logo', true )
		             ->has( 'logoExist' )
		             ->with( 'logoExist' )
		             ->where( 'type', User::OWNER )
		             ->get()
		             ->map( function ( $item ) {
			             return [
				             'id'    => $item->id,
				             'phone' => $item->phone,
				             'logo'  => '/files/' . $item->logoExist->logo,
			             ];
		             } );

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

	//

	/**
	 * @api {post} /code Lấy mã khuyến mại
	 * @apiName /code
	 * @apiGroup Partner
	 *
	 *
	 * @apiParam {String} event_id
	 * @apiParam {String} email
	 * @apiParam {String} phone
	 * @apiParam {String} reference_code
	 * @apiParam {String} note
	 *
	 * @apiDescription Api Lấy mã khuyến mại
	 * @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 getCode( Request $request ) {
		$couponId      = $request->input( 'event_id' );
		$email         = $request->input( 'email' );
		$phone         = $request->input( 'phone' );
		$note          = $request->input( 'note' );
		$referenceCode = $request->input( 'reference_code' );

		$coupon = Coupon::find( $couponId );

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

		$checkOwner = User::where( 'phone', $phone )
		                  ->where( 'type', User::OWNER )
		                  ->first();

		//xu ly

		$name           = null;
		$ownerId        = null;
		$ownerNamePhone = null;
		if ( $checkOwner ) {
			$name           = $checkOwner->name_text;
			$ownerId        = $checkOwner->id;
			$ownerNamePhone = $checkOwner->name_text . ' - ' . $checkOwner->phone;

			$checkTransaction = CouponTransaction::where( 'owner_id', $ownerId )
			                                     ->where( 'coupon_id', $couponId )
			                                     ->count();

			if ( $checkTransaction > 0 ) {
				return response( [
					'status'  => 0,
					'message' => 'Chủ trọ đã được cấp mã khuyến mại trước đó'
				] );
			}
		} else {
			$checkTransaction = CouponTransaction::where( 'coupon_id', $couponId )
			                                     ->where( 'phone', $phone )
			                                     ->count();

			if ( $checkTransaction > 0 ) {
				return response( [
					'status'  => 0,
					'message' => 'Chủ trọ đã được cấp mã khuyến mại trước đó'
				] );
			}
		}

		try {
			\DB::beginTransaction();

			$codeItem = \DB::table( 'coupon_generates' )
			               ->where( 'coupon_id', $couponId )
			               ->where( 'is_given', 0 )
			               ->where( 'status', Coupon::COUPON_GENERATE_NOT_USED )
			               ->first();

			if ( ! $codeItem ) {
				return response( [
					'status'  => 0,
					'message' => 'Đã hết mã khuyến mại'
				] );
			}

			$code       = $codeItem->code;
			$codeItemId = $codeItem->id;

			\DB::table( 'coupon_generates' )->where( 'id', $codeItemId )
			   ->update( [
				   'is_given' => 1
			   ] );

			CouponTransaction::create( [
				'code'           => $code,
				'name'           => $name,
				'phone'          => $phone,
				'email'          => $email,
				'note'           => $note,
				'reference_code' => $referenceCode,
				'owner_name'     => $name,
				'owner_id'       => $ownerId,
				'partner_id'     => $this->user->id,
				'coupon_id'      => $coupon->id
			] );


			if ( ! empty( $ownerId ) ) {
				\DB::table( 'coupon_generates' )
				   ->where( 'id', $codeItemId )
				   ->update( [
					   'given_to'         => $ownerId,
					   'owner_name_phone' => $ownerNamePhone
				   ] );

				\DB::table( 'partner_owners' )->insert( [
					'owner_id'   => $ownerId,
					'partner_id' => $this->user->id
				] );
			} else {
				\DB::table( 'coupon_generates' )
				   ->where( 'id', $codeItemId )
				   ->update( [
					   'given_to_phone'   => $phone,
					   'owner_name_phone' => $phone
				   ] );
			}

			//Gui thong bao
			if ( $checkOwner ) {
				$email = $checkOwner->email;

				$packageId  = $coupon->package_ids;
				$packageNew = Package::find( $packageId );
				if ( $packageNew ) {
					$packageName = $packageNew->name;
				}
				if ( ! empty( $coupon->end_date_expire ) ) {
					$endTime = $coupon->end_date_expire->format( 'd/m/Y' );
				}

				$message = view( 'admin.partner.message', compact( 'packageName', 'endTime', 'packageNew', 'coupon', 'code' ) )->render();

				dispatch( new SendVoucherOwner( $code, $email, $coupon ) );
				dispatch( new SendMessageBot( $message, $checkOwner->id ) );

			} else {
				if ( empty( $email ) ) {
					return response( [
						'status'  => 0,
						'message' => 'SĐT chưa tồn tại trên hệ thống, vui lòng điền địa chỉ email của chủ trọ'
					] );
				}

				dispatch( new SendVoucherOwner( $code, $email, $coupon ) );
			}

			\DB::commit();

		} catch ( \Exception $exception ) {
			\DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra'
			] );
		}

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

	/**
	 * @api {get} /history Lấy lịch sử
	 * @apiName /history
	 * @apiGroup Partner
	 *
	 * * @apiParam {String} coupon_id
	 * @apiParam {String} start_date dạng d/m/Y
	 * @apiParam {String} end_date
	 * @apiParam {String} limit
	 * @apiParam {String} offset
	 *
	 * @apiDescription Api Lấy lịch sử
	 * @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 getHistory( Request $request ) {
		$couponId  = $request->input( 'coupon_id' );
		$startDate = $request->input( 'start_date' );
		$endDate   = $request->input( 'end_date' );
		$userId    = $this->user->id;
		$limit     = $request->input( 'limit', 10 );
		$offset    = $request->input( 'offset', 0 );

		$items = CouponTransaction::orderBy( 'id', 'desc' )->limit( $limit )->offset( $offset );

		if ( empty( $this->user->partner_refer ) ) {
			$partnerRefers   = User::where( 'partner_refer', $userId )->pluck( 'id' )->toArray();
			$partnerRefers[] = $userId;
			$items           = $items->whereIn( 'partner_id', $partnerRefers );
		} else {
			$items = $items->where( 'partner_id', $userId );
		}

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

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

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

		$itemsStat        = clone $items;
		$createdVoucher   = $itemsStat->count();
		$activeVoucher    = $itemsStat->where( 'status', Coupon::COUPON_GENERATE_USED )->count();
		$notActiveVoucher = $createdVoucher - $activeVoucher;

		$items = $items->get();
		foreach ( $items as $item ) {
			$item->owner = [
				'id' => null,
			];

			if ( ! empty( $item->owner_id ) ) {
				$owner = User::find( $item->owner_id );
				if ( $owner ) {
					$item->owner = [
						'id'    => $owner->id,
						'name'  => $owner->name_text,
						'phone' => $owner->phone,
						'email' => $owner->email,
					];
				}
			}

			$usedBy = \DB::table( 'coupon_generates' )
			             ->where( 'coupon_id', $couponId )
			             ->where( 'code', $item->code )
			             ->first();

			$item->used_by = [
				'id' => null
			];

			if ( $usedBy ) {
				$usedById   = $usedBy->used_by;
				$usedByUser = User::find( $usedById );
				if ( $usedByUser ) {
					$item->used_by = [
						'id'    => $usedByUser->id,
						'name'  => $usedByUser->name_text,
						'phone' => $usedByUser->phone,
						'email' => $usedByUser->email,
					];
				}
			}

			$item->partner = [
				'id' => null,
			];

			if ( ! empty( $item->partner_id ) ) {
				$partner = User::find( $item->partner_id );

				if ( $partner ) {
					$item->partner = [
						'id'    => $partner->id,
						'name'  => $partner->name_text,
						'phone' => $partner->phone,
						'email' => $partner->email,
					];
				}
			}
		}


		return response( [
			'status' => 1,
			'data'   => [
				'items'     => $items,
				'sum'       => $createdVoucher,
				'active'    => $activeVoucher,
				'in_active' => $notActiveVoucher
			]
		] );

	}

	/**
	 * @api {get} /contact Lấy contact
	 * @apiName /contact
	 * @apiGroup Partner
	 *
	 * * @apiParam {String} limit
	 * @apiParam {String} offset
	 *
	 * @apiDescription Api Lấy contact
	 * @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 getContacts( Request $request ) {

		$limit  = $request->input( 'limit', 10 );
		$offset = $request->input( 'offset', 0 );

		$users = User::select( \DB::raw( 'users.id, users.phone, CONCAT(users.first_name, " ", users.last_name) AS name, users.email, users.image, users.type' ) )
		             ->join( 'partner_owners', 'users.id', '=', 'partner_owners.owner_id' )->groupBy( 'partner_owners.owner_id' );

		$userId = $this->user->id;
		if ( empty( $this->user->partner_refer ) ) {
			$partnerRefers   = User::where( 'partner_refer', $userId )->pluck( 'id' )->toArray();
			$partnerRefers[] = $userId;
			$items           = $users->whereIn( 'partner_owners.partner_id', $partnerRefers );
		} else {
			$items = $users->where( 'partner_owners.partner_id', $userId );
		}

		$items        = $items->limit( $limit )->offset( $offset )->get();
		$retValRenter = [];
		$retValStaff  = [];
		foreach ( $items as $item ) {
			$retValRenter[] = [
				'id'     => $item->id,
				'name'   => $item->name_text,
				'image'  => $item->image,
				'phone'  => $item->phone,
				'room'   => null,
				'hostel' => null,
				'type'   => $item->type,

			];
		}

		return response( [
			'status' => 1,
			'data'   => [
				'employee' => $retValStaff,
				'renter'   => $retValRenter
			]
		] );
	}

	/**
	 * @api {post} /redeem Dùng mã coupon
	 * @apiName /redeem
	 * @apiGroup Partner
	 *
	 * * @apiParam {String} code
	 *
	 * @apiDescription Api Dùng mã coupon
	 * @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 redeem( Request $request ) {
		$coupon = $request->input( 'code' );

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

		$check = \DB::table( 'coupon_generates' )->where( 'code', $coupon )->first();

		if ( ! $check ) {
			return response( [
				'status'  => 0,
				'message' => 'Coupon không tồn tại'
			] );
		}

		if ( $check->is_active == 0 ) {
			return response( [
				'status'  => 0,
				'message' => 'Coupon chưa được kích hoạt'
			] );
		}

//		if ( $check->status == Coupon::COUPON_GENERATE_USED ) {
//			return redirect()->back()->with( 'error', 'Mã coupon đã được sử dụng' );
//		}

		$couponId   = $check->coupon_id;
		$couponItem = Coupon::find( $couponId );
		if ( ! $couponItem ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		if ( ! empty( $couponItem->from_date_expire ) ) {
			if ( $couponItem->from_date_expire->greaterThan( Carbon::now() ) ) {
				return response( [
					'status'  => 0,
					'message' => 'Coupon chưa thể sử dụng'
				] );
			}
		}

		if ( ! empty( $couponItem->end_date_expire ) ) {
			if ( $couponItem->end_date_expire->lessThan( Carbon::now() ) ) {
				return response( [
					'status'  => 0,
					'message' => 'Coupon đã quá hạn sử dụng'
				] );
			}
		}


		$numberUse = $couponItem->number_use;

		$numberUseBefore = \DB::table( 'log_coupons' )
		                      ->where( 'code', $coupon )
		                      ->count();

		$numberUserInCoupon = \DB::table( 'log_coupons' )
		                         ->where( 'coupon_id', $couponItem->id )
		                         ->count();

		if ( $numberUserInCoupon > 1 ) {
			return [
				'status'  => 0,
				'message' => 'Bạn đã tham gia chương trình này trước đó'
			];
		}

		if ( $numberUseBefore >= $numberUse ) {
			return response( [
				'status'  => 0,
				'message' => 'Coupon đã được sử dụng trước đó'
			] );

		}


		$packageId      = $couponItem->package_ids;
		$packageApply   = $couponItem->package_apply;
		$currentPackage = UserPackage::where( 'user_id', $this->user->id )->first();
		if ( ! empty( $packageApply ) ) {

			if ( $currentPackage ) {
				$currentPackageId = $currentPackage->package_id;
				$packageApplyArr  = json_decode( $packageApply, true );

				if ( ! in_array( - 1, $packageApplyArr ) ) {
					if ( ! in_array( $currentPackageId, $packageApplyArr ) ) {
						return response( [
							'status'  => 0,
							'message' => 'Coupon không áp dụng cho gói cước hiện tại của bạn'
						] );

					}
				}
			}
		}

		$packageName = null;
		$endTime     = null;
		try {

			\DB::beginTransaction();

			if ( $currentPackage ) {
				if ( ! empty( $packageId ) ) {

					if ( $currentPackage->package_id < $packageId ) {

						$currentPackage->package_id = $packageId;
					}
				}

				$currentPackage->end_date = $currentPackage->end_date->addMonth( $couponItem->number_month_more );
				$currentPackage->save();

			}

			\DB::table( 'log_coupons' )->insert( [
				'user_id'            => $this->user->id,
				'coupon_id'          => $couponItem->id,
				'coupon_generate_id' => $check->id,
				'code'               => $coupon,
				'created_at'         => Carbon::now()->toDateTimeString(),
				'updated_at'         => Carbon::now()->toDateTimeString(),
			] );

			\DB::table( 'coupon_generates' )->where( 'code', $coupon )
			   ->update( [
				   'status'             => Coupon::COUPON_GENERATE_USED,
				   'used_by'            => $this->user->id,
				   'used_by_name_phone' => $this->user->name_text . ' - ' . $this->user->phone
			   ] );

			\DB::table( 'coupon_transactions' )->where( 'code', $coupon )
			   ->where( 'coupon_id', $couponId )
			   ->update( [
				   'status' => Coupon::COUPON_GENERATE_USED,

			   ] );

			\DB::commit();

		} catch ( \Exception $exception ) {
			\DB::rollBack();

			return response( [
				'status'  => 0,
				'message' => 'Có lỗi xảy ra'
			] );
		}

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

}
