<?php

namespace TPS\API\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Webkul\RestApi\Http\Resources\V1\Shop\Customer\CustomerResource;

class Customers extends \Webkul\RestApi\Http\Controllers\V1\Shop\Customer\AuthController
{
    /**
     * Register the customer.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'first_name' => 'required|string',
            'last_name'  => 'required|string',
            'phone'      => 'required|digits:8|unique:customers,phone',
            'password'   => 'required|min:6',
            'device_name'=> 'required'
//            'gender'     => 'in:Male,Female'
        ]);

        if ($validation->fails()) {

            return response()->json(['errors'=>$validation->getMessageBag()->all()],422);
        }

        $customer = $this->customerRepository->create([
            'first_name'        => $request->first_name,
            'last_name'         => $request->last_name,
            'phone'             => $request->phone,
            'password'          => bcrypt($request->password),
            'is_verified'       => 1,
            'channel_id'        => core()->getCurrentChannel()->id,
            'customer_group_id' => $this->customerGroupRepository->findOneWhere(['code' => 'general'])->id,
        ]);

        return response([
            'data'    => new CustomerResource($customer),
            'message' => 'Registered in successfully.',
            'token'   => $customer->createToken($request->device_name, ['role:customer'])->plainTextToken,
        ]);
    }

    /**
     * Login the customer.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'phone'       => 'required|digits:8',
            'password'    => 'required',
            'device_name' => 'required',
        ]);

        if ($validation->fails()) {

            return response()->json(['errors'=>$validation->getMessageBag()->all()],422);
        }

        $customer = $this->customerRepository->where('phone', $request->phone)->first();

        if (! $customer || ! Hash::check($request->password, $customer->password)) {
            return response()->json([
                'error' => 'The provided credentials are incorrect.',
            ], 401);
        }

        /**
         * Preventing multiple token creation.
         */
        $customer->tokens()->delete();

        return response([
            'data'    => new CustomerResource($customer),
            'message' => 'Logged in successfully.',
            'token'   => $customer->createToken($request->device_name, ['role:customer'])->plainTextToken,
        ]);
    }

    /**
     * Update the customer.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $customer = $request->user();

        $validation = Validator::make($request->all(), [
            'first_name'    => 'required',
            'last_name'     => 'required',
            'gender'        => 'in:Male,Female',
            'date_of_birth' => 'nullable|date|before:today',
            'email'         => 'email|unique:customers,email,' . $customer->id,
            'phone'         => 'digits:8|unique:customers,phone,' . $customer->id,
            'password'      => 'min:6',
        ]);

        if ($validation->fails()) {
            return response()->json(['errors'=>$validation->getMessageBag()->all()],422);
        }

        $data = $request->only('first_name', 'last_name', 'gender', 'date_of_birth', 'email', 'password','phone');

        if (! isset($data['password']) || ! $data['password']) {
            unset($data['password']);
        } else {
            $data['password'] = bcrypt($data['password']);
        }

        $updatedCustomer = $this->customerRepository->update($data, $customer->id);

        return response([
            'data'    => new CustomerResource($updatedCustomer),
            'message' => 'Your account has been updated successfully.',
        ]);
    }

    public function resetPassword(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'phone'       => 'required|digits:8',
        ]);

        if ($validation->fails()) {

            return response()->json(['errors'=>$validation->getMessageBag()->all()],422);
        }

        if($customer = $this->customerRepository
            ->where('phone', $request->phone)
            ->first()){

            $token = rand(1000,9999);

            $customer->token = $token;
            $customer->save();
            $request->merge(['token'=>$token]);

            Event::dispatch('shop.register.verify', $request);

            return response()->json(['success' => true]);
        }

    }

    public function updatePassword(Request $request){
        $validation = Validator::make($request->all(), [
            'phone'    => 'required|digits:8',
            'token'    => 'required',
            'password' => 'required|min:6'
        ]);

        if ($validation->fails()) {

            return response()->json(['errors'=>$validation->getMessageBag()->all()],422);
        }

        if($customer = $this->customerRepository
            ->where('phone', $request->phone)
            ->where('token', $request->token)
            ->first()){

            $customer->password = bcrypt($request->password);
            $customer->save();

            return response()->json(['success' => true]);
        }else{
            return response()->json(['success'=> false],422);
        }

    }

    public function destroy(Request $request){
        if($request->user()->delete()){
            return response()->json(['success'=>true]);
        }
        return response()->json(['success'=>false],400);
    }
}