<?php

namespace App\Repos;

use App\Models\Subscription;
use Illuminate\Support\Carbon;

class SubscriptionRepo
{
    public static function paginate(int $page, string|null $search)
    {
        $query = Subscription::with(['user', 'plan']);
        if ($search) {
            $query = $query->where(function ($query) use ($search) {
                $query->where('price', 'like', "%$search%")
                    ->orWhereHas('plan', function ($planQuery) use ($search) {
                        $planQuery->where('title', 'like', "%$search%");
                    })
                    ->orWhereHas('user', function ($userQuery) use ($search) {
                        $userQuery->where('email', 'like', "%$search%");
                        $userQuery->orWhere('stripe_id', 'like', "%$search%");
                    });
            });
        } else {
            $query = $query->latest();
        }
        return $query->paginate(18, ['*'], 'page', $page);
    }

    public static function countActive()
    {
        return Subscription::whereNull('canceled_at')->count();
    }

    public static function countActiveBetweenDate(Carbon $start, Carbon $end)
    {
        return Subscription::whereNull('canceled_at')
            ->whereBetween('created_at', [$start, $end])
            ->count();
    }

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

    public static function create(array $subscription)
    {
        return Subscription::create($subscription);
    }

    public static function updateByIdOrFail(int $id, array $data)
    {
        $subscription = Subscription::findOrFail($id);
        $subscription->update($data);
        return $subscription->fresh();
    }

    public static function updateByStripeIdOrFail(string $stripeId, array $data)
    {
        $subscription = Subscription::where('stripe_id', $stripeId)
            ->firstOrFail();
        $subscription->update($data);
        return $subscription->fresh();
    }

    public static function createOrUpdateByStripeId(string $stripeId, array $data)
    {
        $subscription = Subscription::where('stripe_id', $stripeId)->first();
        if ($subscription) {
            $subscription->update($data);
            return $subscription->fresh();
        }
        return Subscription::create($data);
    }
}
