<?php

namespace App\Http\Controllers;

use App\Models\Owner;
use App\Models\OwnerTree;
use Illuminate\Http\Request;
use Inertia\Inertia;

class OwnerTreeController extends Controller
{
    public function index()
    {
        $trees = OwnerTree::with(['owners.shops.activeLease', 'owners.ownerPayments'])
            ->get()
            ->map(function ($tree) {
                $totalMonthly = 0;
                $totalCollected = 0;
                $totalPaidToOwners = 0;

                foreach ($tree->owners as $owner) {
                    $totalPaidToOwners += $owner->ownerPayments->sum('total_amount');

                    foreach ($owner->shops as $shop) {
                        if ($shop->activeLease) {
                            $totalMonthly += (float) $shop->activeLease->agreed_rent;
                        }
                    }
                }

                return [
                    'id' => $tree->id,
                    'name' => $tree->name,
                    'owners' => $tree->owners->map(fn($o) => [
                        'id' => $o->id,
                        'name' => $o->name,
                    ]),
                    'total_monthly' => $totalMonthly,
                    'total_yearly' => $totalMonthly * 12,
                    'total_paid_to_owners' => (float) $totalPaidToOwners,
                ];
            });

        $owners = Owner::orderBy('name')->get(['id', 'name']);

        return Inertia::render('Reports/OwnerTree', [
            'trees' => $trees,
            'owners' => $owners,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'owner_ids' => 'required|array|min:1',
            'owner_ids.*' => 'exists:owners,id',
        ]);

        $tree = OwnerTree::create(['name' => $request->name]);
        $tree->owners()->attach($request->owner_ids);

        return redirect()->route('reports.owner-tree')->with('success', 'Owner tree created successfully.');
    }

    public function update(Request $request, OwnerTree $ownerTree)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'owner_ids' => 'required|array|min:1',
            'owner_ids.*' => 'exists:owners,id',
        ]);

        $ownerTree->update(['name' => $request->name]);
        $ownerTree->owners()->sync($request->owner_ids);

        return redirect()->route('reports.owner-tree')->with('success', 'Owner tree updated successfully.');
    }

    public function destroy(OwnerTree $ownerTree)
    {
        $ownerTree->delete();

        return redirect()->route('reports.owner-tree')->with('success', 'Owner tree deleted successfully.');
    }
}
