<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function showLogin()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'phone_number' => 'required|string',
            'dob_code' => 'required|string|size:6',
        ]);

        $user = \App\Models\User::where('phone_number', $request->phone_number)
                                ->where('dob_code', $request->dob_code)
                                ->first();

        if ($user) {
            \Illuminate\Support\Facades\Auth::login($user);
            return redirect()->intended(route('filament.admin.pages.dashboard'));
        }

        return back()->withErrors([
            'phone_number' => 'Maklumat log masuk tidak padan dengan rekod kami.',
        ])->withInput();
    }

    public function logout(Request $request)
    {
        \Illuminate\Support\Facades\Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }
}
