<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class PartnerAuthController extends Controller
{
    public function showLogin()
    {
        return Inertia::render('Partner/Login');
    }

    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'access_code' => 'required',
        ]);

        $partner = \App\Models\Partner::where('email', $validated['email'])
                                    ->where('access_code', $validated['access_code'])
                                    ->where('is_active', true)
                                    ->first();

        if ($partner) {
            Auth::guard('partner')->login($partner);
            $request->session()->regenerate();
            return redirect()->intended('/partner/dashboard');
        }

        return back()->withErrors([
            'email' => 'Invalid email or access code.',
        ]);
    }

    public function logout(Request $request)
    {
        Auth::guard('partner')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}
