<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\PortalAuth;
use App\Core\Request;
use App\Core\Session;

class PortalAuthController extends Controller
{
    public function __construct()
    {
        PortalAuth::boot();
    }

    public function loginForm(): void
    {
        if (PortalAuth::check()) { $this->redirect('/portal'); return; }
        $this->render('portal/login', [
            'pageTitle' => 'Customer portal sign in',
            'error' => Session::flash('error'),
        ], 'layout/auth');
    }

    public function login(): void
    {
        $this->requireCsrf();
        $email = trim((string)Request::post('email'));
        $password = (string)Request::post('password');

        if (PortalAuth::attempt($email, $password)) {
            $this->redirect('/portal');
            return;
        }

        Session::flash('error', 'Incorrect email or password.');
        $this->redirect('/portal/login');
    }

    public function logout(): void
    {
        PortalAuth::logout();
        $this->redirect('/portal/login');
    }
}
