<?php
/**
 * Copyright (c) 2016. PlatyHouse. all rights reserved.
 */

namespace platyFramework;

/**
 *
 * @property int $id
 * @property int $descId
 * @property int $enabled
 * @property int $serviceUserId
 * @property int $userId
 */
class ptyItemModel extends ptyArrayItemModel
{
    public $_primaryColumnName = "id";
    public $_tableName = "";
    public $_totalCount = -1;

    function __construct($tableName = NULL, $item = NULL, $totalCount = -1)
    {
        // ptyDebug(get_defined_vars());
        $this->_tableName = $tableName;
        $this->_totalCount = $totalCount;
        parent::__construct($item);

        $this->onItemRefresh();
    }

    /*
    function __clone()
    {
        $this->item = clone $this->item;
    }
    */

    /**
     * 데이터 로그
     */
    public function onItemRefresh()
    {
    }

    public static function buildTableItem($tableName, $item)
    {
        $item = new self($tableName, $item);

        return $item;
    }

    public static function buildTableItems($tableName, $items, $totalCount = -1)
    {
        $ret = array();
        foreach ($items as $k => $v) {
            $item = new static($tableName, $v, $totalCount);
            $ret[] = $item;

        }

        return $ret;
    }

    public function updateAllItem()
    {
        if (!(int)$this->id)
            die ("updateAllItem() item->id 가 없습니다");

        $this->db->clear();

        foreach ($this->_item as $k => $v) {
            // if (!isset($v)) $v = NULL;

            if ($k == "id")
                continue;
            $this->db->addSet($k, $v);
        }

        $this->db->addFrom($this->_tableName)
            ->addWhereEqual("id", $this->id)
            ->update();
    }

    /**
     * NULL 이 아닌 항목만을 업데이트 합니다
     */
    public function updateAllNotNullItem()
    {
        if (!(int)$this->id)
            die ("updateAllNotNullItem() item->id 가 없습니다");

        $this->db->clear();

        foreach ($this->_item as $k => $v) {
            // if (!isset($v)) $v = NULL;

            if ($k == "id")
                continue;

            if ($v == NULL)
                continue;

            $this->db->addSet($k, $v);
        }

        $this->db->addFrom($this->_tableName)
            ->addWhereEqual("id", $this->id)
            ->update();
    }


    public function updateRaw($keys, $v = NULL)
    {
        $this->db->clear();
        $this->db->addSet("*" . $keys, $v);
        $this->db->addFrom($this->_tableName)
            ->addWhereEqual("id", $this->id)
            ->update();

        $this->onItemRefresh();
    }

    /*
     *
     *
     *
      */

    /**
     * @return mixed|null
     * @author cpueblo <cpueblo@platyhouse.com>
     */
    public function insert()
    {
        $this->db->clear()->addFrom($this->_tableName)->addSet($this->item->_item)->insert();

        $this->item->id = $this->db->getInsertId();

        return $this->item->id;
    }

    public function __get($key)
    {
        // ptyDebug($key);
        if (isset($this->item->_item[$key])) {
            return $this->item->_item[$key];
        } else if (isset($this->$key))
            return $this->$key;
        else
            return parent::__get($key);
    }

    public function setEnable()
    {
//		if (!($this->loginUserItem && $this->loginUserItem->isAdmin || $this->userId == $this->loginUserItem->id))
//			ptyJsonReturnFalseDie(["alertMsg" => "권한이 없습니다"]);

        $this->enabled = 1;
        $this->updateWithItemName("enabled");

        return $this->item->enabled;
    }

    /**
     * itemName 에 지정한 키값들을 업데이트 합니다
     * ex) updateWithItemName(['colName', 'colName']);
     * ex) updateWithItemName('colName']);
     * @param $itemName array|string
     */
    public function updateWithItemName($itemName)
    {
        $key = $this->_primaryColumnName;

        if (!(int)$this->$key) {

            if (class_exists("platyFramework\\ptylogsItemsModel")) {
                ptylogsItemsModel::build()->addLogs("ptyItemModel", "updateWithItemName", "", "", "id is null.", print_r($this, true));
            }

            die ("updateWithItemName() item->id 가 없습니다");
        }

        $this->db->clear();

        if (is_array($itemName))
            foreach ($itemName as $k => $v) {

                // 1 => col1, 2 => col2
                if (is_int($k)) {
                    $left = $v;
                    $right = $v;
                }
                //
                else {
                    $left = $k;
                    $right = $k;
                }
                $this->db->addSet($left, $this->_item[$right]);
            }
        else
            $this->db->addSet($itemName, $this->_item[$itemName]);

        $this->db->addFrom($this->_tableName)
            ->addWhereEqual($key, $this->$key)
            ->update();
    }

    public function setDisable()
    {
//		if (!($this->loginUserItem->isAdmin || $this->userId == $this->loginUserItem->id))
//			ptyJsonReturnFalseDie(["alertMsg" => "권한이 없습니다"]);

        $this->enabled = 0;
        $this->updateWithItemName("enabled");

        return $this->item->enabled;
    }

    public function setEnableDisable()
    {
        $this->item->enabled = $this->item->enabled ? 0 : 1;
        $this->updateWithItemName("enabled");

        return $this->item->enabled;
    }

