<?php

namespace App\Http\Controllers\Api\V1\Admin\AgentSettlement;

use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\PaginationTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Support\AdminAgentSettlementScope;

final class AgentSettlementPaymentIndexController extends Controller
{
    use PaginationTrait;

    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $periodId = (int) $request->query('settlement_period_id', 0);
        $adminSiteId = (int) $request->query('admin_site_id', 0);

        $query = DB::table('payment_records as pr')
            ->join('settlement_bills as sb', 'sb.id', '=', 'pr.settlement_bill_id')
            ->join('settlement_periods as sp', 'sp.id', '=', 'sb.settlement_period_id')
            ->select([
                'pr.*',
                'sb.bill_type',
                'sb.owner_type',
                'sb.owner_id',
                'sb.counterparty_type',
                'sb.counterparty_id',
                'sp.period_start',
                'sp.period_end',
                'sp.admin_site_id',
            ])
            ->orderByDesc('pr.id');

        if ($periodId > 0) {
            $query->where('sb.settlement_period_id', $periodId);
        }

        if ($adminSiteId > 0) {
            $query->where('sp.admin_site_id', $adminSiteId);
        }

        $siteIds = $admin->accessibleAdminSiteIds();
        if ($siteIds !== null) {
            if ($siteIds === []) {
                $query->whereRaw('0 = 1');
            } else {
                $query->whereIn('sp.admin_site_id', $siteIds);
            }
        }

        AdminAgentSettlementScope::applyDirectEdgeScopeToBillsQuery($query, $admin, 'sb');

        $meta = $this->paginationMeta($request, defaultPerPage: 20, maxPerPage: 200);
        $paginator = $query->paginate($meta['per_page'], ['pr.*', 'sb.bill_type', 'sb.owner_type', 'sb.owner_id', 'sb.counterparty_type', 'sb.counterparty_id', 'sp.period_start', 'sp.period_end', 'sp.admin_site_id'], 'page', $meta['page']);

        return ApiResponse::success([
            'items' => $paginator->items(),
            'total' => $paginator->total(),
            'page' => $paginator->currentPage(),
            'per_page' => $paginator->perPage(),
            'last_page' => $paginator->lastPage(),
        ]);
    }
}
