<?php
    include_once("CUserSession.php");
    include_once("helper.php");
    include_once("CUtil.php");
    include_once("CProjectInfo.php");
    include_once("CEnums.php");
    include_once("CProjectSolutions.php");

    class Comment{

        public $sl_no;
        public $conversation_id;
        public $sub_id;
        public $user_id;
        public $comment;
        public $visibility;
        public $timestamp;
        public $user_status; // if user_id is creater of the project/conversation_id then user_status is creater.
                             // this flag is used to identify if the user is client or the reviewer which is used on UI for displaying icon
        public $comment_owner;

        function populateFromDBRow( $row ){
            $this->sl_no = $row["sl_no"];
            $this->conversation_id = $row["conversation_id"];
            $this->sub_id = $row["sub_id"];
            $this->user_id = $row["user_id"];
            $this->comment = $row["comment"];
            $this->visibility = $row["visibility"];
            $this->timestamp = $row["timestamp"];
        }
    }

    /*
         Insert a new user

        [sl_no], email_id, password, salt, first_name, middle_name, last_name
        organization_id, authtype_id, securityquestion_id, securityquestion_ans,
        [ts_created]
    */

    function add_new_comment( $user ){

        $sql_conn = mysqli_connection();
        $user = Util::escapeObject($user);
        $ret["success"] = true;
        $ret["message"] = "Comment added successfully";

        if (!($stmt = $sql_conn->prepare("INSERT INTO `UD_comments`(conversation_id, sub_id, user_id, comment, visibility ) VALUES (?,?,?,?,?)"))){
            $ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
            $ret["success"] = false;
        }

        if(!($stmt->bind_param("sssss",
                     $user->conversation_id,
                     $user->sub_id,
                     $user->user_id,
                     $user->comment,
                     $user->visibility
                      ))){
            $ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }

        if (!($ret_sql = $stmt->execute())) {
            $ret["message"] =  "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }

        $stmt->close();
        mysqli_close($sql_conn);
        return $ret;
    }


    /*
         Create a new user

        [sl_no], email_id, password, salt, first_name, middle_name, last_name
        organization_id, authtype_id, securityquestion_id, securityquestion_ans,
        [ts_created]
    */

    function set_comment( $conversation_id, $sub_id,
                            $comment, $visibility = 'all'){

        $sql_conn = mysqli_connection();

        $user = new Comment();
        $user->conversation_id = $conversation_id;
        $user->sub_id = $sub_id;
        $user->comment = $comment;
        $user->user_id = $_SESSION['user']->_id;
        $user->visibility = $visibility;

        $user = Util::escapeObject($user);
        $ret = add_new_comment($user);

        return $ret;
    }

    // get comments based on project_id and solution id
    function get_comments( $conversation_id, $sub_id ){
        $sql_conn = mysqli_connection();

        $ret["success"] = true;

        $user_id = $_SESSION['user']->_id;
        $sql = "SELECT * FROM  `UD_comments` WHERE (conversation_id like '".$conversation_id."' AND sub_id like '".$sub_id."' ) AND ( visibility='all' OR user_id like '".$user_id."' ) ORDER BY timestamp";
        $owner = get_owner_of_project($conversation_id);
        $owner = $owner["creater_id"];
        $review_checkbox_value = get_review_checkbox_value($conversation_id, $sub_id);
        $review_checkbox_value = $review_checkbox_value["review_checkbox_value"];
        /*
        if (!($stmt = $sql_conn->prepare($s))){
            $ret["message"] = "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error. $s;
            $ret["success"] = false;
        }

        if (!($ret_sql = $stmt->execute())) {
            $ret["message"] = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }

        if (!($ret_sql = $stmt->get_result())) {
            $ret["message"] = "Getting Result failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }
        */
        try
        {
            $result = mysqli_query($sql_conn, $sql);
            $comment = new Comment();
            $res = array();
            while($row = mysqli_fetch_array($result)) {
                $comment = new Comment();
                $comment->populateFromDBRow($row);
                $comment->user_status = $comment->user_id == $owner ? "creater" :"other";
                $comment->comment_owner = $comment->user_id == $user_id ? "yes" :"no";
                $res[] = $comment;
            }
        }
        catch (Exception $e){
            $ret["success"] = false;
            $res['message'] = "Error : ".$e->getMessage();
        }

        $ret["comments"] = $res;
        $ret["review_checkbox_value"] = $review_checkbox_value;
        mysqli_close($sql_conn);
        //$r = json_encode($ret);
        //echo "hello : ". $r;
        return $ret;
    }

    // get all comments based on project_id
    // we can put this in get_comments() function but we might need to format this all comments differently.
    function get_all_comments( $conversation_id ){
        $sql_conn = mysqli_connection();

        $ret["success"] = true;

        $user_id = $_SESSION['user']->_id;
        //$sql = "SELECT * FROM  `UD_comments` WHERE conversation_id like '".$conversation_id."' ORDER BY sl_no";
        $sql = "SELECT UD_comments.sl_no, conversation_id, sub_id, user_id, comment, visibility, UD_comments.timestamp, Users_temp.email_id, standard_text, UD_S_Headings.h2_sec_title FROM UD_comments LEFT JOIN UD_S_Solutions ON `sub_id`=`standard#` LEFT JOIN UD_S_Headings ON sub_id=credit LEFT JOIN Users_temp ON UD_comments.user_id=Users_temp._id WHERE ( conversation_id like '".$conversation_id."' ) AND ( visibility='all' OR user_id like '".$user_id."' ) ORDER BY UD_comments.sub_id";
        $owner = get_owner_of_project($conversation_id);
        $owner = $owner["creater_id"];
        /*
        if (!($stmt = $sql_conn->prepare($s))){
            $ret["message"] = "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error. $s;
            $ret["success"] = false;
        }

        if (!($ret_sql = $stmt->execute())) {
            $ret["message"] = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }

        if (!($ret_sql = $stmt->get_result())) {
            $ret["message"] = "Getting Result failed: (" . $stmt->errno . ") " . $stmt->error;
            $ret["success"] = false;
        }
        */
        try
        {
            $result = mysqli_query($sql_conn, $sql);
            $res = array();
            while($row = mysqli_fetch_array($result)) {
                $comment['sl_no'] = $row['sl_no'];
                $comment['conversation_id'] = $row['conversation_id'];
                $comment['sub_id'] = $row['sub_id'];
                $comment['user_id'] = $row['user_id'];
                $comment['comment'] = $row['comment'];
                $comment['visibility'] = $row['visibility'];
                $comment['timestamp'] = $row['timestamp'];
                $comment['email_id'] = $row['email_id'];
                $comment['standard_text'] = $row['standard_text'];
                $comment['h2_sec_title'] = $row['h2_sec_title'];
                $comment['user_status'] = $comment['user_id'] == $owner ? "creater" :"other";
                $comment['comment_owner'] = $comment['user_id'] == $user_id ? "yes" :"no";
                $res[] = $comment;
            }
        }
        catch (Exception $e){
            $ret["success"] = false;
            $res['message'] = "Error : ".$e->getMessage();
        }

        $ret["comments"] = $res;
        mysqli_close($sql_conn);
        //$r = json_encode($ret);
        //echo "hello : ". $r;
        return $ret;
    }

    function set_comment_visibility( $conversation_id, $sub_id, 
                            $visibility = 'all'){
        // $sql_update = "UPDATE `UD_solutions` SET `review_checkbox`= ".$value." WHERE project_id LIKE '".$project_id."' and solution LIKE '".$solution."'";
        $user_id = $_SESSION['user']->_id;
        $sql_update = "UPDATE `UD_comments` SET `visibility`= '".$visibility. "' WHERE visibility='self' and conversation_id like '".$conversation_id."' and sub_id like '".$sub_id."' and user_id like '".$user_id."' and sub_id NOT IN ('full','prelim','summary','cert')";
        return write_db( $sql_update );
    }

    function set_comment_visibility_by_no( $sl_no, $visibility = 'all'){
        // $sql_update = "UPDATE `UD_solutions` SET `review_checkbox`= ".$value." WHERE project_id LIKE '".$project_id."' and solution LIKE '".$solution."'";
        $user_id = $_SESSION['user']->_id;
        $sql_update = "UPDATE `UD_comments` SET `visibility`= '".$visibility. "' WHERE sl_no like '".$sl_no."' and user_id like '".$user_id."'";
        return write_db( $sql_update );
    }

    function update_comment_text( $sl_no, $text ){
        // $sql_update = "UPDATE `UD_solutions` SET `review_checkbox`= ".$value." WHERE project_id LIKE '".$project_id."' and solution LIKE '".$solution."'";
        $user_id = $_SESSION['user']->_id;
        $sql_update = "UPDATE `UD_comments` SET `comment`= '".$text. "' WHERE sl_no like '".$sl_no."' and user_id like '".$user_id."'";
        return write_db( $sql_update );
    }

    function get_comment_solution_status( $conversation_id )
    {
        $sql_conn = mysqli_connection();
        $user_id = $_SESSION['user']->_id;
        $ret["success"] = true;

        $sql = "SELECT sub_id FROM `UD_comments` WHERE conversation_id like '".$conversation_id."' AND ( visibility='all' OR user_id like '".$user_id."' )GROUP BY sub_id ORDER BY sub_id";
        
        try
        {
            $result = mysqli_query($sql_conn, $sql);
            $res = array();
            while($row = mysqli_fetch_array($result)) {
                $res[] = $row['sub_id'];
            }
        }
        catch (Exception $e){
            $ret["success"] = false;
            $ret['message'] = "Error : ".$e->getMessage();
        }

        $ret["solutions"] = $res;
        mysqli_close($sql_conn);
        //$r = json_encode($ret);
        //echo "hello : ". $r;
        return $ret;
    }

    function get_owner_of_project($conversation_id)
    {
        $sql_conn = mysqli_connection();

        $ret["success"] = true;

        $sql = "SELECT creating_user_id FROM `UD_P_Info` where _id like '".$conversation_id."'";
        
        try
        {
            $result = mysqli_query($sql_conn, $sql);
            $row = mysqli_fetch_array($result);
            $ret["creater_id"] = $row[0];
        }
        catch (Exception $e){
            $ret["success"] = false;
            $ret['message'] = "Error : ".$e->getMessage();
        }

        mysqli_close($sql_conn);
        return $ret;
    }

    function get_review_checkbox_value($project_id, $solution)
    {
        $sql_conn = mysqli_connection();

        $ret["success"] = true;

        $sql = "SELECT review_checkbox FROM `UD_solutions` where project_id like '".$project_id."' and solution like '".$solution."'";
        
        try
        {
            $result = mysqli_query($sql_conn, $sql);
            $row = mysqli_fetch_array($result);
            $ret["review_checkbox_value"] = $row[0];
        }
        catch (Exception $e){
            $ret["success"] = false;
            $ret['message'] = "Error : ".$e->getMessage();
        }

        mysqli_close($sql_conn);
        return $ret;
    }


?>