<?php

namespace TPS\Shop\Http\Controllers;

use Illuminate\Support\Facades\Event;
use TPS\Shop\Http\Requests\CustomerLoginRequest;
use Webkul\Shop\Http\Controllers\Controller;

class Session extends Controller
{
    public function create(CustomerLoginRequest $request){
        $request->validated();

        if (! auth()->guard('customer')->attempt($request->only(['phone', 'password']))) {

            return response([
                'message' => trans('auth.failed'),
                'errors'=>[
                    'login'=>[
                        trans('shop::app.customer.login-form.invalid-creds')
                    ]
                ]
            ],422);
        }

        if (auth()->guard('customer')->user()->status == 0) {
            auth()->guard('customer')->logout();


            return response([
                'message' => trans('auth.failed'),
                'errors'=>[
                    'login'=>[
                        trans('shop::app.customer.login-form.not-activated')
                    ]
                ]
            ],422);
        }

        //todo phone virification if needed open here
//        if (auth()->guard('customer')->user()->is_verified == 0) {
//
//            Cookie::queue(Cookie::make('enable-resend', 'true', 1));
//
//            Cookie::queue(Cookie::make('email-for-resend', $request->get('email'), 1));
//
//            auth()->guard('customer')->logout();
//
//            return response([
//                'message' => trans('auth.failed'),
//                'errors'=>[
//                    'login'=>[
//                        trans('shop::app.customer.login-form.verify-first')
//                    ]
//                ]
//            ],422);
//        }

        /**
         * Event passed to prepare cart after login.
         */
        Event::dispatch('customer.after.login', $request->get('phone'));

        return response([
            'success' => true,
            'redirect' => route($this->_config['redirect'])
        ]);;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        auth()->guard('customer')->logout();

        Event::dispatch('customer.after.logout', $id);

        return redirect()->route($this->_config['redirect']);
    }

}