<?php

/**
 * ConfigurationController.php
 * Copyright (c) 2019 james@firefly-iii.org
 *
 * This file is part of Firefly III (https://github.com/firefly-iii).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
declare(strict_types=1);

namespace FireflyIII\Http\Controllers\Admin;

use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Http\Requests\ConfigurationRequest;
use FireflyIII\Support\Facades\AppConfiguration;
use FireflyIII\Support\Facades\Preferences;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;

/**
 * Class ConfigurationController.
 */
final class ConfigurationController extends Controller
{
    /**
     * ConfigurationController constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->middleware(static function ($request, $next) {
            app('view')->share('title', (string) trans('firefly.system_settings'));
            app('view')->share('mainTitleIcon', 'bi-cpu');

            return $next($request);
        });
        $this->middleware(IsDemoUser::class)->except(['index']);
    }

    /**
     * Show configuration index.
     *
     * @return Factory|View
     */
    public function index(): Factory|\Illuminate\Contracts\View\View
    {
        $subTitle              = (string) trans('firefly.instance_configuration');
        $subTitleIcon          = 'bi-wrench';

        Log::channel('audit')->info('User visits admin config index.');

        // all available configuration and their default value in case
        // they don't exist yet.
        $singleUserMode        = AppConfiguration::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
        $isDemoSite            = AppConfiguration::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data;
        $siteOwner             = config('firefly.site_owner');

        $enableExchangeRates   = AppConfiguration::get('enable_exchange_rates', config('cer.enabled'))->data;
        $useRunningBalance     = AppConfiguration::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data;
        $enableExternalMap     = AppConfiguration::get('enable_external_map', config('firefly.enable_external_map'))->data;
        $enableExternalRates   = AppConfiguration::get('enable_external_rates', config('cer.download_enabled'))->data;
        $allowWebhooks         = AppConfiguration::get('allow_webhooks', config('firefly.allow_webhooks'))->data;
        $enableBatchProcessing = AppConfiguration::get('enable_batch_processing', false)->data;
        $validUrlProtocols     = AppConfiguration::get('valid_url_protocols', config('firefly.valid_url_protocols'))->data;

        return view('settings.configuration.index', [
            'subTitle'              => $subTitle,
            'subTitleIcon'          => $subTitleIcon,
            'singleUserMode'        => $singleUserMode,
            'isDemoSite'            => $isDemoSite,
            'siteOwner'             => $siteOwner,
            'enableExchangeRates'   => $enableExchangeRates,
            'useRunningBalance'     => $useRunningBalance,
            'enableExternalMap'     => $enableExternalMap,
            'enableExternalRates'   => $enableExternalRates,
            'allowWebhooks'         => $allowWebhooks,
            'enableBatchProcessing' => $enableBatchProcessing,
            'validUrlProtocols'     => $validUrlProtocols,
        ]);
    }

    /**
     * Store new configuration values.
     */
    public function postIndex(ConfigurationRequest $request): RedirectResponse
    {
        // get config values:
        $data = $request->getConfigurationData();

        Log::channel('audit')->info('User updates global configuration.', $data);

        // store config values
        AppConfiguration::set('single_user_mode', $data['single_user_mode']);

        AppConfiguration::set('enable_exchange_rates', $data['enable_exchange_rates']);
        AppConfiguration::set('use_running_balance', $data['use_running_balance']);

        AppConfiguration::set('enable_external_map', $data['enable_external_map']);
        AppConfiguration::set('enable_external_rates', $data['enable_external_rates']);
        AppConfiguration::set('allow_webhooks', $data['allow_webhooks']);
        AppConfiguration::set('enable_batch_processing', $data['enable_batch_processing']);

        AppConfiguration::set('valid_url_protocols', $data['valid_url_protocols']);
        AppConfiguration::set('is_demo_site', $data['is_demo_site']);

        // flash message
        session()->flash('success', (string) trans('firefly.configuration_updated'));
        Preferences::mark();

        return redirect()->route('settings.configuration.index');
    }
}
