<?php

namespace App\Http\Controllers;

use App\Models\CurrencyExchange;
use App\Models\Saraf;
use App\Models\SarafPayment;
use App\Support\SarafAccountLedger;
use Inertia\Inertia;
use Inertia\Response;

class SarafAccountController extends Controller
{
    public function show(Saraf $saraf): Response
    {
        $exchanges = CurrencyExchange::query()
            ->where('saraf_id', $saraf->id)
            ->orderByDesc('exchange_date')
            ->orderByDesc('id')
            ->get()
            ->map(fn (CurrencyExchange $exchange): array => SarafAccountLedger::exchangeDetailPayload($exchange))
            ->values()
            ->all();

        $payments = SarafPayment::query()
            ->where('saraf_id', $saraf->id)
            ->with(['currencyExchange', 'allocations.currencyExchange'])
            ->orderByDesc('paid_at')
            ->orderByDesc('id')
            ->get()
            ->map(fn (SarafPayment $payment): array => SarafAccountLedger::paymentDetailPayload($payment))
            ->values()
            ->all();

        return Inertia::render('sarafi/sarafs/account', [
            'saraf' => [
                'id' => $saraf->id,
                'name' => $saraf->name,
                'address' => $saraf->address,
                'contact_number' => $saraf->contact_number,
                'is_active' => $saraf->is_active,
            ],
            'summary' => SarafAccountLedger::summary($saraf),
            'exchanges' => $exchanges,
            'payments' => $payments,
        ]);
    }
}
