<?php

namespace App\Models;

use App\Models\Traits\LanguageSupportTrait;
use App\Models\Traits\BlocksTrait;
use App\Models\Interfaces\CardableModel;
use Illuminate\Support\Facades\DB;

class CaseStudy extends ContentTypeModel implements CardableModel
{
    use LanguageSupportTrait;
    use BlocksTrait;

    protected $hidden = array('languages', "websites");
    protected $with = array("websites.languages", "languages");

    public function sectors()
    {
        return $this->belongsToMany(Sector::class, "case_study_sector");
    }

    public function downloads()
    {
        return $this->belongsToMany(Publication::class, "case_study_publication");
    }

    public function blocks()
    {
        return $this->belongsToMany(Block::class, 'case_study_blocks');
    }

    public function overviewImage()
    {
        return $this->belongsTo(MediaItem::class);
    }

    public function clientImage()
    {
        return $this->belongsTo(MediaItem::class);
    }

    public function slides()
    {
        return $this->belongsToMany(MediaItem::class, "case_studies_slides");
    }

    public function contentSnippet()
    {
        return $this->belongsTo(ContentSnippet::class);
    }

    public function getSectorTypes()
    {
        $sectorTypes = $this->sectors->map(function ($sector) {
            return $sector->sector_type;
        });
        return array_unique($sectorTypes->toArray());
    }

    public function sidebarWidgets()
    {
        return $this->belongsToMany(SidebarWidget::class, 'case_study_sb_widgets');
    }

    public function scopeFilterBySectors($query, $sectors)
    {
        return $query->whereExists(function ($query) use ($sectors) {
            $query->select(DB::raw(1))
                ->from("case_study_sector")
                ->whereRaw("case_study_sector.case_study_id = case_studies.id")
                ->whereIn("case_study_sector.sector_id", $sectors);
        });
    }

    public function codeEmbeds()
    {
        return $this->belongsToMany(CodeEmbed::class, "case_study_code_embeds");
    }

    public function getCardFields()
    {
        $wo = $this->websites()->first();
        if ($wo->status != 'published' || $wo->lang_status != 'published') {
            return null;
        }

        $fieldsObject = new \stdClass();
        $fieldsObject->subject = '';
        $fieldsObject->title = $this->title;
        $fieldsObject->excerpt = '<p>' . $this->reference_summary . '</p>';
        $fieldsObject->image = $this->overviewImage;
        $fieldsObject->image_alt = $this->title;
        $fieldsObject->cta = generateObjectLinkJson($this);
        $fieldsObject->cta2 = null;

        return $fieldsObject;
    }
}
