<?php

namespace App\QueryBuilders;

use App\TransactionOnline;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class TransactionOnlineBuilder extends Builder
{
    public function filter(Request $request)
    {
        return $this->with('cawangan')
            ->whereDatePaidBetween($request)
            ->when($request->filled('kodcaw'), fn($query) => $query->whereCawanganCode($request->kodcaw))
            ->when($request->filled('status'), fn($query) => $query->whereStatus($request->status))
            ->when($request->isNotFilled('status'), fn($query) => $query->whereStatus('PAID'))
            ->when($request->filled('orderBy'), fn($query) => $query->orderByColumn($request->orderBy));
    }

    public function whereDatePaidBetween(Request $request): self
    {
        $startDate = $request->filled('startDate') ?
            Carbon::parse($request->startDate)->startOfDay() :
            Carbon::now()->startOfDay();

        $endDate = $request->filled('endDate') ?
            Carbon::parse($request->endDate)->endOfDay() :
            Carbon::now()->endOfDay();

        return $this->whereBetween('paid_at', [$startDate, $endDate]);
    }

    public function whereCawanganCode(string $kodcaw): self
    {
        return $this->where('kodcaw', $kodcaw);
    }

    public function whereStatus(string $status): self
    {
        return $this->where('status', $status);
    }

    public function orderByColumn(string $orderBy): self
    {
        return $this->orderBy($orderBy, 'desc');
    }
}
