<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\EmployeeCounter;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class AuthController extends Controller
{
    private function generateEmployeeId()
    {
        return DB::transaction(function () {

            $year = date('Y');

            $counter = EmployeeCounter::lockForUpdate()
                ->where('year', $year)
                ->first();

            if (!$counter) {
                $counter = EmployeeCounter::create([
                    'year' => $year,
                    'last_number' => 0
                ]);
            }

            $counter->last_number += 1;
            $counter->save();

            $runningNumber = str_pad($counter->last_number, 3, '0', STR_PAD_LEFT);

            return 'S' . $year . $runningNumber;
        });
    }

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

    public function showLogin()
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'login' => 'required',
            'password' => 'required'
        ]);

        $loginType = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'employee_id';

        $credentials = [
            $loginType => $request->login,
            'password' => $request->password
        ];

        $user = User::where($loginType, $request->login)->first();

        if (!$user) {
            return back()->withErrors([
                'login' => 'Account not registered.'
            ]);
        }

        if (!$user->is_approved) {
            return back()->withErrors([
                'login' => 'Account not approved by manager.'
            ]);
        }

        if (Auth::attempt($credentials)) {

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

            session(['token_version' => Auth::user()->token_version]);

            Redis::lpush('login_logs', json_encode([
                'user_id' => Auth::id(),
                'event' => 'login',
                'ip' => request()->ip(),
                'time' => now()
            ]));

            return redirect('/dashboard');
        }

        return back()->withErrors([
            'login' => 'ID Pekerja / Email atau Password salah.'
        ]);
    }

    public function logout(Request $request)
    {
        $userId = Auth::id(); // ambil dulu sebelum logout

        Redis::lpush('login_logs', json_encode([
            'user_id' => $userId,
            'event' => 'logout',
            'ip' => request()->ip(),
            'time' => now()
        ]));

        Auth::logout();

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

        return redirect('/login');
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8|confirmed'
        ]);

        User::create([
            'name' => $request->name,
            'employee_id' => $this->generateEmployeeId(),
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'is_approved' => false,
            'token_version' => 1,
        ]);

        return redirect('/login')
            ->with('message', 'Registration successful. Waiting for admin approval.');
    }
}
