<?php
require_once 'demosettings.php';
require_once 'write_log.php';
require_once 'sqlUtils.php';

//class flavor
class Tags{
    private $username ="";
    private $mysqli = "";
    
    public function __construct($mysqli, $username) {   
        $this->mysqli = $mysqli;
        $this->username = $username;
    }
    
    /**
     * 
     */
    public function getTagsTree(){
            write_to_log("TRACE","Fetching tag tree");
            
            $res = sqlQuery($this->mysqli, "SELECT DISTINCT groupName,exclusive FROM filetags where docId=0");
           
            $response = array();
            if ($res != false){
                while (($row_group = $res->fetch_object()) != false){
                    $exclusive = $row_group->exclusive == "0" ? false : true;
                    $tagGroup = $row_group->groupName;
                    $res_group = sqlQuery($this->mysqli, "SELECT DISTINCT name FROM filetags WHERE groupName='$tagGroup' AND docId=0");
                    $element_arr = array("id"=>$tagGroup, "name"=>$tagGroup, "exclusive"=>$exclusive, "children"=>array());
                    while (($row_name = $res_group->fetch_object()) != false){
                        $checked = false;
                        $tag_name = $row_name->name;  
                        $element_arr['children'][] = array("id"=>$tag_name, "name"=>$tag_name, "checked"=> $checked);
                    }
                    $response[] = $element_arr;
                }
            }   
            return $response;
        
    }
    
    /**
     * 
     */
    public function addToTagTree($tagGroup, $tags, $exclusive){
        //checks if taggroup exists with different exclusive
        $sql = "SELECT * FROM filetags WHERE groupName=\"$tagGroup\"";
        $res = sqlQuery($this->mysqli, $sql);
        if ($res != false){
            $obj = $res->fetch_object();
            if(!empty($obj)){
                $exclusive_val = $exclusive=="true" ? 1 : 0;
                if(intval($obj->exclusive) !== $exclusive_val){
                    return "exclusive error";
                }
            }
        }
        $values = "";
        $tags_arr = explode('^', $tags);
        foreach($tags_arr as $tag){
            $values .= "(\"$this->username\", 0, $exclusive, \"$tagGroup\", \"$tag\"),";
        }
        $values = rtrim($values, ',');
        $sql = "INSERT INTO filetags(username, docId, exclusive, groupName, name) VALUES $values;";
        $res = sqlQuery($this->mysqli, $sql);
        if ($res != false){
            write_to_log("TRACE","Fetching tag tree");
            return "ok";
        }
        write_to_log("ERROR","Failed:  addToTagTree($tagGroup, $tag, $exclusive)");
        
        return null;
    }
    
    /**
     *
     */
    public function removeFromTree($tagGroup = null , $tag = null){
        $sql = "DELETE FROM filetags WHERE username = \"$this->username\"";
        if(isset($tagGroup)){
            $sql .= " AND groupName = \"$tagGroup\" ";
        }
        if(isset($tag)) {
            $sql.= " AND Name = '$tag'";
        }
        $res = sqlQuery($this->mysqli, $sql);
        if ($res != false){
            write_to_log("TRACE","remove from tag tree");            
            return "ok";
        }
        write_to_log("ERROR","Failed: removeFromTree($tagGroup, $tag)");
        return null;
    }
    
    /**
     * Document actions 
     */
    
    /**
     * 
     */
    function getTagsPerDoc($docid){
        $res = sqlQuery($this->mysqli, "SELECT DISTINCT groupName,exclusive FROM filetags where docId=0");
        $doc_tags = array();
        $res_doc = sqlQuery($this->mysqli, "SELECT * FROM filetags where docId=$docid");
        while (($row = $res_doc->fetch_object()) != false){
            $doc_tags[$row->groupName][] = $row->name;
        }
       
        $response = array();
        if ($res != false){
            while (($row_group = $res->fetch_object()) != false){
                $exclusive = $row_group->exclusive == "0" ? false : true;
                $tagGroup = $row_group->groupName;
                $res_group = sqlQuery($this->mysqli, "SELECT DISTINCT name FROM filetags WHERE groupName='$tagGroup' AND docId=0");
                $element_arr = array("id"=>$tagGroup, "name"=>$tagGroup, "exclusive"=>$exclusive, "children"=>array());
                while (($row_name = $res_group->fetch_object()) != false){
                    $checked = false;
                    $tag_name = $row_name->name;
                    if(isset($doc_tags[$tagGroup])){
                        if(in_array($tag_name, $doc_tags[$tagGroup])){
                            $checked = true;
                        }
                    }
                    $element_arr['children'][] = array("id"=>$tag_name, "name"=>$tag_name, "checked"=> $checked);
                }
                $response[] = $element_arr;
            }
        }
        
        return $response;     
    }
    
    /**
     * 
     */
    
    function insertTag($docId, $tagName, $tagGroup) {
        $values = "";
        $tags_arr = explode('^', $tagName);
        foreach($tags_arr as $tag){
            $values .= "($docId, '$tag', '$tagGroup','$this->username'),";
        }
        $values = rtrim($values, ',');
        $sql = "INSERT INTO filetags(docId, name, groupName,username) VALUES $values";
        $res = sqlQuery($this->mysqli, $sql);
        if ($res != false){
            write_to_log("TRACE","insertTag");
            return "insertTag - ok";
        }
        write_to_log("ERROR","Failed: insertTag($docId, $tagName, $tagGroup)");
        return null;
    }
    
    /**
     * 
     */
    function deleteTags($tagGroup, $docId, $tagName = null) {
        $sql = "DELETE FROM filetags WHERE groupName=\"$tagGroup\" AND docId=$docId";
        if(isset($tagName)) {
            $sql.= " AND Name = '$tagName'";
        }
        $res = sqlQuery($this->mysqli, $sql);
        if ($res != false){
            write_to_log("TRACE","remove from tag tree");
            return "deleteTags - ok";
        }
        write_to_log("ERROR","Failed: deleteTags($tagGroup, $docId, $tagName = null)");
        return null;
    }
    
    function setTagsForSearch($tags){
        $tags_arr = json_decode($tags,true);
        $response = array("success" => "inserted batch tags");
        $ssid = getLastSavedSearchId($this->mysqli, $this->username);
        $sql = "SELECT docid FROM savedsearchid WHERE id=$ssid";
        $res = sqlQuery($this->mysqli, $sql);
        while(($row = $res->fetch_object()) != false){
            $docid = $row->docid;
            
            foreach($tags_arr as $tag){
                $insert_res = $this->insertTag($docid, $tag["tag"], $tag["group"]);
                if(empty($insert_res)){
                    $response = null;
                }
            }
        }
        return $response;
        
    }
    
    
    
}