<?php

namespace Modules\Example\Entities;

use App\Traits\QueryCacheable;
use Deligoez\LaravelModelHashId\Traits\HasHashId;
use Deligoez\LaravelModelHashId\Traits\HasHashIdRouting;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Modules\Example\Database\Factories\ExampleFactory;
use Yajra\DataTables\Facades\DataTables;

class Example extends Model
{
    use HasFactory;
    use HasHashId;
    use HasHashIdRouting;
    use SoftDeletes;
    use QueryCacheable;

    /**
     * Specify the amount of time to cache queries.
     * Do not specify or set it to null to disable caching.
     *
     * @var int|\DateTime
     */
    public $cacheFor = 3600;

    /**
     * The tags for the query cache. Can be useful
     * if flushing cache for specific tags only.
     *
     * @var null|array
     */
    public $cacheTags = ['examplies'];

    /**
     * Invalidate the cache automatically
     * upon update in the database.
     *
     * @var bool
     */
    protected static $flushCacheOnUpdate = true;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        //
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        // 'deleted_at',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        //
    ];

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory()
    {
        return ExampleFactory::new();
    }

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

    public function scopeFilters($query, Request $request)
    {
        $query->when($request->has('status'), function ($query) use ($request) {
            return $query->where('is_active', $request->status == 'active');
        });

        $query->when($request->has('range'), function ($query) use ($request) {
            $date_range = explode(' to ', $request->range);

            if (count($date_range) == 2) {
                $from = new Carbon($date_range[0]);
                $to = new Carbon($date_range[1]);

                $query->whereBetween('created_at', [$from->startOfDay(), $to->endOfDay()]);
            } else if (count($date_range) == 1) {
                $query->whereDate('created_at', $date_range[0]);
            }

            return $query;
        });
    }

    public function getThumbnailPathAttribute()
    {
        $default = uno()->no_image;

        if ($this->thumbnail) {
            if (filter_var($this->thumbnail, FILTER_VALIDATE_URL)) {
                return $this->thumbnail;
            } else if (asset_exists($this->thumbnail)) {
                return disk_public()->url($this->thumbnail);
            } else {
                return $default;
            }
        }

        return $default;
    }

    public static function makeDataTable($source, $trash = false)
    {
        return DataTables::of($source)
            ->addColumn('status', function (self $row) {
                return view('admin.datatables.status', ['active' => $row->is_active]);
            })
            ->addColumn('actions', function (self $row) use ($trash) {
                $actions = ['row' => $row];

                if ($trash) {
                    $actions['restore_route'] = 'example.restore';
                } else {
                    $actions['update_route'] = 'example.edit';
                    $actions['delete_route'] = 'example.destroy';
                }

                return view('admin.datatables.actions', $actions);
            })
            // to fixed yajra weird timezone return
            ->editColumn('created_at', fn($row) => $row->created_at)
            ->editColumn('updated_at', fn($row) => $row->updated_at)
            ->editColumn('deleted_at', fn($row) => $row->deleted_at)
            ->make(true);
    }
}
