<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class AuthController extends Controller
{
    private User $userModel;

    public function __construct()
    {
        $this->userModel = new User();
    }

    public function loginForm(): void
    {
        if ($this->isAuthenticated()) {
            $this->redirect('/catalog');
        }

        $redirect = $this->getQuery('redirect', '/catalog');
        
        $this->view('auth/login', [
            'redirect' => $redirect,
            'error' => $this->getFlash('error'),
            'success' => $this->getFlash('success')
        ]);
    }

    public function login(): void
    {
        $email = $this->getPost('email', '');
        $password = $this->getPost('password', '');
        $redirect = $this->getPost('redirect', '/catalog');

        if (empty($email) || empty($password)) {
            $this->json([
                'success' => false,
                'message' => 'Заполните все поля'
            ]);
            return;
        }

        $user = $this->userModel->authenticate($email, $password);

        if (!$user) {
            $this->json([
                'success' => false,
                'message' => 'Неверный email или пароль'
            ]);
            return;
        }

        $this->setSession($user);

        $this->json([
            'success' => true,
            'redirect' => $redirect
        ]);
    }

    public function registerForm(): void
    {
        if ($this->isAuthenticated()) {
            $this->redirect('/catalog');
        }

        $this->view('auth/register', [
            'errors' => $_SESSION['registration_errors'] ?? [],
            'old' => $_SESSION['old_data'] ?? [],
            'success' => $_SESSION['registration_success'] ?? null
        ]);

        unset($_SESSION['registration_errors']);
        unset($_SESSION['old_data']);
        unset($_SESSION['registration_success']);
    }

    public function register(): void
    {
        $errors = [];
        
        $fullName = trim($this->getPost('fio', ''));
        $city = trim($this->getPost('city', ''));
        $email = trim($this->getPost('email', ''));
        $phone = trim($this->getPost('phone', ''));
        $password = $this->getPost('password', '');
        $confirmPassword = $this->getPost('confirm-password', '');
        $privacy = $this->getPost('privacy');

        if (empty($fullName) || strlen($fullName) < 3) {
            $errors[] = 'ФИО должно содержать минимум 3 символа';
        }

        if (empty($city) || strlen($city) < 2) {
            $errors[] = 'Введите корректное название города';
        }

        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Введите корректный email адрес';
        }

        if (empty($phone)) {
            $errors[] = 'Введите номер телефона';
        }

        if (empty($password) || strlen($password) < 6) {
            $errors[] = 'Пароль должен содержать минимум 6 символов';
        }

        if ($password !== $confirmPassword) {
            $errors[] = 'Пароли не совпадают';
        }

        if (!$privacy) {
            $errors[] = 'Необходимо согласие с условиями обработки персональных данных';
        }

        if (empty($errors) && $this->userModel->emailExists($email)) {
            $errors[] = 'Пользователь с таким email уже существует';
        }

        if (!empty($errors)) {
            $_SESSION['registration_errors'] = $errors;
            $_SESSION['old_data'] = [
                'fio' => $fullName,
                'city' => $city,
                'email' => $email,
                'phone' => $phone
            ];
            $this->redirect('/register');
            return;
        }

        try {
            $userId = $this->userModel->register([
                'email' => $email,
                'password' => $password,
                'full_name' => $fullName,
                'phone' => $phone,
                'city' => $city
            ]);

            if (!$userId) {
                throw new \Exception('Ошибка при создании пользователя');
            }

            $user = $this->userModel->find($userId);
            $this->setSession($user);

            $_SESSION['registration_success'] = 'Регистрация прошла успешно!';
            $this->redirect('/catalog');

        } catch (\Exception $e) {
            $_SESSION['registration_errors'] = [$e->getMessage()];
            $_SESSION['old_data'] = [
                'fio' => $fullName,
                'city' => $city,
                'email' => $email,
                'phone' => $phone
            ];
            $this->redirect('/register');
        }
    }

    public function logout(): void
    {
        session_destroy();
        session_start();
        
        $this->redirect('/');
    }

    private function setSession(array $user): void
    {
        $_SESSION['user_id'] = $user['user_id'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['user_phone'] = $user['phone'] ?? '';
        $_SESSION['user_city'] = $user['city'] ?? '';
        $_SESSION['isLoggedIn'] = true;
        $_SESSION['isAdmin'] = (bool) $user['is_admin'];
        $_SESSION['login_time'] = time();
    }
}
