<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

/**
 * SettingsController — app-wide configuration.
 */
class SettingsController extends BaseController
{
    public function index(): string
    {
        $settingsModel = model('App\Models\SettingsModel');

        return $this->render('admin/settings/index', [
            'title'    => lang('Admin.settings'),
            'settings' => $settingsModel->getAllSettings(),
        ]);
    }

    public function update()
    {
        $this->requireSuperAdmin();

        $settingsModel = model('App\Models\SettingsModel');
        $post = $this->request->getPost();

        $allowed = ['app_name', 'qr_base_url', 'default_language', 'items_per_page'];

        foreach ($allowed as $key) {
            if (isset($post[$key])) {
                $settingsModel->setSetting($key, $post[$key]);
            }
        }

        // QR logo upload
        $logoFile = $this->request->getFile('qr_logo');
        if ($logoFile && $logoFile->isValid() && ! $logoFile->hasMoved()) {
            $result = (new \App\Libraries\FileUploadHandler())->uploadImage($logoFile, 'qr_logos');
            if ($result['success']) {
                $settingsModel->setSetting('qr_logo_path', $result['path']);
            }
        }

        $this->flashSuccess(lang('Admin.settings_saved'));
        return redirect()->to(site_url('admin/settings'));
    }
}
