<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\TransactionOnline;

class BayaranOnlineDetailController extends Controller
{

    public function __invoke(Request $request)
    {

        $transactionOnlineQuery = TransactionOnline::filter($request);

        $formatMoney = fn($x) => number_format($x, 2, '.', ',');

        $sumTotalPayments = (clone $transactionOnlineQuery)->sum('total_payment');
        $sumTotalPayments = $formatMoney($sumTotalPayments);
        $sumPaymentNos = (clone $transactionOnlineQuery)->count('total_payment');

        $transactions = (clone $transactionOnlineQuery)->select('nokp', 'customer_name', 'norujukan', 'reference_no', 'kodcaw', 'total_payment', 'tarikh', 'masa', 'status')
            ->get()
            ->groupBy('nokp')
            ->map(fn($x) => $x->groupBy('cawangan.details_caw'))
            ->map(function ($cawangan) {

                $all_entries = $cawangan->collapse();

                $first = $all_entries->first();

                $payment_details = $cawangan->map(function ($cawangan_payments) {
                    return [
                        'paymentNos' => $cawangan_payments->count(),
                        'paymentSum' => $cawangan_payments->sum('total_payment'),
                        'paymentDetails' => $cawangan_payments->map(function ($x) {

                            $payment_details = collect($x)->except('nokp', 'customer_name', 'kodcaw', 'cawangan');

                            return $payment_details;
                        }),
                    ];
                });

                return [
                    'customer_name' => $first->customer_name,
                    'nokp' => $first->nokp,
                    'payments' => $payment_details,
                ];
            })
            ->values();


        return response()->json([
            'sumTotalPayments' => $sumTotalPayments,
            'sumPaymentNos' => $sumPaymentNos,
            'transactions' => $transactions,
        ]);
    }
}
