<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Database;
use App\Helpers\Validator;

class AuthController extends Controller
{
    public function loginForm(): void
    {
        if (Auth::check()) {
            $this->redirect('/');
        }
        $this->view('auth/login');
    }

    public function login(): void
    {
        $username = $this->input('username', '');
        $password = $this->input('password', '');

        if (Auth::attempt($username, $password)) {
            $this->redirect('/');
        }

        $this->view('auth/login', ['error' => 'Nieprawidłowy login lub hasło.']);
    }

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

    public function changePasswordForm(): void
    {
        Auth::requireLogin();
        $this->view('auth/change-password');
    }

    public function changePassword(): void
    {
        Auth::requireLogin();

        $current = $this->input('current_password', '');
        $new = $this->input('new_password', '');
        $confirm = $this->input('confirm_password', '');

        $validator = new Validator();
        $validator
            ->required('current_password', $current, 'Aktualne hasło')
            ->required('new_password', $new, 'Nowe hasło')
            ->minLength('new_password', $new, 6, 'Nowe hasło');

        if (!$validator->isValid()) {
            $this->view('auth/change-password', ['error' => $validator->getFirstError()]);
            return;
        }

        if ($new !== $confirm) {
            $this->view('auth/change-password', ['error' => 'Nowe hasła nie są identyczne.']);
            return;
        }

        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT password_hash FROM users WHERE id = :id");
        $stmt->execute(['id' => Auth::user()['id']]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($current, $user['password_hash'])) {
            $this->view('auth/change-password', ['error' => 'Aktualne hasło jest nieprawidłowe.']);
            return;
        }

        $stmt = $db->prepare("UPDATE users SET password_hash = :hash WHERE id = :id");
        $stmt->execute([
            'hash' => Auth::hashPassword($new),
            'id' => Auth::user()['id'],
        ]);

        $this->flash('success', 'Hasło zostało zmienione.');
        $this->redirect('/');
    }
}
