<?php

namespace App\Http\Controllers;

use App\Models\Family;
use App\Models\Relationship;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class FamilyRelationshipController extends Controller
{
    public function index(Request $request, Family $family)
    {
        $this->authorizeMember($request, $family);

        $canManage = $this->canManage($request, $family);
        $members = $family->members()
            ->select('people.id', 'first_name', 'last_name')
            ->orderBy('first_name')
            ->get()
            ->map(fn($p) => [
                'id' => $p->id,
                'name' => trim(($p->first_name ?? '') . ' ' . ($p->last_name ?? '')) ?: 'Member',
            ]);

        $relationships = Relationship::where('family_id', $family->id)
            ->with(['person', 'relatedPerson'])
            ->latest('id')
            ->paginate(20);

        $prefill = [
            'person_id' => (string) $request->query('person_id', ''),
            'related_person_id' => (string) $request->query('related_person_id', ''),
            'type' => (string) $request->query('type', ''),
        ];

        return view('families.relationships.index', compact('family', 'members', 'relationships', 'canManage', 'prefill'));
    }

    public function store(Request $request, Family $family)
    {
        $this->authorizeManage($request, $family);

        $data = $request->validate([
            'person_id' => ['required', 'integer', 'exists:people,id'],
            'related_person_id' => ['required', 'integer', 'different:person_id', 'exists:people,id'],
            'type' => ['required', Rule::in(['parent', 'child', 'spouse', 'sibling', 'guardian', 'ward', 'other'])],
            'start_date' => ['nullable', 'date'],
            'end_date' => ['nullable', 'date', 'after_or_equal:start_date'],
            'notes' => ['nullable', 'string'],
        ]);

        // Ensure both people are members of this family
        $memberIds = $family->members()->pluck('people.id')->map(fn($id) => (int) $id)->all();
        $validPair = in_array((int) $data['person_id'], $memberIds, true)
            && in_array((int) $data['related_person_id'], $memberIds, true);
        abort_unless($validPair, 422, 'Both people must be members of this family.');

        Relationship::create([
            'family_id' => $family->id,
            'person_id' => $data['person_id'],
            'related_person_id' => $data['related_person_id'],
            'type' => $data['type'],
            'start_date' => $data['start_date'] ?? null,
            'end_date' => $data['end_date'] ?? null,
            'notes' => $data['notes'] ?? null,
        ]);

        return redirect()->route('families.relationships.manage.index', $family)->with('status', 'Relationship added.');
    }

    public function destroy(Request $request, Family $family, Relationship $relationship)
    {
        $this->authorizeManage($request, $family);
        abort_unless($relationship->family_id === $family->id, 404);

        $relationship->delete();

        return redirect()->route('families.relationships.manage.index', $family)->with('status', 'Relationship removed.');
    }

    private function authorizeMember(Request $request, Family $family): void
    {
        $user = $request->user();
        $isMember = $user && $family->members()->where('people.user_id', $user->id)->exists();
        abort_unless($isMember, 403);
    }

    private function authorizeManage(Request $request, Family $family): void
    {
        $user = $request->user();
        $isOwner = $user && $family->members()
            ->wherePivot('role', 'owner')
            ->where('people.user_id', $user->id)
            ->exists();

        abort_unless($user && ($user->can('relationships.manage') || $isOwner), 403);
    }

    private function canManage(Request $request, Family $family): bool
    {
        $user = $request->user();
        $isOwner = $user && $family->members()
            ->wherePivot('role', 'owner')
            ->where('people.user_id', $user->id)
            ->exists();

        return $user && ($user->can('relationships.manage') || $isOwner);
    }
}
