<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Controllers\AppController;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use App\Models\UserData;
use App\Models\UserDocuments;
use App\Http\Resources\User as UserResource;

class LoginController extends AppController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function register(Request $request){
        try {
            //Validated
            $validate = Validator::make($request->all(), 
            [
                'user_type' => 'required',
                'user_name' => 'required',
              //  'email' => 'required|email|unique:users,email',
               // 'password' => 'required'
            ]);

            if($validate->fails()){
                return response()->json([
                    'status' => false,
                    'message' => 'validation error',
                    'errors' => $validate->errors()
                ], 400);
            }
            $user = User::where('phone_number', '=', $request->user_name)->first();
            if(empty($user)){
                $user = User::where('email', '=', $request->user_name)->first();
                if(empty($user)){
                    $phoneNumber = NULL;
                    $email = NULL;
                    if(filter_var($request->user_name, FILTER_VALIDATE_EMAIL)) {
                        $email = $request->user_name;
                    } else {
                        $phoneNumber = $request->user_name;
                    }
                    $user = User::create([
                        'phone_number' => $phoneNumber,
                        'email' => $email,
                        'user_type' => $request->user_type
                    ]);
                }else{
                    return response()->json([
                        'status' => false,
                        'message' => 'This Email already registered',
                    ], 400);
                }
            }else{
                return response()->json([
                    'status' => false,
                    'message' => 'This Phone Number already registered',
                ], 400);
            }

            return response()->json([
                'status' => true,
                'message' => 'User Created Successfully',
                'token' => $user->createToken($request->user_name)->plainTextToken
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
    /**
     * Customer login
     */
    public function login(Request $request){
        try {
            $response =[];
            $validate = Validator::make($request->all(), [
                'user_name' => 'required',
                'password' => 'required'
            ]);
            
            if($validate->fails()){
                return response()->json([
                    'status' => false,
                    'message' => 'Validation errors in your request',
                    'errors' => $validate->errors()
                ], 400);
            }
            $credentials = $request->only('user_name', 'password');
            $user = User::where('email', $request->user_name)->first();
            $credentials = ['email' => $request->user_name, 'password' => $request->password];
            if(empty($user)){
                $user = User::where('email', $request->user_name)->first();
                $credentials = ['phone_number' => $request->user_name, 'password' => $request->password];
            }
            if (Auth::attempt($credentials)) {
                $token = auth()->user()->createToken("Gozap-". $request->user_name, ['*'], now()->addHours(3) );
                return response()->json([
                    'status' => true,
                    'message' => 'User Logged In Successfully',
                    'token' => $token->plainTextToken,
                    'expired_at' => $token->accessToken->expires_at
                ], 200);
            }else{
                return response()->json([
                    'status' => false,
                    'message' => 'Email & Password does not match.',
                ], 401);
                
            }
        } catch (\Throwable $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
    public function user_details(Request $request){
        $user = $request->user('api');
        return response()->json([
            'status' => true,
            'message' => 'User Details',
            'user' => new UserResource($user),
        ], 200);
    }
    public function kyc(Request $request){
        $postData = $request->all();
        $user = $request->user('api');
        if($userDoc['doc']){
            (new UserDocuments())->uploadFile($postData, $user);
        }
    }
    public function update_user(Request $request){
        $postData = $request->all();
        $user = $request->user('api');
        $userUpdate = [
            'name' => $postData['first_name'] .' ' . $postData['last_name'],
            'email' => $postData['email'],
            'phone_number' => $postData['phone_number'],
            'user_type' => $postData['user_type']
        ];
        $user->update($userUpdate);
        $userData = UserData::where('user_id', $user['id'])->first();
        $userDataUpdate = [
            'user_id' => $user['id'],
            'first_name' => isset($postData['first_name']) ? $postData['first_name'] : '',
            'last_name' => isset($postData['last_name']) ? $postData['last_name'] : '',
            'user_country_code' => isset($postData['user_country_code']) ? $postData['user_country_code'] :  $this->siteSettings['country_code'],
            'phone_number' => isset($postData['phone_number']) ? $postData['phone_number'] : '',
            'wallet_amount' => ( isset($postData['wallet_amount']) && $postData['wallet_amount'] > 0) ? $postData['wallet_amount'] : 0
        ];
        if($userData){
            $userData = $userData->update($userDataUpdate);
        }else{
            $userData = UserData::create($userDataUpdate);
        }
        return response()->json([
            'status' => true,
            'message' => 'User Updated Successfully',
            'user' => new UserResource($user),
        ], 200);
    }
}
