<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Cache;
use Morilog\Jalali\Jalalian;

class ProductComment extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'product_id',

        'content',
        'answer',
        'strengths',
        'weakness',

        'images',

        'buy_suggest',
        'rating',
        'vote_up',
        'vote_down',

        'reported',
        'status',
    ];

    protected $casts = [
        'user_id' => 'integer',
        'product_id' => 'integer',

        'reported' => 'boolean',
    ];

    /**
     * additional data
     */
    protected $appends = [
        'get_images',
        'get_product_status',
        'get_strengths',
        'get_weakness',
        'get_answer',
        'is_buyer',
        'jalali_created_at',
        'jalali_updated_at',

        'safe',
    ];

    public function getGetImagesAttribute()
    {
        $finalImages = [];
        $images = $this->images != null ? unserialize($this->images) : [];
        foreach ($images as $image) {
            $file = Cache::remember('files_' . $image, now()->addMonth(), function () use ($image) {
                return File::find($image);
            });
            if ($file != null && $file->type == "image") {
                $finalImages[] = [
                    'id' => $file->id,
                    'url' => asset($file->url),
                    'alt' => $file->description,
                ];
            }
        }

        return $finalImages;
    }

    public function getGetProductStatusAttribute()
    {
        return $this->product->status == 'publish' ? true : false;
    }

    public function getGetStrengthsAttribute()
    {
        return $this->strengths != null ? unserialize($this->strengths) : [];
    }

    public function getGetWeaknessAttribute()
    {
        return $this->weakness != null ? unserialize($this->weakness) : [];
    }

    public function getGetAnswerAttribute()
    {
        return $this->answer != null ? unserialize($this->answer) : null;
    }

    public function getIsBuyerAttribute()
    {
        $user = $this->user;
        $isBuyer = Cache::remember('product_comment_is_buyer_' . $this->id . '_' . $user->id, now()->addDay(), function () use ($user) {
            return $user->consignments()->whereHas('consignmentItems', function ($query) {
                $query->where('product_id', $this->product_id)->where(function ($query) {
                    $query->where('status', 'sent')->orWhere('status', 'delivered');
                });
            })->count() > 0 ? true : false;
        });

        return $isBuyer;
    }

    public function getJalaliCreatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->created_at)->format('%d %B %Y'),
            Jalalian::forge($this->created_at)->format('Y/m/d'),
            Jalalian::forge($this->created_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->created_at)->ago(),
            Jalalian::forge($this->created_at)->getTimestamp(),
        ];
        return $date;
    }

    public function getJalaliUpdatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->updated_at)->format('%d %B %Y'),
            Jalalian::forge($this->updated_at)->format('Y/m/d'),
            Jalalian::forge($this->updated_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->updated_at)->ago(),
            Jalalian::forge($this->updated_at)->getTimestamp(),
        ];
        return $date;
    }

    public function getSafeAttribute()
    {
        return [
            'id' => $this->id,
            'content' => $this->content,
            'answer' => $this->answer,
            'get_answer' => $this->get_answer,
            'get_strengths' => $this->get_strengths,
            'get_weakness' => $this->get_weakness,
            'buy_suggest' => $this->buy_suggest,
            'rating' => $this->rating,
            'vote_up' => $this->vote_up,
            'vote_down' => $this->vote_down,
            'is_buyer' => $this->is_buyer,
            'status' => $this->status,
            'jalali_created_at' => $this->jalali_created_at,
            'jalali_updated_at' => $this->jalali_updated_at,

            'get_product_status' => $this->get_product_status,
            'user' => $this->user,
            'product' => [
                'id' => $this->product->id,
                'title' => $this->product->title,
                'slug' => $this->product->slug,
            ],
        ];
    }
    /** end append */

    /**
     * remove cache data in update
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($comment) {
            // product appends
            Cache::forget('product_comments_info_' . $comment->product_id);
            Cache::forget('product_first_comment_' . $comment->product_id);
        });

        static::deleted(function ($comment) {
            // product appends
            Cache::forget('product_comments_info_' . $comment->product_id);
            Cache::forget('product_first_comment_' . $comment->product_id);
        });
    }

    /* relationships **************/
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }
}
