<?php

namespace GriffinForms\Items;

class Format extends \GriffinForms\Format
{
    protected $meta;
    protected $config;
    protected $sql;
    protected $lang;
    protected $id;
    protected $name;
    protected $heading;
    protected $description;
    protected $folder;
    protected $css_class;
    protected $css_id;
    protected $author;
    protected $created;
    protected $last_editor;
    protected $last_edited;
    protected $item_loaded = false;
    
    protected function setSql()
    {
        $sql_class = '\GriffinForms\Admin\Sql\\' . $this->meta;
        $this->sql = $sql_class::getInstance();
    }    
    
    protected function setLang($type = null)
    {
        $lang_class = '\GriffinForms\Admin\Language\\' . $this->meta;
        $this->lang = $lang_class::getInstance();
    }
    
    public function getProp($prop)
    {
        $prop = strtolower($prop);
        
        if (!isset($this->$prop)) {
            return null;
        }

        return $this->maybeDecode($this->$prop);
    }
    
    public function loadItem($id)
    {
        if ($id === null) {
            esc_html_e('Item ID not set. Unable to load values from the database.', 'griffinforms-form-builder');
            return false;    
        }
        
        $values = $this->sql->itemValues($id);

        if (is_scalar($values) or is_null($values)) {
            return false;
        }

        foreach ($values as $prop => $value) {
            if (property_exists($this, $prop)) {
                $this->$prop = $this->maybeDecode($value);
            } else {
                $error = 'SQL field "' . $prop . '" has no equivalent item property';
            }
        }

        $this->item_loaded = true;
        return true;
    }
    
/*     public function loadItemDefaults()
    {
        $values = $this->sql->defaultValues($this->meta);
        foreach ($values as $value) {
            $prop = $value['name'];
            $val = $this->maybeDecode($value['value']);
            $this->$prop = $val;
        }
    } */
    
    protected function setId()
    {
        $this->id = null;
    }
    
    protected function setFolder()
    {
        $this->folder = 0;
    }
    
    public function getHtmlId()
    {
        return 'griffinforms-' . $this->meta . '-' . $this->id;
    }
    
    public function __construct()
    {
        $this->setAll();
    }

    public function isLoaded(): bool
    {
        return (bool) $this->item_loaded;
    }
}
