<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Arr;

use App\Models\PhotoBlock;
use App\Models\Photo;

use App\Traits\ContentElementTrait;
use App\Traits\PhotosTrait;
use App\Traits\AppendAttributesTrait;

use App\Utilities\PageLink;

use App\Contracts\SearchResultContract;
use App\Utilities\SearchResult;

class PhotoBlock extends Model implements SearchResultContract
{
    use HasFactory;
    use ContentElementTrait;
    use PhotosTrait;
    use AppendAttributesTrait;

    protected $with = ['photos'];
    protected $casts = [
        'show_text' => 'boolean',
        'text_first' => 'boolean',
    ];

    //protected $append_attributes = [];

    public function saveContent(array $input, $id = null)
    {
        if ($id >= 1) {
            $photo_block = PhotoBlock::findOrFail($id);
            $duplicate_photos = false;
        } else {
            $photo_block = new PhotoBlock();
            $duplicate_photos = true;
        }

        $photo_block->columns = Arr::get($input, 'columns');
        $photo_block->height = Arr::get($input, 'height');
        $photo_block->padding = Arr::get($input, 'padding');
        $photo_block->show_text = Arr::get($input, 'show_text');
        $photo_block->text_first = Arr::get($input, 'text_first');
        $photo_block->header = Arr::get($input, 'header');
        $photo_block->body = Arr::get($input, 'body');
        $photo_block->text_order = Arr::get($input, 'text_order');
        $photo_block->text_span = Arr::get($input, 'text_span');
        $photo_block->text_style = Arr::get($input, 'text_style');
        $photo_block->layout = Arr::get($input, 'layout');
        $photo_block->number = Arr::get($input, 'number');

        $photo_block->save();

        $photo_block->savePhotos($input, $duplicate_photos);

        cache()->tags([cache_name($photo_block)])->flush();
        return $photo_block;
    }

    public function getBodyAttribute($value)
    {
        return $this->convertAttributeLinks($value, 'body');
    }

    public function getSearchFieldsAttribute()
    {
        return [
            'header',
            'body',
        ];
    }

    public function getSearchResultTitle($default = null)
    {
        if (mb_strlen($this->header) > 0) {
            return $this->header;
        }
        return $default;
    }

    public function getSearchResultPreview($terms)
    {
        return SearchResult::truncatePreview(strip_tags($this->body) ? $this->body : $this->header, $terms);
    }

    public function getSearchResultRank($terms)
    {
        $rank = 0;
        foreach ($terms as $term) {
            $rank += mb_substr_count($this->header, $term) * $this->headerRankMultiplier;
            $rank += mb_substr_count($this->body, $term) * $this->bodyRankMultiplier;
        }
        return $rank;
    }
}
