<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Storage;

/**
 * @package App\Models
 * @property int $id
 * @property int $useful_info_id
 * @property array $name
 * @property array $description
 * @property string $video_url
 * @property string $link_url
 * @property string $file_url
 * @property string $created_at
 * @property string $updated_at
 *
 * @property UsefulInfo $usefulInfo
 *
 * @method string getName()
 * @method string getDescription()
 * @method string getFile()
 */
class UsefulInfoItem extends Model
{
    use HasFactory;

    protected $table = 'useful_info_items';

    protected $fillable = [
        'useful_info_id',
        'name',
        'description',
        'video_url',
        'link_url',
        'file_url',
    ];

    protected $casts = [
        'name' => 'array',
        'description' => 'array',
    ];

    public function usefulInfo()
    {
        return $this->belongsTo(UsefulInfo::class);
    }

    public function getName(): string
    {
        if (App::isLocale('ru')) {
            return (string) $this->name['ru'];
        }

        return (string) $this->name['uz'];
    }

    public function getFile(): string
    {
        if (!empty($this->file_url)) {
            if (in_array(env('FILESYSTEM_DISK'), ['s3', 'minio'])) {
                return Storage::temporaryUrl(
                    $this->file_url,
                    Date::now()->addMinutes(5)
                );
            }
            return '/' . $this->file_url;
        }

        return '/images/no_product.jpg';
    }

    public function getDescription(): string
    {
        if (isset($this->description['uz']) && isset($this->description['ru'])) {
            if (App::isLocale('ru')) {
                return (string) $this->description['ru'];
            }

            return (string) $this->description['uz'];
        }

        return '';
    }
}
