<?php

namespace App\Livewire\Pages\Settings;

use App\Domains\Workspace\Models\Workspace;
use Illuminate\View\View;
use Livewire\Component;

class Index extends Component
{
    public string $workspaceName = '';

    public string $workspaceSlug = '';

    public int $workspaceId = 0;

    public function mount(): void
    {
        $ws = require_workspace();
        $this->workspaceId = $ws->id;
        $this->workspaceName = $ws->name;
        $this->workspaceSlug = $ws->slug;
    }

    public function saveWorkspace(): void
    {
        $this->validate([
            'workspaceName' => 'required|string|max:100',
            'workspaceSlug' => 'nullable|string|max:50|alpha_dash',
        ]);

        $ws = Workspace::findOrFail($this->workspaceId);
        $ws->update([
            'name' => $this->workspaceName,
            'slug' => $this->workspaceSlug ?: $ws->slug,
        ]);

        session()->flash('status', 'Workspace settings saved.');
    }

    public function render(): View
    {
        return view('livewire.pages.settings.index')
            ->layout('layouts.nimuli-app', ['title' => 'Settings']);
    }
}
