<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Spatie\Translatable\HasTranslations;

class Project extends Model
{
    use HasTranslations, SoftDeletes;

    protected $guarded = ['id'];

    protected $translatable = ['name', 'sub_name', 'summaries', 'img_alt', 'address', 'floor_plan',
        'building_structure', 'design_unit', 'contact', 'district', 'seo_description', 'seo_keywords',
    ];

    protected $casts = ['img_url' => 'array', 'mobile_img_url' => 'array'];

    protected $appends = ['first_list_img_url', 'img_list', 'thumbnail_url', 'first_mobile_img_url', 'mobile_img_list'];

    public function region()
    {
        return $this->belongsTo(Region::class);
    }

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    public function badges()
    {
        return $this->morphToMany(Badge::class, 'badgeable')
            ->withPivot('award_date', 'award_type', 'sort_order')
            ->orderByPivot('sort_order')
            ->withTimestamps();
    }

    /**
     * 永續目標
     */
    public function targetBadges()
    {
        return $this->morphToMany(Badge::class, 'badgeable')
            ->withPivot('award_type', 'sort_order')
            ->wherePivot('award_type', 1)
            ->orderByPivot('sort_order')
            ->withTimestamps();
    }

    /**
     * 取得標章
     */
    public function awardBadges()
    {
        return $this->morphToMany(Badge::class, 'badgeable')
            ->withPivot('award_type', 'award_date', 'sort_order')
            ->wherePivot('award_type', 2)
            ->orderByPivot('sort_order')
            ->withTimestamps();
    }

    public function histories()
    {
        return $this->hasMany(ProjectHistory::class)->orderBy('order');
    }

    public function spaceInfos()
    {
        return $this->hasMany(ProjectSpaceInfo::class)->orderBy('order');
    }

    public function firstListImgUrl(): Attribute
    {
        return Attribute::make(
            get: fn($value) => !empty($this->img_url) ? Storage::url($this->img_url[0]) : null,
        );
    }

    public function imgList(): Attribute
    {
        $imgList = [];
        if (!is_null($this->img_url) && count($this->img_url) > 0) {
            foreach ($this->img_url as $img) {
                $imgList[] = Storage::url($img);
            }
        }

        return Attribute::make(
            get: fn($value) => $imgList,
        );
    }

    public function thumbnailUrl(): Attribute
    {
        return Attribute::make(
            get: fn($value) => !empty($this->thumbnail) ? Storage::url($this->thumbnail) : null,
        );
    }

    public function firstMobileImgUrl(): Attribute
    {
        return Attribute::make(
            get: fn($value) => !empty($this->mobile_img_url) ? Storage::url($this->mobile_img_url[0]) : null,
        );
    }

    public function mobileImgList(): Attribute
    {
        $imgList = [];
        if (!is_null($this->mobile_img_url) && count($this->mobile_img_url) > 0) {
            foreach ($this->mobile_img_url as $img) {
                $imgList[] = Storage::url($img);
            }
        }

        return Attribute::make(
            get: fn($value) => $imgList,
        );
    }

    public function getBadges($locale): array
    {
        $badges = [];
        if ($this->badges->count() > 0) {
            foreach ($this->badges as $badge) {
                $badges[] = [
                    'imgUrl' => $badge->imgUrlLink,
                    'name' => $badge->getTranslation('title', $locale),
                    'awardDate' => '取得時間 : ' . date('Y.m', strtotime($badge->pivot->award_date)),
                ];
            }
        }

        return $badges;
    }

    public function getBadgesByType($locale, $badgeType): array
    {
        // 定義「取得時間」的翻譯
        $awardDateLabels = [
            'zh_TW' => '取得時間',
            'en' => 'Awarded',
        ];

        // 取得對應的標籤，如果找不到則使用預設值
        $awardDateLabel = $awardDateLabels[$locale] ?? $awardDateLabels['zh_TW'];

        $badges = [];
        switch ($badgeType) {
            case '1':
                $badgesData = $this->targetBadges;
                foreach ($badgesData as $badge) {
                    $badges[] = [
                        'imgUrl' => $badge->imgUrlLink,
                        'name' => $badge->getTranslation('title', $locale),
                        'awardDate' => null,
                    ];
                }
                break;
            case '2':
                $badgesData = $this->awardBadges;
                foreach ($badgesData as $badge) {
                    $badges[] = [
                        'imgUrl' => $badge->imgUrlLink,
                        'name' => $badge->getTranslation('title', $locale),
                        'awardDate' => $awardDateLabel . ' : ' . date('Y.m', strtotime($badge->pivot->award_date)),
                    ];
                }
                break;
        }

        return $badges;
    }

    public function getTags($locale): array
    {
        $tags = [];
        if ($this->tags->count() > 0) {
            foreach ($this->tags as $tag) {
                $tags[] = [
                    'id' => $tag->id,
                    'name' => $tag->getTranslation('name', $locale),
                ];
            }
        }

        return $tags;
    }
}
