<?php

namespace Modules\Store\Repositories;

use App\Traits\UploadMedia;
use Modules\Store\Entities\ProductPublication;


class PublicationRepository extends BaseRepository
{
    use UploadMedia;


    public function model()
    {
        return ProductPublication::class;
    }

    function getAll()
    {
        return $this->model->all();
    }

    function store($request)
    {
        try {
            $publication = new $this->model();
            if (isModuleActive('FrontendMultiLang')) {
                foreach ($request->name as $key => $name) {
                    $publication->setTranslation('name', $key, $name);
                }
                foreach ($request->description as $key => $description) {
                    $publication->setTranslation('description', $key, $description);
                }
            } else {
                $publication->name = $request->name;
                $publication->description = $request->description;
            }

            $publication->status = 1;

            $publication->save();

            if ($request->logo) {
                $publication->logo = $this->generateLink($request->logo, $publication->id, get_class($publication), 'logo');
            }
            $publication->save();

            return true;
        } catch (\Throwable $th) {
            return false;
        }
    }

    function update($request)
    {
        try {
            $publication = $this->model->find($request->id);
            if (isModuleActive('FrontendMultiLang')) {
                foreach ($request->name as $key => $name) {
                    $publication->setTranslation('name', $key, $name);
                }
                foreach ($request->description as $key => $description) {
                    $publication->setTranslation('description', $key, $description);
                }
            } else {
                $publication->name = $request->name;
                $publication->description = $request->description;
            }
            $publication->logo = null;
            $publication->save();

            if ($request->logo) {
                $publication->logo = $this->generateLink($request->logo, $publication->id, get_class($publication), 'logo');
            }
            $publication->save();
            return true;
        } catch (\Throwable $th) {
            return false;
        }
    }

    function destroy($id)
    {
        try {
            $unit = $this->model->find($id);
            $unit->delete();
            return true;
        } catch (\Throwable $th) {

            return false;
        }
    }
}
