<?php

namespace App\Services;

use App\Repositories\LearningProduct;

class LearningProductService
{
    private $learningProductRepository;

    public function __construct(LearningProduct $learningProductRepository)
    {
        $this->learningProductRepository = $learningProductRepository;
    }

    public function save(array $data)
    {
        if (isset($data['id'])) {
            $learningProduct = $this->learningProductRepository
                ->withTrashed()
                ->findOrFail($data['id']);
            $learningProduct->update($data);
        } else {
            $learningProduct = $this->learningProductRepository->create($data);
        }

        return $learningProduct;
    }

    public function delete($id, $forceDelete = false)
    {
        $learningProduct = $this->learningProductRepository->withTrashed()->findOrFail($id);

        if ($forceDelete || $learningProduct->deleted_at) {
            return $learningProduct->forceDelete($id);
        }

        return $learningProduct->delete();
    }

    public function get($id)
    {
        return $this->learningProductRepository->withTrashed()->findOrFail($id);
    }

    public function getAll()
    {
        return $this->learningProductRepository->withTrashed()->get();
    }

    public function getPublishedWith(array $children)
    {
        return $this->learningProductRepository->with($children)->where('published', 1)->get();
    }

    public function with(array $children)
    {
        return $this->learningProductRepository->with($children)->get();
    }

    public function withTrashedAndChildren(array $children)
    {
        return $this->learningProductRepository->with($children)->withTrashed()->get();
    }

    public function getOneWith($id, array $children)
    {
        return $this->learningProductRepository->with($children)->findOrFail($id);
    }

    public function getOneWithChildrenAndTrashed($id, array $children)
    {
        return $this->learningProductRepository
        ->with($children)
        ->withTrashed()
        ->findOrFail($id);
    }

    public function getDraftId($id)
    {
        return $this->learningProductRepository->where('parent_id', $id);
    }

    public function countAll()
    {
        return $this->learningProductRepository->where('published', true)->get()->count();
    }

    public function scopeForMembers($query)
    {
        return $query->where('for_members', true);
    }
}
