<?php

namespace Salesloo\Abstracts;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use Salesloo\Builder;

/**
 * database query builder
 */
abstract class Database
{
    /**
     * database table
     */
    protected $table;

    /**
     * table columns
     */
    protected $columns;

    protected $attributes = [];

    /**
     * Handle dynamic static method calls.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        return (new static)->$method(...$parameters);
    }

    /**
     * setter
     * @param  string $name [description]
     * @return [type]      [description]
     */
    public function __set($name, $value)
    {

        if (isset($this->columns[$name])) {

            $type = $this->columns[$name];

            if ('integer' == $type) {
                $value = intval($value);
            } else if ('array' == $type) {
                $value = \maybe_serialize($value);
            } else if ('price' == $type) {
                $value = floatval($value);
            } else if ('content' == $type) {
                $value = stripslashes_deep(wp_kses_post($value));
            } else {
                if (is_array($value)) {
                    $value = \maybe_serialize($value);
                }
                $value = \sanitize_text_field($value);
            }
        }

        return $this->attributes[$name] = $value;
    }

    /**
     * getter
     * @param  string $name [description]
     * @return [type]      [description]
     */
    public function __get($name)
    {
        $data = $this->attributes;

        if (array_key_exists($name, $data))
            return maybe_unserialize($data[$name]);

        return NULL;
    }

    /**
     * isset
     * @param  string $name [description]
     * @return [type]      [description]
     */
    public function __isset($name)
    {
        $data = $this->attributes;

        return isset($data[$name]);
    }

    /**
     * constructor
     */
    public function __construct()
    {
    }

    /**
     * set model
     */
    public static function model($data = [])
    {
        $model = new static;

        $data_output = [];
        $data_array = (array)$data;
        foreach ($data_array as $key => $value) {
            $data_output[$key] = maybe_unserialize($value);
        }

        $model->attributes = $data_output;

        return $model;
    }

    /**
     * Handle dynamic method calls.
     */
    public function __call($method, $parameters)
    {
        $builder = new Builder($this->table, $this->columns, $this->attribues, [$this, 'model']);
        return $builder->$method(...$parameters);
    }
}
