<?php
namespace boru\boruai\Vtiger;

use boru\boruai\BoruAI;
use boru\query\Entity;
use boru\query\models\EntityDefinition;
use boru\query\Query;

/**
 * Entity wrapper for vtiger records.
 */
class VtigerRecord
{
    private $entityName;
    private $selectStub;
    private $data = [];
    private $original = [];

    private $id = null;

    private $fieldMap;

    private static $cache_schemaMap = [];
    private static $cache_entityFieldMap = [];

    public function __construct($entityName, $id = null)
    {
        static::schemaMap($entityName);
        $this->entityName = $entityName;
        $this->fieldMap = static::fieldMap($entityName);
        $this->data = $this->fieldMap->makeDataArray();
        $this->selectStub = static::getSelectStub($entityName);
        $this->original = $this->data;

        if ($id !== null) {
            $this->load($id);
        }
    }

    /**
     * Load a record by ID.
     * @param int $id
     * @return bool
     * @throws \Exception
     */
    public function load($id)
    {
        $select = $this->selectStub;
        if (!$select) {
            throw new \Exception("No select stub for entity: " . $this->entityName);
        }
        $select.= " WHERE `vtiger_crmentity`.`crmid` = ? and `vtiger_crmentity`.`deleted` = 0";
        $db = BoruAI::db();
        $result = $db->query($select, [$id]);
        while($row=$db->next($result)) {
            $this->id = $id;
            $this->data = $this->fieldMap->makeDataArray($row->asArray(), true);
            $this->original = $this->data;
            return true;
        }
        return false;
    }

    /**
     * Get a field value.
     * @param string $field
     * @return mixed
     */
    public function get($field)
    {
        return isset($this->data[$field]) ? $this->data[$field] : null;
    }

    public function data()
    {
        return $this->data;
    }

    /**
     * Set a field value.
     * @param string $field
     * @param mixed $value
     * @return self
     */
    public function set($field, $value=null)
    {
        $this->data[$field] = $value;
        return $this;
    }

    /**
     * Save the record (insert or update).
     * @return bool
     */
    public function save()
    {
        throw new \Exception("Save not implemented");
    }

    /**
     * Delete the record.
     * @return bool
     */
    public function delete()
    {
        if (!$this->id) {
            return false;
        }
        $query = new Query($this->entityName);
        $query->where('id', $this->id);
        $result = $query->delete();
        if ($result) {
            $this->id = null;
            $this->data = [];
            $this->original = [];
        }
        return $result ? true : false;
    }

    /**
     * Get the record ID.
     * @return int|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Return all data as array.
     * @return array
     */
    public function toArray()
    {
        return $this->data;
    }


    public static function fieldMap($module) {
        if(!isset(static::$cache_entityFieldMap[$module])) {
            static::schemaMap($module);
        }
        return isset(static::$cache_entityFieldMap[$module]) ? static::$cache_entityFieldMap[$module] : [];
    }
    public static function schemaMap($module) {
        if(!isset(static::$cache_schemaMap[$module])) {
            $vtiger = Vtiger::instance();
            static::$cache_schemaMap[$module] = $vtiger->schema($module);
            static::$cache_entityFieldMap[$module] = VtigerFields::forModule($module);
        }
        return static::$cache_schemaMap[$module];
    }
    public static function getSelectStub($module) {
        if(!isset(static::$cache_schemaMap[$module])) {
            static::schemaMap($module);
        }
        return isset(static::$cache_schemaMap[$module]['select']) ? static::$cache_schemaMap[$module]['select'] : false;
    }
}
/*
{
    "fields": {
        "cf_dscs": {
            "fieldid": "3595",
            "fieldname": "cf_dscs",
            "columnname": "cf_dscs",
            "tablename": "vtiger_potentialscf",
            "fieldlabel": "dsKS",
            "uitype": "7",
            "typeofdata": "I~O",
            "presence": "2"
        },
        "cf_day_sf": {
            "fieldid": "3596",
            "fieldname": "cf_day_sf",
            "columnname": "cf_day_sf",
            "tablename": "vtiger_potential",
            "fieldlabel": "Days from Signing to Funding",
            "uitype": "7",
            "typeofdata": "I~O",
            "presence": "2"
        },
        "cf_unreadthreads": {
            "fieldid": "3597",
            "fieldname": "cf_unreadthreads",
            "columnname": "cf_unreadthreads",
            "tablename": "vtiger_potentialscf",
            "fieldlabel": "Unread Threads?",
            "uitype": "15",
            "typeofdata": "V~O",
            "presence": "2",
            "picklistValues": [
                "Yes",
                "No"
            ]
        }
    }
}
*/