<?php

namespace Daylight\Core\Http\Controllers\Settings;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Settings\UpdateGeneralSettingsRequest;
use Daylight\Core\Settings\General;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use PeterColes\Countries\CountriesFacade as Countries;

class GeneralSettingsController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:update:settings', only: ['update']),
            new Middleware('can:read:settings', only: ['index']),
        ];
    }

    public function index(General $settings)
    {
        $pages = (daylightModel('page'))::query()
            ->withWhereHas('translations', function ($query) {
                return $query->where('locale', app()->getLocale());
            })
            ->get();

        return view('daylight::settings.general', [
            'settings' => $settings,
            'countries' => Countries::lookup(app()->getLocale()),
            'pages' => $pages,
        ]);
    }

    public function update(UpdateGeneralSettingsRequest $request, General $settings)
    {
        $settings->fill($request->all())->save();

        return redirect()
            ->route('daylight.settings.general.index')
            ->with('success', __('daylight::settings.settings_updated'));
    }
}
