<?php

namespace App\Http\Controllers\User;

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

class UserAuthController extends Controller
{
    public function login_form(Request $request)
    {
        Log::info('User login request received', [
            'user_id' => $request->user_id,
        ]);

        $request->validate([
            'user_id' => 'required|string|exists:users,user_id',
            'password' => 'required|string|min:5',
        ]);

        try {

            $user = User::where('user_id', $request->user_id)->first();

            if (!$user || !$user->hasRole('user')) {

                Log::warning('Unauthorized user login attempt', [
                    'user_id' => $request->user_id,
                ]);

                return back()->with('error', 'Invalid credentials.');
            }

            // Check status
            if ($user->status !== 'Active') {

                return back()
                    ->with('error', 'Your account is inactive. Please contact support.')
                    ->withInput();
            }


            if (sha1(trim($request->password)) != $user->pwd) {

                Log::warning('Incorrect password attempt', [
                    'user_id' => $request->user_id,
                ]);

                return back()
                    ->with('error', 'Incorrect password')
                    ->withInput();
            }


            Auth::guard('web')->login($user);



            // $user->password = Hash::make($request->password);
            $user->save();

            Log::info('User logged in successfully', [
                'user_id' => $user->id,
            ]);

            return redirect()->route('user.dashboard')
                ->with('success', 'Logged in successfully!');
        } catch (\Throwable $e) {

            Log::error('User login error', [
                'error' => $e->getMessage(),
            ]);

            return back()
                ->with('error', 'Something went wrong!')
                ->withInput();
        }
    }

      public function logout_form(Request $request)
    {
        Auth::guard('web')->logout();

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

        return redirect()
            ->route('user.login')
            ->with('success', 'You have been logged out successfully.');
    }

}
