<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Services\AuditService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class PortalLoginController extends Controller
{
    public function __construct(
        protected AuditService $auditService,
    ) {}

    public function showLoginForm(): View
    {
        return view('portal.auth.login');
    }

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

        $customer = Customer::query()
            ->where(function ($query) use ($validated) {
                $query->where('email', $validated['identifier'])
                    ->orWhere('customer_no', $validated['identifier']);
            })
            ->first();

        if (! $customer
            || ! $customer->portal_enabled
            || $customer->status !== 'active'
            || ! $customer->portal_password
            || ! Hash::check($validated['password'], $customer->portal_password)
        ) {
            return back()
                ->withInput($request->only('identifier'))
                ->withErrors(['identifier' => 'Invalid credentials or portal access is disabled.']);
        }

        $request->session()->put('portal_customer_id', $customer->id);
        $request->session()->regenerate();

        $this->auditService->log('portal_login', 'auth', 'customer', $customer->id);

        return redirect()->intended('/portal/dashboard');
    }

    public function logout(Request $request): RedirectResponse
    {
        $customerId = $request->session()->get('portal_customer_id');

        if ($customerId) {
            $this->auditService->log('portal_logout', 'auth', 'customer', (int) $customerId);
        }

        $request->session()->forget('portal_customer_id');
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/portal/login');
    }
}
