<?php

namespace Wizard\Framework\Models;

use Wizard\Framework\Traits\Filterable;
use Wizard\Framework\Database\Builder;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    use Filterable;

		protected static string $builder = Builder::class;

    protected $default_relations = [];

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

        self::creating(function ($item) {
            $item->created_by = \Auth::user()?->id ?? '';
            $item->updated_by = \Auth::user()?->id ?? '';
        });

        self::saving(function ($item) {
            $item->updated_by = \Auth::user()?->id ?? '';
        });
    }


    protected static function load_auxilary_data()
    {
        $data = [];

        $instance = new static;

        foreach ($instance->default_relations as $relation) {
            $related_model = $instance->$relation()->getRelated();
            $related_table = $related_model->getTable();
            $data[$related_table] = $related_model->all()->pluck('name', 'id')->toArray();
        }

        return $data;
    }

    public static function load_index()
    {
        return static::load_auxilary_data();
    }

    public static function load_create()
    {
        return static::load_auxilary_data();
    }

    public static function load_edit()
    {
        return static::load_auxilary_data();
    }

		public static function named_joins() {
			return [];
		}

    /**
     * Retrieve a query builder instance with default relations loaded.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function data_query()
    {
        $query = static::query();

        $instance = new static;

        foreach ($instance->default_relations as $relation) {
            $query->with($relation);
        }

        return $query;
    }

    /**
     * Retrieve a query builder instance with default relations loaded.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function get_data(array $validated = [])
    {
        $query = static::data_query();

        $query->filter($validated);

        return $query->get();
    }
}
