<?php

declare(strict_types=1);

namespace AllCoach\Frontend\Controllers;

defined( 'ABSPATH' ) || exit;

use AllCoach\Application\Auth\LoginService;
use AllCoach\Application\Auth\LoginDTO;
use AllCoach\Frontend\Router;
use AllCoach\Support\TemplateLoader;

class AuthController extends BaseController {

	public function __construct(
		TemplateLoader $templateLoader,
		private readonly LoginService $loginService,
	) {
		parent::__construct( $templateLoader );
	}

	public function login(): void {
		if ( is_user_logged_in() ) {
			$this->redirect( Router::url() );
		}

		$error = '';

		if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
			$error = $this->handleLogin();
		}

		$this->render(
			'auth/login.php',
			[
				'pageTitle' => __( 'Login', 'allcoach' ),
				'error'     => $error,
			]
		);
	}

	private function handleLogin(): string {
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_allcoach_nonce'] ?? '' ) ), 'allcoach_login' ) ) {
			return __( 'Security check failed. Please try again.', 'allcoach' );
		}

		$login    = sanitize_text_field( wp_unslash( $_POST['login'] ?? '' ) );
		$password = wp_unslash( $_POST['password'] ?? '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- password must not be sanitized

		if ( empty( $login ) || empty( $password ) ) {
			return __( 'Please enter your email and password.', 'allcoach' );
		}

		$rememberme = ! empty( $_POST['rememberme'] );

		try {
			$dto = new LoginDTO(
				login: $login,
				password: $password,
				remember: $rememberme,
			);

			$this->loginService->execute( $dto );

			$redirect = sanitize_url( wp_unslash( $_GET['redirect_to'] ?? '' ) );
			$this->redirect( $redirect ?: Router::url() );
		} catch ( \AllCoach\Core\Exceptions\ValidationException $e ) {
			return $e->getErrors()['login'] ?? $e->getMessage();
		}

		return '';
	}
}
