<?php

namespace App\Http\Controllers;

use App\Http\Requests\CustomerLedgerReportRequest;
use App\Models\Customer;
use App\Support\CashSaleCustomer;
use App\Support\CustomerLedgerReport;
use Inertia\Inertia;
use Inertia\Response;

class CustomerLedgerReportController extends Controller
{
    public function index(CustomerLedgerReportRequest $request): Response
    {
        $filters = $request->filters();
        $report = CustomerLedgerReport::build($filters);

        $customers = Customer::query()
            ->tap(fn ($query) => CashSaleCustomer::applyRegisteredScope($query))
            ->orderBy('full_name')
            ->get(['id', 'full_name'])
            ->map(fn (Customer $customer): array => [
                'id' => $customer->id,
                'full_name' => $customer->full_name,
            ])
            ->values()
            ->all();

        return Inertia::render('customers/ledger', [
            'customers' => $customers,
            'filters' => [
                'customer_id' => $filters['customer_id'],
                'date_from' => $filters['date_from'],
                'date_to' => $filters['date_to'],
                'payment_group' => $filters['payment_group'],
            ],
            'paymentGroups' => CustomerLedgerReport::paymentGroupValues(),
            'summary' => $report['summary'],
            'purchases' => $report['purchases'],
            'payments' => $report['payments'],
            'payment_group' => $report['payment_group'],
        ]);
    }
}
