<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\TransactionOnline;

class BayaranOnlineController 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);
        $nosPayments = (clone $transactionOnlineQuery)->count('total_payment');

        $transactions = (clone $transactionOnlineQuery)->select('kodcaw', DB::raw('sum(total_payment) as totalCawanganPayment'), DB::raw('count(reference_no) as totalReferenceNo'))
            ->groupBy('kodcaw')
            ->get()
            ->map(function($x) use($formatMoney) {
               $x['totalCawanganPayment'] = $formatMoney($x['totalCawanganPayment']);
               return $x; 
            });
        
        return response()->json([
            'nosPayments' => $nosPayments,
            'sumTotalPayments' => $sumTotalPayments,
            'transactions' => $transactions,
        ]);
    }
}
