<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;
use Inertia\Response;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */

     public function storePin(Request $request)
{
    // Validate the request
    $request->validate([
        'user_pin' => ['required', 'string'], // Ensure the PIN is provided
        'company_id' => ['required', 'exists:company,id'], // Ensure the company exists
        'branch_id' => ['required', 'exists:company_branch,id'], // Ensure the branch exists
    ]);

    // Find the user by PIN, company_id, and branch_id
    $user = \App\Models\User::where('user_pin', $request->user_pin)
                            ->where('company_id', $request->company_id)
                            ->where('branch_id', $request->branch_id)
                            ->first();

    if ($user) {
        // Log the user in manually
        Auth::login($user);

        // Regenerate the session to prevent session fixation attacks
        $request->session()->regenerate();

        // Redirect to the intended page
        return redirect()->intended('/NewDashboard');
    }

    // Authentication failed
    return back()->withErrors([
        'user_pin' => 'The provided PIN, company, or branch is incorrect.',
    ]);
}

    public function create(): Response
    {
        return Inertia::render('Auth/Login', [
            'canResetPassword' => Route::has('password.request'),
            'status' => session('status'),
        ]);
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

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

        return redirect()->intended(RouteServiceProvider::HOME);
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}
