<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CartItem;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
// use App\Services\ActivityLogService;
use App\Models\UserLog;

class LoginController extends Controller
{

    // LOGIN PAGE

    public function login()
    {

        return view('frontend.auth.login');
    //     return redirect()
    // ->route('frontend.login')
    // ->with('error', 'You are not authorized to login.');

    }

    public function register()
    {

        return view('frontend.auth.register');

    }

    // public function register_form(Request $request)
    // {
    //     $request->validate([

    //         'name'                  => 'required|string|max:255',
    //         'company_name'                  => 'required|string|max:255',

    //         'email'                 => 'required|email|unique:users,email',

    //         'password'              => 'required|min:4|confirmed',

    //     ]);

    //     $user = User::create([

    //         'name'     => $request->name,

    //         'company_name'    => $request->company_name,
    //         'email'    => $request->email,

    //         'password' => Hash::make($request->password),

    //         'type'     => 'user',

    //     ]);

    //     Auth::login($user);

    //     return redirect('/')
    //             ->with('success','Account Created Successfully');
    // }
        // LOGIN CHECK
    public function register_form(Request $request)
    {
        // print_r($request);

        try {

            $user = User::create([
                'name'         => $request->name,
                'company_name' => $request->company_name,
                'email'        => $request->email,
                'password'     => Hash::make($request->password),
                'type'         => 'user',
                'status'       => 'pending',
            ]);
        // print_r($user);
        // die($user);
        return redirect()
        ->route('login')
        ->with(
            'success',
            'Registration successful. Your account is pending admin approval.'
        );

        } catch (\Exception $e) {

        // die('$user');
            return back()->with('error', $e->getMessage());

        }
    }


    
    // public function login()
    // {

    //     return view('frontend.auth.login');

    // }

        public function loginCheck(Request $request)
    {
        try {

            $request->validate([
                'email'    => 'required|email',
                'password' => 'required|min:4',
            ]);

            $credentials = [
                'email'    => trim($request->email),
                'password' => $request->password,
            ];

            // Check User Exists
            $user = \App\Models\User::where('email', $request->email)->first();

            if (!$user) {
                return back()
                    ->withInput($request->only('email'))
                    ->with('error', 'Email not registered.');
            }

            // Approval Check
            if ($user->status == 'pending') {
                return back()
                    ->withInput($request->only('email'))
                    ->with('error', 'Your account is pending admin approval.');
            }

            if ($user->status != 'approved') {
                return back()
                    ->withInput($request->only('email'))
                    ->with('error', 'Your account is not approved.');
            }

            // Login Attempt
            if (!Auth::attempt($credentials)) {
                return back()
                    ->withInput($request->only('email'))
                    ->with('error', 'Invalid Email or Password.');
            }

            $request->session()->regenerate();

            // Only User Login Allowed
            // if (Auth::user()->type !== 'Admin') {

            //     Auth::logout();

            //     return redirect()
            //         ->route('login')
            //         ->with('error', 'You are not authorized to login.');
            // }

            try {

                UserLog::create([
                    'user_id'       => Auth::id(),
                    'activity'      => 'User Logged In',
                    'activity_type' => 'LOGIN',
                    'ip_address'    => request()->ip(),
                ]);

            } catch (\Exception $e) {

                \Log::error('User Log Error: ' . $e->getMessage());
            }

            return redirect()
                ->route('products')
                ->with('success', 'Login Successfully');

        } catch (\Illuminate\Validation\ValidationException $e) {

            return back()
                ->withErrors($e->validator)
                ->withInput();

        } catch (\Exception $e) {

            \Log::error('Login Error: ' . $e->getMessage());

            return back()
                ->withInput($request->only('email'))
                ->with('error', 'Something went wrong. Please try again.');
        }
    }
        // LOGOUT

    public function logout(Request $request)
    {
        try {

            UserLog::create([
                'user_id'       => Auth::id(),
                'activity'      => 'User Logged Out',
                'activity_type' => 'LOGOUT',
                'ip_address'    => $request->ip(),
            ]);

        } catch (\Exception $e) {

            \Log::error('Logout Log Error: ' . $e->getMessage());
        }

        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login');
    }

}