<?php

namespace App\Livewire\Studio\Setting;

use App\Livewire\Forms\Studio\Setting\ContactForm;
use App\Livewire\Forms\Studio\Setting\GeneralForm;
use App\Livewire\Forms\Studio\Setting\SeoForm;
use App\Livewire\Forms\Studio\Setting\SocialForm;
use App\Settings\ContactSettings;
use App\Settings\GeneralSettings;
use App\Settings\SeoSettings;
use App\Settings\SocialSettings;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Artisan;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Aplikasi')]
class Application extends Component
{
    use WithAuthorization, WithSubscribeNotification, WithToast, WithUpdatedData;

    public GeneralForm $generalForm;

    public ContactForm $contactForm;

    public SocialForm $socialForm;

    public SeoForm $seoForm;

    public function mount(
        GeneralSettings $generalSettings,
        ContactSettings $contactSettings,
        SocialSettings $socialSettings,
        SeoSettings $seoSettings,
    ): void {
        $this->generalForm->setSettings($generalSettings);

        $this->contactForm->setSettings($contactSettings);

        $this->socialForm->setSettings($socialSettings);

        $this->seoForm->setSettings($seoSettings);
    }

    public function updateGeneral(GeneralSettings $generalSettings): void
    {
        $this->canOrAbort('update general settings');

        $isMaintenance = $this->generalForm->update($generalSettings);

        if ($isMaintenance) {
            Artisan::call('down', [
                '--secret' => config('app.maintenance.secret'),
            ]);

            $this->redirect('/'.config('app.maintenance.secret'));
        }

        Artisan::call('up');

        $this->toast('Pengaturan umum berhasil diperbarui.');
    }

    public function updateContact(ContactSettings $contactSettings): void
    {
        $this->canOrAbort('update contact settings');

        $this->contactForm->update($contactSettings);

        $this->toast('Pengaturan kontak berhasil diperbarui.');
    }

    public function updateSocial(SocialSettings $socialSettings): void
    {
        $this->canOrAbort('update social settings');

        $this->socialForm->update($socialSettings);

        $this->toast('Pengaturan media sosial berhasil diperbarui.');
    }

    public function updateSeo(SeoSettings $seoSettings): void
    {
        $this->canOrAbort('update seo settings');

        $this->seoForm->update($seoSettings);

        $this->toast('Pengaturan SEO berhasil diperbarui.');
    }

    public function render(): View
    {
        return view('livewire.studio.setting.application', [
            'pageTitle' => 'Aplikasi',
        ]);
    }
}
