<?php

namespace App\Support;

use App\Models\Sale;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class SaleInvoiceMetrics
{
    public static function invoiceRows(?Builder $query = null): Builder
    {
        $query ??= Sale::query();

        return $query->whereIn('sales.id', function ($sub) {
            $sub->from('sales')
                ->selectRaw('MIN(id)')
                ->groupBy('invoice_no');
        });
    }

    public static function sumGrandTotal(?Builder $query = null): float
    {
        return (float) self::invoiceRows($query)->sum('invoice_grand_total');
    }

    public static function sumDue(?Builder $query = null): float
    {
        return (float) self::invoiceRows($query)->sum('due_amount');
    }

    public static function countDueInvoices(?Builder $query = null): int
    {
        return (int) self::invoiceRows($query)->where('due_amount', '>', 0)->count();
    }

    public static function invoiceQueryByDateRange(string $from, string $to): Builder
    {
        return self::invoiceRows(
            Sale::query()->whereBetween('sale_date', [$from, $to])
        );
    }

    public static function dailyGrandTotals(string $from, string $to)
    {
        return self::invoiceRows(
            Sale::query()
                ->select('sale_date', DB::raw('SUM(invoice_grand_total) as amount'))
                ->whereBetween('sale_date', [$from, $to])
                ->groupBy('sale_date')
                ->orderBy('sale_date')
        )->get();
    }
}
