<?php

namespace Hilco\Models;

use Blade;
use Exception;
use Flynsarmy\DbBladeCompiler\Facades\DbView;
use Storage;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Illuminate\Support\Str;
use Throwable;

trait HasLandingPage {
    public function webAttributeFilters() {
        return $this->morphMany(WebAttributeFilter::class, 'filterable')
            ->has('webAttribute')
            ->with('webAttribute', 'webAttributeFilterValues')
        ;
    }

    public function getFeaturedChildrenAttribute() {
        return collect();
    }

    public function getChildrenAttribute() {
        return collect();
    }

    public function getFiltersAttribute() {
        $filters = $this->webAttributeFilters;
        $attributes = [];
        foreach ($filters as $filter) {
            $attributes[$filter->webAttribute->id]['id'] = $filter->webAttribute->id;
            $attributes[$filter->webAttribute->id]['attribute_name'] = $filter->webAttribute->attribute_name;
            $attributes[$filter->webAttribute->id]['webAttributeFilters'][$filter->id]['id'] = $filter->id;
            $attributes[$filter->webAttribute->id]['webAttributeFilters'][$filter->id]['display_as'] = $filter->display_as;
            $attributes[$filter->webAttribute->id]['webAttributeFilters'][$filter->id]['values'] = $filter->webAttributeFilterValues->toArray();
        }
        foreach ($attributes as $id => $attribute) {
            $attributes[$id]['webAttributeFilters'] = \Illuminate\Support\Arr::sort($attribute['webAttributeFilters'], function ($item) {
                return $item['display_as'];
            });
        }
        \Illuminate\Support\Arr::sort($attributes, function ($item) {
            return $item['attribute_name'];
        });

        if ($this->getParentRelationName()) {
            $parentRelationName = $this->getParentRelationName();
            $parentAttributes = $this->$parentRelationName->first()->filters;
            foreach ($parentAttributes as $parentFilterId => $parentFilter) {
                $attributes[$parentFilterId] = $parentFilter;
            }
        }
        return $attributes;
    }

    public function setDetailAttribute($detail) {
        if (Str::contains($detail, 'mceNonEditable')) {
            throw new \InvalidArgumentException(trans('hilco::app.error_while_saving_details_please_try_again'));
        }

        $newDetail = preg_replace_callback('%<!--\\[\\[\\[(.*?)\|(.*?)\\]\\]\\]-->%', function ($matches) {
            return "@include('$matches[1]', " . str_replace(["\n", "\r"], '', var_export(json_decode($matches[2], true), true)) . ")";
        }, $detail);

        $this->attributes['detail'] = $newDetail;
    }

    public function getDetailForEditAttribute() {
        return DbView::make($this)->with(['edit' => true, 'wrap' => true])->render();
    }
}