<?php

namespace App\Http\Controllers;

use App\Models\ChurchService;
use App\Models\ServiceType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ChurchServiceController extends Controller
{
    public function index(Request $request): View
    {
        $services = ChurchService::with(['serviceType', 'creator'])
            ->when($request->status, fn ($query, $status) => $query->where('status', $status))
            ->when($request->service_type_id, fn ($query, $type) => $query->where('service_type_id', $type))
            ->latest('service_date')
            ->paginate(12)
            ->withQueryString();

        return view('services.index', [
            'services' => $services,
            'serviceTypes' => ServiceType::orderBy('name')->get(),
        ]);
    }

    public function create(Request $request): View
    {
        if ($request->ajax()) {
            return $this->modalForm(
                'Create Service',
                'services._form',
                $this->formData(new ChurchService),
                route('services.store'),
                '#services-fragment',
            );
        }

        return view('services.create', $this->formData(new ChurchService));
    }

    public function store(Request $request): JsonResponse|RedirectResponse
    {
        $data = $this->validatedData($request);
        $data['created_by'] = $this->actingUser()?->id;
        $service = ChurchService::create($data);
        $this->logActivity('created', 'services', "Created service {$service->name}");

        return $this->saveResponse($request, 'Service/Event imetengenezwa.', 'services.index', [], '#services-fragment');
    }

    public function show(ChurchService $service): View
    {
        $service->load(['serviceType', 'attendanceRecords.member.jumuiya', 'sacramentRecords.member']);

        return view('services.show', compact('service'));
    }

    public function edit(Request $request, ChurchService $service): View
    {
        if ($request->ajax()) {
            return $this->modalForm(
                'Edit Service',
                'services._form',
                $this->formData($service),
                route('services.update', $service),
                '#services-fragment',
                'PUT',
            );
        }

        return view('services.edit', $this->formData($service));
    }

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

        return $this->saveResponse($request, 'Service/Event imeboreshwa.', 'services.index', [], '#services-fragment');
    }

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

        return $this->backResponse($request, 'Service/Event imefutwa.', '#services-fragment');
    }

    private function formData(ChurchService $service): array
    {
        return [
            'service' => $service,
            'serviceTypes' => ServiceType::where('status', 'active')->orderBy('name')->get(),
        ];
    }

    private function validatedData(Request $request): array
    {
        return $request->validate([
            'service_type_id' => ['nullable', 'exists:service_types,id'],
            'name' => ['required', 'string', 'max:255'],
            'service_date' => ['required', 'date'],
            'start_time' => ['nullable', 'date_format:H:i'],
            'end_time' => ['nullable', 'date_format:H:i'],
            'location' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'status' => ['required', 'in:open,closed'],
        ]);
    }
}
