<?php

namespace Modules\News\Repositories;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\News\Interfaces\NewsRepositoryInterface;
use Modules\News\Models\News;
use Modules\News\Models\NewsDescription;

class NewsRepository implements NewsRepositoryInterface
{
    public function get(array $request)
    {
        return News::query()
            ->join('news_descriptions as nd', 'news.id', 'nd.news_id')
            ->join('languages', 'languages.id', 'nd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['news.*', 'nd.title', 'nd.description']);
    }

    public function getItem(int $id)
    {
        return NewsDescription::where('news_id', $id)
            ->join('languages', 'languages.id', 'news_descriptions.language_id')
            ->join('news', 'news.id', 'news_descriptions.news_id')
            ->select(['news_descriptions.*', 'languages.local', 'news.*'])
            ->get();
    }

    public function checkItem(int $id)
    {
        return News::find($id);
    }

    public function getItemTrashed(int $id)
    {
        return News::onlyTrashed()->find($id);
    }

    public function create(array $request): News
    {
        return News::create($request);
    }

    public function update(array $request, News $news): News
    {
        $news->update($request);
        return $news;
    }

    public function saveData(array $request, int $newsId): void
    {
        NewsDescription::where('news_id', $newsId)->delete();

        foreach (languages() as $lang) {
            NewsDescription::create([
                'news_id' => $newsId,
                'language_id' => $lang->id,
                'title' => $request['title_' . $lang->local] ?? null,
                'description' => $request['description_' . $lang->local] ?? null,
            ]);
        }
    }

    public function destroy(News $news): void
    {
        $news->delete();
    }

    public function destroyAll(array $ids): void
    {
        News::whereIn('id', $ids)->delete();
    }

    public function restore(News $news): void
    {
        $news->restore();
    }

    public function restoreAll(array $ids): void
    {
        News::onlyTrashed()->whereIn('id', $ids)->restore();
    }

    public function forceDelete(News $news): void
    {
        $news->forceDelete();
    }

    public function forceDeleteAll(array $ids): void
    {
        News::onlyTrashed()->whereIn('id', $ids)->forceDelete();
    }
}
