<?php

namespace App\Support;

use Carbon\Carbon;
use App\Services\LotterySettings;
use Illuminate\Database\Eloquent\Builder;

/**
 * 注项列表共用筛选：号码/订单号搜索、按开奖时区日界筛选下单时间。
 */
trait TicketItemListFilters
{
    protected function applyTicketItemNumberSearch(Builder $query, string $number): void
    {
        $number = trim($number);
        if ($number === '') {
            return;
        }

        $query->where(function (Builder $q) use ($number): void {
            $q->where('ticket_items.original_number', 'like', '%'.$number.'%')
                ->orWhere('ticket_items.normalized_number', 'like', '%'.$number.'%')
                ->orWhere('ticket_items.ticket_no', 'like', '%'.$number.'%')
                ->orWhereHas('order', fn (Builder $order) => $order->where('order_no', 'like', '%'.$number.'%'));
        });
    }

    protected function applyOrderPlacedDateRange(Builder $query, ?string $startDate, ?string $endDate): void
    {
        if (is_string($startDate) && $startDate !== '') {
            $fromUtc = $this->scheduleDateStartUtc($startDate);
            $query->whereHas('order', fn (Builder $q) => $q->where('created_at', '>=', $fromUtc));
        }

        if (is_string($endDate) && $endDate !== '') {
            $toUtc = $this->scheduleDateEndUtc($endDate);
            $query->whereHas('order', fn (Builder $q) => $q->where('created_at', '<=', $toUtc));
        }
    }

    private function scheduleTimezone(): string
    {
        return LotterySettings::drawTimezone();
    }

    private function scheduleDateStartUtc(string $ymd): Carbon
    {
        return Carbon::createFromFormat('Y-m-d', $ymd, $this->scheduleTimezone())
            ->startOfDay()
            ->utc();
    }

    private function scheduleDateEndUtc(string $ymd): Carbon
    {
        return Carbon::createFromFormat('Y-m-d', $ymd, $this->scheduleTimezone())
            ->endOfDay()
            ->utc();
    }
}
