<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{

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

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

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'              => 'required|string|max:200',
            'mobile'            => 'required|digits:10|unique:users,mobile',
            'email'             => 'required|string|email|max:255|unique:users,email',
            'password'          => 'required|string|min:6',
            'confirm_password'  => 'required|same:password',
            'agreed'            => 'accepted'
        ], [
            'agreed.accepted'   => 'You must agree to the Terms & Conditions and Privacy Policy.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => $validator->errors()
            ]);
        }

        $user = User::create([
            'name'     => $request->name,
            'mobile'   => $request->mobile,
            'email'    => $request->email,
            'password' => Hash::make($request->password),
        ]);
        $user->assignRole('User');

        return response()->json(['success' => 'Registration successful!', 'user' => $user]);
    }


    public function signin(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'username' => 'required',
                'password' => 'required',
            ],
            [
                'username.required' => 'Please enter username',
                'password.required' => 'Please enter password',
            ],
        );

        if ($validator->passes()) {
            $username    = $request->username;
            $password    = $request->password;
            $remember_me = $request->has('remember_me') ? true : false;

            try {
                $user = User::where('email', $username)->orWhere('mobile', $username)->first();
                if (! $user) {
                    return response()->json(['error2' => 'No user found with this username']);
                }

                $userType = $user->roles()->first()?->name;
                Logger($userType);
                if (null == $userType || '' == $userType) {
                    return response()->json(['error2' => 'User type not found']);
                }

                // if ('User' == $userType) {
                //     return response()->json(['error2' => 'You are not authorized to login']);
                // }

                if (!auth()->attempt(['email' => $username, 'password' => $password], $remember_me)) {
                    return response()->json(['error2' => 'Your entered credentials are invalid']);
                }

                if (in_array($userType, ['Admin', 'Super Admin'])) {
                    $redirectUrl = route('dashboard');
                    Logger($redirectUrl);
                } else {
                    $redirectUrl = session()->pull('url.intended', route('home'));
                    Logger($redirectUrl);
                }

                return response()->json(['success' => 'login successful', 'user_type' => $userType, 'redirect' => $redirectUrl,]);
            } catch (\Exception $e) {
                Log::info('login error:' . $e);

                return response()->json(['error2' => 'Something went wrong while validating your credentials!']);
            }
        } else {
            return response()->json(['error' => $validator->errors()]);
        }
    }



    public function logout()
    {
        auth()->logout();
        Logger("Logout");
        return redirect()->route('login');
    }

    public function showChangePassword()
    {
        return view('admin.change-password');
    }

    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'old_password'     => 'required',
            'password'         => 'required',
            'confirm_password' => 'required|same:password',
        ]);

        if ($validator->passes()) {
            $old_password = $request->old_password;
            $password     = $request->password;

            try {
                $user = DB::table('users')->where('id', $request->user()->id)->first();

                if (Hash::check($old_password, $user->password)) {
                    DB::table('users')->where('id', $request->user()->id)->update(['password' => Hash::make($password)]);

                    return response()->json(['success' => 'Password changed successfully!']);
                }

                return response()->json(['error2' => 'Old password does not match']);
            } catch (\Exception $e) {
                DB::rollBack();
                Log::info('password change error:' . $e);

                return response()->json(['error2' => 'Something went wrong while changing your password!']);
            }
        } else {
            return response()->json(['error' => $validator->errors()]);
        }
    }


    public function myAccount()
    {
        return view('user.my_account');
    }
}
