<?php

namespace App\Model;

use App\Helpers\StringOperation;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Auth;
use Illuminate\Support\Str;

class Gallery extends Model
{

    public $guarded = ['id'];


    use TranslatableColumn;
    use EnumValues;

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            $model->slug = Str::slug($model->name);
        });

        static::deleting(function ($model) {
            $model->photos->each(function ($photo) {
                $photo->delete();
            });
        });

        // we want the categories to be sorted always by priority.
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('priority', 'asc');
        });

    }

    public function user()
    {
        return $this->belongsTo('App\Model\User');
    }


    public function photo()
    {
        return $this->belongsTo('App\Model\Gallery\GalleryPhoto');
    }

    public function photos()
    {
        return $this->hasMany('App\Model\Gallery\GalleryPhoto')
            ->orderBy('priority')
            ->orderBy('id');
    }


    public function scopeRecent($query)
    {
        $query->orderByDesc('id');
    }

    public function scopeActive($query)
    {
        $query->where('status', 'active');
    }

    public function scopeFeatured($query)
    {
        $query->where('is_featured', true);
    }


    public function getArchive()
    {
        return (new $this->archive)->orderByDesc('year')->orderBy('month')->get()->groupBy('year');
    }

    public function getUrl()
    {
        return $this->url;
        return route('site.gallery', [$this->slug, $this]);
    }


    public function getDummyImage()
    {
        return 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
    }


    public function getStatusClassAttribute()
    {
        switch ($this->status) {
            case 'pending':
                return 'warning';
            case 'active':
                return 'primary';
            case 'inactive':
                return 'danger';

        }
    }

    public function getPhotoUrl()
    {
        if ($this->photo) {
            return $this->photo->getPhotoUrl();
        }
        return $this->getDummyImage();
    }

    public function getThumbUrl()
    {
        if ($this->photo) {
            return $this->photo->getThumbUrl();
        }
        return $this->getDummyImage();
    }

    public function isNew()
    {
        if (!$this->created_at) {
            return false;
        }
        return $this->created_at->gt(Carbon::now()->subDay(2));
    }

    public function isPending()
    {
        return $this->status === 'pending';
    }

    public function isActive()
    {
        return $this->status === 'active';
    }

}
