<?php
namespace App\Core;

use App\Models\UserModel;

class Controller
{
    protected $user;

    public function __construct()
    {
        if (!empty($_SESSION['user_id'])) {
            $this->user = (new UserModel())->findById((int)$_SESSION['user_id']);
        }
    }

    protected function requireLogin(): void
    {
        if (!$this->user) {
            if (function_exists('app_log_security_event')) {
                app_log_security_event('web_route_requires_login', [
                    'route' => (string)($_SERVER['REQUEST_URI'] ?? ''),
                ]);
            }
            flash('error', app_zh('请先登录'));
            redirect('login');
        }
    }

    protected function requireAdmin(): void
    {
        $this->requireLogin();
        if (($this->user['role'] ?? '') !== 'admin') {
            flash('error', app_zh('无权限访问'));
            redirect('dashboard');
        }
    }

    protected function json($data): void
    {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}
