<?php

require_once BASE_PATH . '/app/controllers/admin/AdminBaseController.php';

class AdminSettingController extends AdminBaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->requireAdmin();
    }

    public function index(): void
    {
        $settings = $this->systemSetting()->getAll();
        require BASE_PATH . '/app/views/admin/settings/index.php';
    }

    public function update(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        $maxUpload = trim($_POST['max_upload_mb'] ?? '');
        if (!ctype_digit($maxUpload)
            || (int) $maxUpload < 1
            || (int) $maxUpload > 100) {
            $this->flashError('Dung lượng upload phải là số nguyên từ 1 đến 100 MB.');
            $this->redirect('admin/system-settings');
        }

        $values = [
            'registration_enabled' => isset($_POST['registration_enabled']) ? '1' : '0',
            'maintenance_mode' => isset($_POST['maintenance_mode']) ? '1' : '0',
            'activity_logging_enabled' => isset($_POST['activity_logging_enabled']) ? '1' : '0',
            'max_upload_mb' => (string) (int) $maxUpload
        ];

        $this->mutateAndLog(
            fn () => $this->systemSetting()->update($values, (int) $_SESSION['user']['id']),
            'admin.system_settings.update',
            'system_setting',
            null,
            ['updated_keys' => array_keys($values)],
            true
        );

        $this->flashSuccess('Đã lưu cài đặt hệ thống.');
        $this->redirect('admin/system-settings');
    }
}
