<?php

namespace App\Http\Controllers;

use App\Http\Requests\SaveAjoGroupRequest;
use App\Models\AjoGroup;
use App\Models\Member;
use App\Support\CurrentBusiness;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class AjoGroupController extends Controller
{
    public function index(): View
    {
        $this->authorize('viewAny', AjoGroup::class);
        $groups = AjoGroup::withCount('members')->latest()->paginate(15);

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

    public function create(): View
    {
        $this->authorize('create', AjoGroup::class);

        return $this->form(new AjoGroup);
    }

    public function store(SaveAjoGroupRequest $request): RedirectResponse
    {
        $group = AjoGroup::create($this->payload($request));
        $this->syncMembers($group, $request->validated('member_ids', []));

        return to_route('groups.index')->with('status', 'Group created successfully.');
    }

    public function edit(AjoGroup $group): View
    {
        $this->authorize('update', $group);

        return $this->form($group);
    }

    public function update(SaveAjoGroupRequest $request, AjoGroup $group): RedirectResponse
    {
        $group->update($this->payload($request));
        $this->syncMembers($group, $request->validated('member_ids', []));

        return to_route('groups.index')->with('status', 'Group updated successfully.');
    }

    public function destroy(AjoGroup $group): RedirectResponse
    {
        $this->authorize('delete', $group);
        $group->delete();

        return to_route('groups.index')->with('status', 'Group archived.');
    }

    private function payload(SaveAjoGroupRequest $request): array
    {
        $data = $request->validated();
        unset($data['member_ids']);
        $data['contribution_amount'] = (int) round(((float) $data['contribution_amount']) * 100);

        return $data;
    }

    private function form(AjoGroup $group): View
    {
        $group->loadMissing('members:id');

        return view('groups.form', ['group' => $group, 'members' => Member::where('is_active', true)->orderBy('full_name')->get(['id', 'full_name', 'member_number'])]);
    }

    private function syncMembers(AjoGroup $group, array $memberIds): void
    {
        $group->members()->syncWithPivotValues($memberIds, ['business_id' => app(CurrentBusiness::class)->id(), 'joined_at' => today(), 'status' => 'active']);
    }
}
