<?php

namespace App\Http\Controllers;

use App\Models\Jumuiya;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class JumuiyaController extends Controller
{
    public function index(Request $request): View
    {
        $jumuiyas = Jumuiya::withCount('members')
            ->when($request->search, function ($query, $search) {
                $query->where(function ($query) use ($search) {
                    $query->where('name', 'like', "%{$search}%")
                        ->orWhere('code', 'like', "%{$search}%");
                });
            })
            ->latest()
            ->paginate(12)
            ->withQueryString();

        return view('jumuiyas.index', compact('jumuiyas'));
    }

    public function create(Request $request): View
    {
        if ($request->ajax()) {
            return $this->modalForm(
                'Register Jumuiya',
                'jumuiyas._form',
                ['jumuiya' => new Jumuiya],
                route('jumuiyas.store'),
                '#jumuiyas-fragment',
            );
        }

        return view('jumuiyas.create', ['jumuiya' => new Jumuiya]);
    }

    public function store(Request $request): JsonResponse|RedirectResponse
    {
        $data = $this->validatedData($request);
        $jumuiya = Jumuiya::create($data);
        $this->logActivity('created', 'jumuiyas', "Registered jumuiya {$jumuiya->name}");

        return $this->saveResponse($request, 'Jumuiya imesajiliwa kikamilifu.', 'jumuiyas.index', [], '#jumuiyas-fragment');
    }

    public function show(Jumuiya $jumuiya): View
    {
        $jumuiya->load(['members.position']);

        return view('jumuiyas.show', compact('jumuiya'));
    }

    public function edit(Request $request, Jumuiya $jumuiya): View
    {
        if ($request->ajax()) {
            return $this->modalForm(
                'Edit Jumuiya',
                'jumuiyas._form',
                compact('jumuiya'),
                route('jumuiyas.update', $jumuiya),
                '#jumuiyas-fragment',
                'PUT',
            );
        }

        return view('jumuiyas.edit', compact('jumuiya'));
    }

    public function update(Request $request, Jumuiya $jumuiya): JsonResponse|RedirectResponse
    {
        $jumuiya->update($this->validatedData($request, $jumuiya));
        $this->logActivity('updated', 'jumuiyas', "Updated jumuiya {$jumuiya->name}");

        return $this->saveResponse($request, 'Jumuiya imeboreshwa.', 'jumuiyas.index', [], '#jumuiyas-fragment');
    }

    public function destroy(Request $request, Jumuiya $jumuiya): JsonResponse|RedirectResponse
    {
        $jumuiya->delete();
        $this->logActivity('deleted', 'jumuiyas', "Deleted jumuiya {$jumuiya->name}");

        return $this->backResponse($request, 'Jumuiya imefutwa.', '#jumuiyas-fragment');
    }

    private function validatedData(Request $request, ?Jumuiya $jumuiya = null): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'code' => ['required', 'string', 'max:50', 'unique:jumuiyas,code,'.($jumuiya?->id ?? 'NULL')],
            'leader_name' => ['nullable', 'string', 'max:255'],
            'assistant_leader' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'location' => ['nullable', 'string', 'max:255'],
            'status' => ['required', 'in:active,inactive'],
            'description' => ['nullable', 'string'],
        ]);
    }
}