    /**
     * id 를 기준으로 데이터를 reload 합니다
     */
    public function reload()
    {
        $this->db->clear()->addSelect("*")->addFrom($this->_tableName)->addWhereEqual("id", $this->item->_item['id']);
        $item = $this->db->sql_fetch();
        $this->item->_item = $item;
    }

    /**
     * 수정시 DB 입력전 호출된다
     *
     * @param $oldItem
     * @param $newItem
     * @return bool
     */
    public function onItemEdit($oldItem, $newItem)
    {
        return true;
    }

    /**
     * 수정시 DB 입력후 호출된다
     * @param $oldItem
     * @param $newItem
     * @return $this
     */
    public function onItemEdited($oldItem, $newItem)
    {
        return $this;
    }

    /**
     * 신규의 DB 입력 전 호출된다.
     * 입력된 신규 데이터의 참조는 $this->item... 을 참고하면 된다
     */
    public function onItemAdd($item)
    {
        return $this;
    }

    /**
     * 신규의 DB 입력 후 호출된다.
     * 입력된 신규 데이터의 참조는 $this->item... 을 참고하면 된다
     */
    public function onItemAdded($item)
    {
        return $this;
    }

    /**
     * @param $keyName
     * @param int $position
     * @return ptyItemModel
     */
    public function getFileItem($keyName, $position = 0)
    {
        $fileItemsModel = new ptyfileItemsModel();
        $item = $fileItemsModel->clear()->getItemBy([
            "tableName" => str_replace("t_", "", $this->_tableName),
            "tableId" => $this->id, "keyName" => $keyName, "position" => $position]);

        return $item;
    }


    /**
     * id 를 기준으로 추가하거나 수정합니다
     *
     * @return ptyItemModel
     */
    /*
    ex)
    // 아이템을 추가하거나 등록합니다
    $params = $this->getPropertyParams();
    $siteItem = siteItemsModel::buildItem(
        $params->getItem(["id" => "siteId", "title", ])
    );
    $siteItem->modify();
    */
    public function x_modify()
    {
        $ip = $this->request->ip;

        $colNames = "`" . implode("`, `", array_keys($this->_item)) . "`";
        $values = "'" . implode("', '", array_values($this->_item)) . "'";
        $_values2 = array();
        foreach ($this->_item as $k => $v) {
            if ($k == "id")
                continue;

            $_values2[] = "`$k` = '$v'";
        }
        $values2 = "" . implode(", ", $_values2) . "";

        $sql = "INSERT INTO $this->_tableName \n(regDateTime, ip, $colNames) \nVALUES (NOW(), '$ip', $values) \nON DUPLICATE KEY UPDATE regDateTime=NOW(), ip='$ip', $values2";
        $this->db->sql_query($sql);

        $lastInsertId = $this->db->getInsertId();
        if ($lastInsertId)
            $this->id = $lastInsertId;

        return $this;
    }

    public function modify()
    {
        $_colNames = array();
        $_values = array();
        $_values2 = array();

        // 신규라면
        if (!isset($this->_item['id'])) {
            $new = true;
            $_colNames[] = "regDateTime";
            $_values[] = "NOW()";

            $_colNames[] = "ip";
            $_values[] = "'{$this->request->ip}'";
        }

        foreach ($this->_item as $k => $v) {
            if ($k == "id")
                continue;

            $_colNames[] = $k;
            $v = addslashes($v);
            if (stripos($v, "/*RAW*/") !== false) {
                $_values2[] = "`$k` = " . substr($v, 7);
                $_values[] = substr($v, 7);
            } else {
                $_values2[] = "`$k` = '$v'";
                $_values[] = "'$v'";
            }
        }

        $colNames = "`" . implode("`, `", $_colNames) . "`";
        $values = "" . implode(", ", $_values) . "";
        $values2 = "" . implode(", ", $_values2) . "";

        $sql = "INSERT INTO $this->_tableName \n($colNames) \nVALUES ($values) \nON DUPLICATE KEY UPDATE $values2";
        $this->db->sql_query($sql);

        if ($new) {
            $lastInsertId = $this->db->getInsertId();
            if ($lastInsertId) {
                $this->id = $lastInsertId;
                $descId = (int)$this->id * -1;
                $sql = "UPDATE $this->_tableName SET descId = $descId";
                $this->db->sql_query($sql);
            }
        }

        return $this;
    }

    public function unsetVar($string)
    {
        unset($this->_item[$string]);
    }


    public function compareFieldToString($targetItem)
    {
        $r = array_diff($this->_item, $targetItem->_item);
        $msg = array();

        foreach ($r as $k => $v) {
            if (strstr($k, "password"))
                continue;

            $oldValue = $this->_item[$k];
            $newValue = $targetItem->_item[$k];
            $msg[] = "$k : $oldValue => $newValue";
        }

        //
        $r = array_diff($targetItem->_item, $this->_item);

        foreach ($r as $k => $v) {
            if (strstr($k, "password"))
                continue;

            $oldValue = $this->_item[$k];
            $newValue = $targetItem->_item[$k];
            $msg[] = "$k : $oldValue => $newValue";
        }

        return $msg;
    }


}

