<?php

namespace Hura8\System\Model;

use Hura8\Database\iConnectDB;
use Hura8\Interfaces\TableName;

class WebUserModel
{

    protected   $user_browser_id = '';
    protected   $user_db_id = 0;
    private     $tb_user = TableName::WEB_USER; //"web_user_info";

    protected  $db;


    public function __construct($user_browser_id)
    {
        $this->db = get_db('', ENABLE_DB_DEBUG);
        $this->user_browser_id = preg_replace("/[^a-z0-9]/i", "", $user_browser_id);
        $this->user_db_id = (defined("USER_ID")) ? USER_ID : 0;
    }

    public function getValue($key) {
        $key = $this->cleanKey($key);

        $query = $this->db->runQuery("SELECT `content` FROM `".$this->tb_user."` 
                                            WHERE  `user_id` = ? AND `key` =  ?
                                            LIMIT 1 ", ['s', 's'], [ $this->user_browser_id , $key ]) ;
        if($rs = $this->db->fetchAssoc($query )){
            return \unserialize($rs['content']);
        }

        return null;
    }

    public function setValue($key, $value) {
        $key = $this->cleanKey($key);

        if($row_id = $this->checkKey($key)) {
            return $this->db->update(
                $this->tb_user ,
                [
                    'content' => \serialize($value) ,
                    'user_db_id' => $this->user_db_id ,
                    'last_update' => CURRENT_TIME ,
                ],
                [
                    'id' => $row_id,
                ]
            );

        }

        return $this->db->insert(
            $this->tb_user ,
            [
                'user_id' => $this->user_browser_id ,
                'user_db_id' => $this->user_db_id,
                'key' => $key,
                'content' => \serialize($value),
                'create_time' => CURRENT_TIME ,
                'last_update' => CURRENT_TIME,
            ]
        );
    }

    //delete all user history
    public function deleteUser($key) {
        $this->db->runQuery(
            "DELETE FROM `".$this->tb_user."` WHERE `user_id` = ? LIMIT 1 ",
            ['s'],
            [ $this->user_browser_id ]
        ) ;
    }

    protected function cleanKey($key) {
        return preg_replace("/[^a-z0-9]/i", "", $key);
    }

    protected function checkKey($key) {
        $query = $this->db->runQuery("SELECT `id` FROM `".$this->tb_user."` 
                                            WHERE `user_id` = ? AND `key` = ?
                                            LIMIT 1", ['s', 's'], [ $this->user_browser_id , $key ] ) ;
        if($rs = $this->db->fetchAssoc($query )){
            return $rs['id'];
        }

        return false;
    }
}
