<?php

namespace Blog\Controller;

use Blog\Model\AuthModel;

class AuthController
{
    private $model;
    private $view;

    public function __construct($view) {
        $this->model = new AuthModel();
        $this->view = $view;
    }

    public function showLoginForm() {
        $this->view->setVars([
            'labels' => [
                "email" => "E-Mail-Adresse",
                "password" => "Passwort",
                "password_repeat" => "Passwort wiederholen",
                "old_password" => "Altes Passwort"
            ],
            'errors' => $_SESSION['auth_errors'] ?? [],
            'validData' => $_SESSION['auth_validData'] ?? []
        ]);
        unset($_SESSION['auth_errors'], $_SESSION['auth_validData']);
    }

    public function showRegistrationForm() {
        $this->view->setVars([
            'labels' => [
                "email" => "E-Mail-Adresse",
                "password" => "Passwort",
                "password_repeat" => "Passwort wiederholen",
                "old_password" => "Altes Passwort"
            ],
            'errors' => $_SESSION['auth_errors'] ?? [],
            'validData' => $_SESSION['auth_validData'] ?? []
        ]);
        unset($_SESSION['auth_errors'], $_SESSION['auth_validData']);
    }

    public function login() {
        $email = $_POST['email'];
        $password = $_POST['password'];

        $result = $this->model->login($email, $password);
        
        if ($result['success']) {
            $_SESSION['user'] = $result['user']['email'];
            $_SESSION['is_admin'] = $result['user']['is_admin'];
            $this->view->setDoMethodName('showLoginSuccess');
        } else {
            $this->view->setVars([
                'errors' => ['login' => $result['error']],
                'validData' => ['email' => $email],
                'loginSuccess' => false
            ]);
            $this->view->setDoMethodName('showLoginForm');
        }
    }

    public function register() {
        $data = [
            'first_name' => $_POST['first_name'] ?? '',
            'last_name' => $_POST['last_name'] ?? '',
            'street' => $_POST['street'] ?? '',
            'house_number' => $_POST['house_number'] ?? '',
            'postal_code' => $_POST['postal_code'] ?? '',
            'city' => $_POST['city'] ?? '',
            'country' => $_POST['country'] ?? '',
            'phone' => $_POST['phone'] ?? '',
            'email' => $_POST['email'] ?? '',
            'password' => $_POST['password'] ?? '',
            'password_repeat' => $_POST['password_repeat'] ?? '',
            'is_admin' => $_POST['isAdmin'] ?? false,
        ];

        $result = $this->model->register($data);

        if ($result === true) {
            $this->view->setDoMethodName('showRegistrationSuccess');
        } else {
            if (is_array($result)) {
                $errors['register'] = implode('<br>', $result);
            } else {
                $errors['register'] = is_string($result) ? $result : "Registrierung fehlgeschlagen.";
            }
            $this->view->setVars(['errors' => $errors, 'validData' => $data]);
            $this->view->setDoMethodName('showRegistrationForm');
        }
    }

    public function forgotPassword() {
        $email = $_POST['email'] ?? '';
        if (empty($email)) {
            $_SESSION['auth_errors']['email'] = "Bitte E-Mail-Adresse angeben.";
            header("Location: /?controller=Auth&do=showAuthForm");
            exit;
        }
        $this->model->pwForgot($email);
        header("Location: /?controller=Auth&do=showConfirmation&msg=pwforgot");
        exit;
    }

    public function changePassword() {
        $email = $_POST['email'] ?? '';
        $oldpw = $_POST['old_password'] ?? '';
        $newpw = $_POST['password'] ?? '';
        $repeat = $_POST['password_repeat'] ?? '';

        if (!$this->model->checkDoublePw($newpw, $repeat)) {
            $_SESSION['auth_errors']['password'] = "Neue Passwörter stimmen nicht überein.";
            header("Location: /?controller=Auth&do=showAuthForm");
            exit;
        }

        $result = $this->model->updatePassword($email, $oldpw, $newpw);

        if ($result === true) {
            header("Location: /?controller=Auth&do=showConfirmation&msg=pwchange");
            exit;
        } else {
            $_SESSION['auth_errors']['password'] = is_string($result) ? $result : "Fehler beim Aktualisieren des Passworts.";
            header("Location: /?controller=Auth&do=showAuthForm");
            exit;
        }
    }

    public function showConfirmation() {
        $messages = [
            'login' => "Login erfolgreich.",
            'register' => "Registrierung erfolgreich.",
            'pwforgot' => "Ein temporäres Passwort wurde an Ihre E-Mail gesendet.",
            'pwchange' => "Passwort erfolgreich geändert."
        ];
        $msgKey = $_GET['msg'] ?? '';
        $message = $messages[$msgKey] ?? "Aktion erfolgreich.";
        $this->view->setVars(['message' => $message]);
        $this->view->render('auth/confirmation');
    }

    public function logout() {
        unset($_SESSION['user']);
        session_destroy();
        $this->view->setDoMethodName('showLogoutSuccess');
    }
}