<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Models\UserModel;

class AuthController
{
    public function csrf(array $params): void
    {
        $this->json(['csrfToken' => Csrf::get()]);
    }

    public function login(array $params): void
    {
        Csrf::validate();

        if (!Auth::checkLoginRateLimit()) {
            http_response_code(429);
            $this->json(['error' => ['message' => 'Terlalu banyak percobaan. Coba lagi nanti.', 'code' => 'RATE_LIMITED']]);
            return;
        }

        $body = $this->body();
        $username = trim($body['username'] ?? '');
        $password = $body['password'] ?? '';

        if ($username === '' || $password === '') {
            http_response_code(400);
            $this->json(['error' => ['message' => 'Username dan password wajib diisi', 'code' => 'VALIDATION']]);
            return;
        }

        $user = UserModel::findByUsername($username);
        if (!$user || !password_verify($password, $user['password_hash'])) {
            http_response_code(401);
            $this->json(['error' => ['message' => 'Username atau password salah', 'code' => 'INVALID_CREDENTIALS']]);
            return;
        }

        Auth::login($user['id']);
        // Reset rate limit on success
        unset($_SESSION['login_attempts']);

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

    public function logout(array $params): void
    {
        Auth::logout();
        $this->json(['success' => true]);
    }

    public function me(array $params): void
    {
        if (!Auth::isLoggedIn()) {
            http_response_code(401);
            $this->json(['error' => ['message' => 'Belum login', 'code' => 'UNAUTHORIZED']]);
            return;
        }
        $user = UserModel::findById(Auth::userId());
        $this->json(['username' => $user['username'] ?? '']);
    }

    public function changePassword(array $params): void
    {
        Auth::requireAuth();
        Csrf::validate();

        $body = $this->body();
        $current = $body['currentPassword'] ?? '';
        $newPass = $body['newPassword'] ?? '';

        if (strlen($newPass) < 6) {
            http_response_code(400);
            $this->json(['error' => ['message' => 'Password baru minimal 6 karakter', 'code' => 'VALIDATION']]);
            return;
        }

        $user = UserModel::findById(Auth::userId());
        if (!password_verify($current, $user['password_hash'])) {
            http_response_code(400);
            $this->json(['error' => ['message' => 'Password saat ini salah', 'code' => 'INVALID_PASSWORD']]);
            return;
        }

        $hash = password_hash($newPass, PASSWORD_BCRYPT);
        UserModel::updatePassword($user['id'], $hash);

        $this->json(['success' => true, 'message' => 'Password berhasil diubah']);
    }

    private function json(mixed $data, int $code = 0): void
    {
        if ($code) http_response_code($code);
        header('Content-Type: application/json');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    private function body(): array
    {
        return json_decode(file_get_contents('php://input'), true) ?? [];
    }
}
