<?php

namespace Modules\Auth\Controllers;

use App\Controllers\BaseController;
use Modules\Auth\Services\AuthService;

class LoginController extends BaseController
{
    protected AuthService $auth;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->auth = new AuthService();
    }

    public function show()
    {
        return view('Modules\Auth\Views\login', [
            'title' => 'Sign In',
        ]);
    }

    public function attempt()
    {
        $rules = [
            'identifier' => 'required|min_length[3]|max_length[191]',
            'password'   => 'required|min_length[1]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $identifier = trim($this->request->getPost('identifier'));
        $password   = (string) $this->request->getPost('password');
        $rememberMe = (bool) $this->request->getPost('remember_me');

        $result = $this->auth->attemptLogin(
            $identifier,
            $password,
            $this->request->getIPAddress(),
            $this->request->getUserAgent()->getAgentString()
        );

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('error', $result['error']);
        }

        $this->auth->establishSession(
            $result['user'],
            $rememberMe,
            $this->request->getIPAddress(),
            $this->request->getUserAgent()->getAgentString()
        );

        if ($result['user']->must_change_password) {
            return redirect()->to('/password/change')->with('warning', 'Please set a new password before continuing.');
        }

        $landing = $this->auth->landingUrlForRole($result['user']->role_id);

        return redirect()->to($landing)->with('success', 'Welcome back, ' . $result['user']->getFullName() . '.');
    }
}
