<?php

namespace auctionforge\inc\abs;

use Exception;

abstract class Model
{
    /**
     * Id Entity on site
     * @var int
     */
    protected $id;

    /**
     * Auction name
     * @var string
     */
    protected $name;

    /**
     * Initializing object properties
     * @param $model
     * @return void
     */
    public function loadAttributes($model)
    {
        foreach ($model as $key => $value) {
            $key = preg_replace_callback("/_(\w)/", "auctionforge\inc\abs\Model::bpLoadValue", $key);
            if (property_exists($this, $key)) {
                $value = apply_filters('auctionforge_before_init_mutation', $value, $key, $model);
                $this->{"set" . ucfirst($key)}($value);
            }
        }
    }

    private static function bpLoadValue($value)
    {
        if (!empty($value) && isset($value[1])) {
            return mb_strtoupper($value[1]);
        }
        return $value[0];
    }

    /**
     * Convert boolean to string
     * @param $value
     * @return string
     */
    public static function toString($value)
    {
        try {
            if (boolval($value) === false) {
                return 'false';
            } elseif (boolval($value) === true) {
                return 'true';
            }
        } catch (Exception $exception) {
            return 'false';
        }
    }

    /**
     * Convert boolean to int
     * @param $value
     * @return string
     */
    public static function toInt($value)
    {
        try {
            if (boolval($value) === false) {
                return 0;
            } elseif (boolval($value) === true) {
                return 1;
            }
        } catch (Exception $exception) {
            return 0;
        }
    }

    public static function toBoolean($value)
    {
        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = mb_substr($name, 0, 255);
    }
}
