<?php

namespace Modules\Store\Repositories;

use App\Traits\UploadMedia;
use Illuminate\Http\Request;
use Modules\Store\Entities\ProductBrand;
use Modules\Store\interfaces\CrudInterface;

class ProductBrandRepository implements CrudInterface
{
    use UploadMedia;

    public function create(Request $request)
    {
        try {
            $brand = new ProductBrand();

            if (isModuleActive('FrontendMultiLang')) {
                foreach ($request->name as $key => $name) {
                    $brand->setTranslation('name', $key, $name);
                }
            } else {
                $brand->name = $request->name;
            }

            if (isModuleActive('FrontendMultiLang')) {
                foreach ($request->description as $key => $description) {
                    $brand->setTranslation('description', $key, $description);
                }
            } else {
                $brand->description = $request->description;
            }
            $brand->link = $request->link;
            $brand->status = 1;
            $brand->featured = $request->featured == 'on' ? 1 : 0;


            $brand->meta_title = $request->meta_title;
            $brand->meta_description = $request->meta_description;
            $brand->save();

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

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

    public function delete($id)
    {

        $brand = ProductBrand::find($id)->delete();
        return $brand;
    }

    public function update(Request $request)
    {
        $brand = ProductBrand::find($request->id);


        if (isModuleActive('FrontendMultiLang')) {
            foreach ($request->name as $key => $name) {
                $brand->setTranslation('name', $key, $name);
            }
        } else {
            $brand->name = $request->name;
        }

        if (isModuleActive('FrontendMultiLang')) {
            foreach ($request->description as $key => $description) {
                $brand->setTranslation('description', $key, $description);
            }
        } else {
            $brand->description = $request->description;
        }
        $brand->link = $request->link;
        $brand->featured = $request->featured == 'on' ? 1 : 0;

        $brand->meta_title = $request->meta_title;
        $brand->meta_description = $request->meta_description;
        $brand->logo = null;

        $brand->save();


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