<?php

namespace App\Services\Admin;

use Illuminate\Support\Facades\DB;

/** 站点信用账期账单摘要（待确认 / 待收付）。 */
final class SiteSettlementBillStats
{
    /**
     * @return array{
     *     pending_confirm_count: int,
     *     payable_count: int,
     *     payable_unpaid_minor: int
     * }
     */
    public static function forSite(int $siteId): array
    {
        $pendingConfirmQuery = DB::table('settlement_bills as sb')
            ->join('settlement_periods as sp', 'sp.id', '=', 'sb.settlement_period_id')
            ->where('sp.admin_site_id', $siteId)
            ->where('sb.status', 'pending_confirm');

        $payableQuery = DB::table('settlement_bills as sb')
            ->join('settlement_periods as sp', 'sp.id', '=', 'sb.settlement_period_id')
            ->where('sp.admin_site_id', $siteId)
            ->whereIn('sb.status', ['confirmed', 'partial_paid', 'overdue'])
            ->where('sb.unpaid_amount', '>', 0);

        return [
            'pending_confirm_count' => (int) (clone $pendingConfirmQuery)->count(),
            'payable_count' => (int) (clone $payableQuery)->count(),
            'payable_unpaid_minor' => (int) (clone $payableQuery)->sum('sb.unpaid_amount'),
        ];
    }
}
