<?php

namespace App\Modules\Bills\Repositories;

use App\Core\Repositories\BaseRepository;
use App\Models\BillService;
use App\Models\BillVariation;
use App\Modules\Bills\Interfaces\BillServiceRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;

class BillServiceRepository extends BaseRepository implements BillServiceRepositoryInterface
{
    public function __construct(BillService $model)
    {
        parent::__construct($model);
    }

    public function allActive(): Collection
    {
        return $this->model->active()->orderBy('sort_order')->get();
    }

    public function findByCategory(string $category): Collection
    {
        return $this->model->active()->category($category)->orderBy('sort_order')->get();
    }

    public function findBySlug(string $slug): ?BillService
    {
        return $this->model->where('slug', $slug)->first();
    }

    public function findByCode(string $code): ?BillService
    {
        return $this->model->where('code', $code)->first();
    }

    public function getVariations(string $serviceId): Collection
    {
        return BillVariation::where('bill_service_id', $serviceId)
            ->active()
            ->orderBy('sort_order')
            ->get();
    }

    public function getVariationByCode(string $code): ?BillVariation
    {
        return BillVariation::where('code', $code)->first();
    }

    public function createService(array $data): BillService
    {
        return $this->model->create($data);
    }

    public function updateService(string $id, array $data): BillService
    {
        $service = $this->findOrFail($id);
        $service->update($data);
        return $service->fresh();
    }

    public function createVariation(array $data): BillVariation
    {
        return BillVariation::create($data);
    }

    public function updateVariation(string $id, array $data): BillVariation
    {
        $variation = BillVariation::findOrFail($id);
        $variation->update($data);
        return $variation->fresh();
    }
}
