<?php

namespace App\Models;

use Barryvdh\LaravelIdeHelper\Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Contracts\JsonResourceful;
use Illuminate\Support\Carbon;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

/**
 * App\Models\Pages
 *
 * @property int $id
 * @property string $title
 * @property string|null $URL
 * @property int $status
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read string $pages_image
 * @property-read MediaCollection|Media[] $media
 * @property-read int|null $media_count
 * @method static Builder|Pages newModelQuery()
 * @method static Builder|Pages newQuery()
 * @method static Builder|Pages query()
 * @method static Builder|Pages whereCreatedAt($value)
 * @method static Builder|Pages whereId($value)
 * @method static Builder|Pages whereStatus($value)
 * @method static Builder|Pages whereTitle($value)
 * @method static Builder|Pages whereURL($value)
 * @method static Builder|Pages whereUpdatedAt($value)
 * @mixin Eloquent
 */
class Pages extends Model implements HasMedia, JsonResourceful
{
    use HasFactory, InteractsWithMedia; 

    protected $table = 'pages';
    const PAGES_IMAGE = 'pages_image';
    protected $appends = ['pages_image'];
    protected $fillable = [
        'title',
        'URL',
        'status',
    ];

    const ACTIVE = 1;
    const INACTIVE = 0;

    const STATUS = [
        self::ACTIVE   => 'Active',
        self::INACTIVE => 'Inactive',
    ];
    protected $casts = ['status' => 'boolean'];
    public static $rules = [
        'title'              => 'required',
        'walk_through_image' => 'required',
    ];

    public function getPagesImageAttribute(): string
    {
        /** @var Media $media */
        $media = $this->getMedia(self::PAGES_IMAGE)->first();
        if (!empty($media)) {
            return $media->getFullUrl();
        }

        return asset('images/avatar.png');
    }

    public function prepareAttributes(): array
    {
        return [
            'id'        => $this->id,
            'title'     => $this->title,
            'URL'  => $this->URL,
            'status'    => $this->status,
            'image_url' => $this->getMedia(self::PAGES_IMAGE)->first()->getFullUrl(),
        ];
    }
}
