<?php
namespace boru\boruai\Vtiger;

use boru\boruai\BoruAI;
use boru\query\Query;

class VtigerFields {
    private static $moduleFieldsCache = [];

    private $moduleName;
    private $fields = [];
    public function __construct($module=null) {
        if($module !== null) {
            $this->moduleName = $module;
            $this->fields = static::getFields($module);
        }
    }
    public function moduleName() {
        return $this->moduleName;
    }

    public function makeDataArray($inputArray=[],$fromColumns=false) {
        $data = [];
        foreach($this->fields as $fieldname=>$fieldInfo) {
            if(isset($inputArray[$fieldInfo['columnname']]) && $fromColumns) {
                $data[$fieldname] = $inputArray[$fieldInfo['columnname']];
            } elseif(isset($inputArray[$fieldname]) && !$fromColumns) {
                $data[$fieldname] = $inputArray[$fieldname];
            } else {
                $data[$fieldname] = null;
            }
        }
        return $data;
    }

    public function columnName($fieldname) {
        if(isset($this->fields[$fieldname])) {
            return $this->fields[$fieldname]['columnname'];
        }
        return null;
    }
    public function tableName($fieldname) {
        if(isset($this->fields[$fieldname])) {
            return $this->fields[$fieldname]['tablename'];
        }
        return null;
    }
    public function fieldName($tableName,$columnName) {
        foreach($this->fields as $fieldname=>$field) {
            if($field['tablename'] == $tableName && $field['columnname'] == $columnName) {
                return $fieldname;
            }
        }
        return null;
    }
    public function fieldLabel($fieldname) {
        if(isset($this->fields[$fieldname])) {
            return $this->fields[$fieldname]['fieldlabel'];
        }
        return null;
    }
    public function fieldType($fieldname) {
        if(isset($this->fields[$fieldname])) {
            return $this->fields[$fieldname]['uitype'];
        }
        return null;
    }
    public function typeOfData($fieldname) {
        if(isset($this->fields[$fieldname])) {
            return $this->fields[$fieldname]['typeofdata'];
        }
        return null;
    }
    private static $cache = [];
    public static function forModule($moduleNameOrTabId) {
        if(isset(static::$cache[$moduleNameOrTabId])) {
            return static::$cache[$moduleNameOrTabId];
        }
        if(is_numeric($moduleNameOrTabId)) {
            $modInfo = VtigerModule::getModuleById($moduleNameOrTabId);
        } else {
            $modInfo = VtigerModule::getModuleByName($moduleNameOrTabId);
        }
        
        static::$cache[$modInfo["name"]] = new static($modInfo["name"]);
        static::$cache[$modInfo["tabid"]] = static::$cache[$modInfo["name"]];
        return static::$cache[$modInfo["name"]];
    }
    /**
     * Get fields for a module
     * @param int|string $tabIdOrModuleName The tabid or module name
     * @return array array of fields with fieldname as key, [fieldlabel, uitype, typeofdata, presence, columnname] as value
     */
    public static function getFields($tabIdOrModuleName) {
        if(!is_numeric($tabIdOrModuleName)) {
            $tabIdOrModuleName = VtigerModule::getModuleByName($tabIdOrModuleName);
            $tabId = $tabIdOrModuleName['tabid'];
        } else {
            $tabId = $tabIdOrModuleName;
        }
        if(isset(static::$moduleFieldsCache[$tabId])) {
            return static::$moduleFieldsCache[$tabId];
        }
        $fields = Query::create()
            ->select("fieldid, fieldname, columnname, tablename, fieldlabel, uitype, typeofdata, presence")
            ->from("vtiger_field")
            ->where("tabid","=",$tabId)
            ->toRows();
        foreach($fields as $field) {
            static::$moduleFieldsCache[$tabId][$field->get('fieldname')] = $field->asArray();
            if($field->get('uitype') == 10) {
                $relatedModules = static::getFieldRelatedModules($field->get('fieldid'));
                static::$moduleFieldsCache[$tabId][$field->get('fieldname')]['relatedModules'] = $relatedModules;
            } elseif($field->get('uitype') == 15) {
                $picklistValues = static::getPicklistValues($field->get('fieldname'));
                static::$moduleFieldsCache[$tabId][$field->get('fieldname')]['picklistValues'] = $picklistValues;
            }
        }
        return static::$moduleFieldsCache[$tabId];
    }

    private static function getFieldRelatedModules($fieldId) {
        $rows = Query::create()
            ->select("*")
            ->from("vtiger_fieldmodulerel")
            ->where("fieldid","=", $fieldId)
            ->toRows();
        $modules = [];
        foreach($rows as $row) {
            $modules[] = $row->get("relmodule");
        }
        //return $field['tabid'];
    }

    private static function getPicklistValues($fieldname) {
        $rows = Query::create()
            ->select($fieldname)
            ->from("vtiger_".$fieldname)
            ->toRows();
        $values = [];
        foreach($rows as $row) {
            $values[] = $row->get($fieldname);
        }
        return $values;
    }
}