<?php

namespace Mtc\Plugins\Wisebee\Classes\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Shop\Category;

/**
 * Accessors
 *
 * @property int $id
 * @property string $name
 * @property string $value
 *
 * @property Carbon $updated_at
 * @property Carbon $created_at
 *
 */

class WisebeeSetting extends Model
{
    protected $table = 'wisebee_settings';

    protected $fillable = [
        'name',
        'value',
    ];

    public const SETTING_APPLY_TO_CATEGORIES = 'apply_to_categories';
    public const SETTING_CONSULTATION_WITH_PRODUCT_FREE = 'consultation_with_product_free';

    public static $settings = [
        self::SETTING_APPLY_TO_CATEGORIES => [
            'type' => 'checkbox',
            'default' => 0,
            'title' => 'Apply to categories',
        ],
        self::SETTING_CONSULTATION_WITH_PRODUCT_FREE => [
            'type' => 'checkbox',
            'default' => 0,
            'title' => 'Consultation together with product is free',
        ],
    ];

    /**
     * Gets setting by name
     *
     * @param string $name
     * @return \Illuminate\Database\Eloquent\HigherOrderBuilderProxy|mixed|void
     */
    public static function getSetting(string $name)
    {
        $setting = self::query()
            ->where('name', $name)
            ->first();

        if (! empty($setting)) {
            return $setting->value;
        }

        self::populate();
        if (empty(self::$settings[$name])) {
            return null;
        }

        return self::$settings[$name]['default'];
    }

    /**
     * Get all settings mapped
     */
    public static function allSettings()
    {
        $settings = self::query()
            ->orderBy('name')
            ->get();
        foreach (array_keys(self::$settings) as $name) {
            if ($settings->where('name', $name)->count() === 0) {
                self::populate();
                $settings = self::query()
                    ->orderBy('name')
                    ->get();
                break;
            }
        }

        return $settings->mapWithKeys(function (self $setting) {
            return [$setting->name => $setting->value];
        });
    }

    /**
     * Populates DB with missing settings
     *
     * @return void
     */
    protected static function populate(): void
    {
        $settings = self::all();
        foreach (self::$settings as $name => $attributes) {
            if ($settings->where('name', $name)->count() === 0) {
                self::query()
                    ->create([
                        'name' => $name,
                        'value' => $attributes['default'],
                    ]);
            }
        }
    }
}
