<?php

namespace App\Jobs\Dashboard\Product;

use App\Http\Requests\Dashboard\Product\Update as Request;
use App\Models\Product;

class Update
{
    protected $attr;
    protected $request;
    protected $product;

    /**
     * @param Product $product
     * @param Request $request
     */
    public function __construct(Product $product, Request $request)
    {
        $this->product = $product;
        $this->request = $request;
    }

    /**
     * @return Product
     */
    public function handle()
    {
        $this->product->update([
            'name' => $this->request->getName(),
            'brand_id' => $this->request->getBrandID(),
            'measurement_id' => $this->request->getMeasurementId(),
            'currency' => $this->request->currency,
            'is_ready_solution' => $this->request->is_ready_solution == 'false' ? 0 : 1,
            'price' => $this->request->getPrice(),
            'price_discount' => $this->request->getPriceDiscount(),
            'poster' => $this->request->getPoster($this->product),
            'calc' => $this->request->getCalc($this->product),
            'poster_thumb' => $this->request->getPosterThumb($this->product),
            'data_sheet' => $this->request->getDataSheet($this->product),
            'body' => $this->request->getBody(),
            'short_body' => $this->request->short_body,
            'power' => !in_array($this->request->power, [null, 'null', 'NULL']) ? $this->request->power : null,
            'slug' => $this->request->getSlug(),
            'published' => $this->request->getPublished(),
            // 'popular' => $this->request->getPopular(),
            'leader_of_sales' => $this->request->getLeaderOfSales(),
            'article_number' => $this->request->article_number,
            'count' => $this->request->count,
            'available' => $this->request->getAvailable(),
            'keywords' => $this->request->keywords,
            'descriptions' => $this->request->descriptions,
            'title_seo' => $this->request->title_seo,
        ]);

        $this->syncCategories();
    }

    private function syncCategories()
    {
        $cats = $this->product->categories()->get();

        $cats = array_map(function ($cat) {
            return $cat['id'];
        }, $cats->toArray());

        $this->product->categories()->detach($cats);
        $this->product->categories()->attach([$this->request->getCategoryID()]);
    }
}
