<?php

namespace App\Model;

use App\Helpers\StringOperation;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use File;
use Image;
use Utils;
use Str;

class Cover extends Model
{

    use TranslatableColumn;

    protected $guarded = ['id'];

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

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

        static::deleting(function ($model) {

            // check if there is there is another entry with same photo name (eg: sometimes it's uploaded by mistake, and want to deleate a duplicate. keep the rest.)
            if ($model
                    ->where('id', '!=', $model->id)
                    ->where('filename', $model->filename)
                    ->count() === 0) {
                File::delete(StringOperation::getCompletePathCovers($model->filename));
            }

//            // check if there is there is another entry with same photo name (eg: sometimes it's uploaded by mistake, and want to deleate a duplicate. keep the rest.)
//            if ($model
//                    ->where('id', '!=', $model->id)
//                    ->where('catalog_filename', $model->catalog_filename)
//                    ->count() === 0) {
//                File::delete(StringOperation::getCompletePathCatalogs($model->catalog_filename));
//            }
        });

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

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


    public function scopeActive($query)
    {
        $query->where('is_active', true);
    }

    public function hasCover() {
        return !empty($this->filename);
    }

    public function getPhotoUrl()
    {
        return Utils::storageUrl('covers', $this->filename);
    }

    public function hasProductPhoto() {
        return !empty($this->product_filename);
    }

    public function getProductPhotoUrl()
    {
        return Utils::storageUrl('cover_products', $this->product_filename);
    }
}
