<?php

namespace App\Repos;

use App\Models\Colored;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;

class ColoredRepo
{
    public static function count()
    {
        return Colored::count();
    }

    public static function countBetweenDate(Carbon $start, Carbon $end)
    {
        return Colored::whereBetween('created_at', [$start, $end])
            ->count();
    }

    public static function paginate(
        int $page,
        string|null $search,
    ) {
        $query = Colored::with(['user', 'page']);
        if ($search) {
            $query = $query->where(function (Builder $query) use ($search) {
                $query->orWhereHas('user', function ($userQuery) use ($search) {
                    $userQuery->where('name', 'like', "%$search%")
                        ->orWhere('stripe_id', 'like', "%$search%");
                })
                    ->orWhereHas('page', function ($userQuery) use ($search) {
                        $userQuery->where('prompt', 'like', "%$search%");
                    });
            });
        } else {
            $query->latest();
        }
        return $query->paginate(18, ['*'], 'page', $page);
    }

    public static function dailyCountBetweenDate(Carbon $start, Carbon $end)
    {
        return Colored::dailyCountBetweenDate($start, $end)
            ->get();
    }

    public static function updateOrCreateByUserIdAndPageId(int $userId, int $pageId, $colored)
    {
        $where = ['user_id' => $userId, 'page_id' => $pageId];
        return Colored::updateOrCreate($where, $colored);
    }
}
