<?php

namespace Inside\BCLH\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Inside\Content\Models\Model;
use Inside\Host\Bridge\BridgeContent;
use Inside\Workflow\Facades\Workflow;

/**
 * Bulk update job
 *
 * @category Class
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class BulkUpdate implements ShouldQueue
{
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var string
     */
    protected $contentType;

    /**
     * @var array
     */
    protected $data;

    public function __construct(string $contentType, array $data)
    {
        $this->contentType = $contentType;
        $this->data = $data;
    }

    public function handle(): void
    {
        $bridge = new BridgeContent();

        $content = call_user_func(type_to_class($this->contentType).'::find', $this->data['uuid']);

        if ($content) {
            $this->data['langcode'] = $content->langcode;

            $referenceFields = ['brands', 'countries', 'management_modes', 'profiles'];
            foreach ($referenceFields as $referenceField) {
                foreach ($this->data[$referenceField] as &$referenceUuid) {
                    $reference = call_user_func(type_to_class($referenceField).'::find', $referenceUuid);

                    if ($reference->langcode !== $content->langcode) {
                        $reference = $reference->getTranslationIfExists($content->langcode);
                        $referenceUuid = $reference->uuid;
                    }
                }
            }

            $this->data['status'] = $content->status;
            $this->data['author'] = $content->author;

            Workflow::disableWorkflow();
            $bridge->contentUpdate($this->contentType, $this->data, true, true);
            Workflow::enableWorkflow();
        }

        $this->delete();
    }
}
