<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreSarafRequest;
use App\Http\Requests\UpdateSarafRequest;
use App\Http\Requests\UpdateSarafStatusRequest;
use App\Models\Saraf;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class SarafController extends Controller
{
    public function index(): Response
    {
        $sarafs = Saraf::query()
            ->orderBy('name')
            ->get()
            ->map(fn (Saraf $saraf): array => [
                'id' => $saraf->id,
                'name' => $saraf->name,
                'address' => $saraf->address,
                'contact_number' => $saraf->contact_number,
                'is_active' => $saraf->is_active,
            ]);

        return Inertia::render('sarafi/sarafs/index', [
            'sarafs' => $sarafs,
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('sarafi/sarafs/create');
    }

    public function store(StoreSarafRequest $request): RedirectResponse
    {
        Saraf::query()->create([
            ...$request->validated(),
            'is_active' => true,
        ]);

        return redirect()
            ->route('sarafi.sarafs.index')
            ->with('status', __('Saraf created.'));
    }

    public function edit(Saraf $saraf): Response
    {
        return Inertia::render('sarafi/sarafs/edit', [
            'saraf' => [
                'id' => $saraf->id,
                'name' => $saraf->name,
                'address' => $saraf->address ?? '',
                'contact_number' => $saraf->contact_number ?? '',
                'is_active' => $saraf->is_active,
            ],
        ]);
    }

    public function update(UpdateSarafRequest $request, Saraf $saraf): RedirectResponse
    {
        $saraf->fill($request->validated());
        $saraf->save();

        return redirect()
            ->route('sarafi.sarafs.index')
            ->with('status', __('Saraf updated.'));
    }

    public function updateStatus(
        UpdateSarafStatusRequest $request,
        Saraf $saraf,
    ): RedirectResponse {
        $saraf->fill([
            'is_active' => $request->boolean('is_active'),
        ]);
        $saraf->save();

        return redirect()
            ->route('sarafi.sarafs.index')
            ->with('status', __('Saraf status updated.'));
    }
}
