<?php
    include_once("CUserSession.php");
    include_once("CProject.php");
    include_once("helper.php");
    include_once("CUtil.php");

    class UD_Project_Document{

        public $sl_no;
        public $project_id;
        public $user_id;
        public $document_id;
        public $server_path;
        public $true_name;
        public $doc_type;
        public $timestamp;
        public $file_desc;
        function populateFromDBRow( $row ){
            $this->sl_no = $row["sl_no"];
            $this->project_id = $row["project_id"];
            $this->user_id = $row["user_id"];
            $this->document_id = $row["document_id"];
            $this->server_path = $row["server_path"];
            $this->true_name = $row["true_name"];
            $this->doc_type = $row["doc_type"];
            $this->timestamp = $row["timestamp"];
            $this->file_desc = $row["description"];
        }
        
    }
	// getProjectDocuments_DB('pr_c1f4cc2343');
	function getProjectDocuments_DB($project_id){
		$sql_conn = mysqli_connection();
        $res = array();
        $res['result'] = false;
        if(isLoggedIn()){
            
            $where = " WHERE `user_id` is not NULL";
            if($project_id != -1){
                $where = $where." AND `project_id` like '".$project_id."'";
            }

            $sql = "SELECT * FROM UD_P_Documents a join (select _id, last_name from `Users_temp`) b on a.user_id = b._id".$where." ORDER BY a.`sl_no`";
            $udProjectDocuments = array();
//             SELECT * FROM UD_P_Documents a join (select _id, last_name from `Users_temp`) b on a.user_id = b._id
// where `user_id` is not NULL AND `project_id` like 'pr_4e814507fa'
            try{
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) {

                    // hide fields
                    unset($row["user_id"]);
                    unset($row["sl_no"]);
                    unset($row["server_path"]);
                    foreach($row as $key => $val){
                        if(gettype($key) === "integer"){
                            unset($row[$key]);
                        }
                    }
                    $udProjectDocuments[] = $row;
                    $res['result'] = true;
                }
                mysqli_close($sql_conn);
                $res["data"] = $udProjectDocuments;
            } catch (Exception $e){
                $res['message'] = "Error : ".$e->getMessage();
            }
        } else {
            $res['message'] = "Error : User not logged in";
        }
        
        $r = json_encode($res);
        // print($r);
        return $r;
		
	}
    
    function addProjectDocument_DB($project_id, $document_id, $server_path, $true_name, $doc_type, $temp_file, $file_desc){
        $sql_conn = mysqli_connection();
        // $sql_conn->begin_transaction();

        $ret = array();
        $ret['response'] = false;
        if(isLoggedIn()){
            $projectDocument = new UD_Project_Document();
            $projectDocument->project_id = $project_id;
            $projectDocument->user_id = $_SESSION['user']->_id;
            $projectDocument->document_id = $document_id;
            $projectDocument->server_path = $server_path;
            $projectDocument->true_name = $true_name;
            $projectDocument->doc_type = $doc_type;
            $projectDocument->file_desc = $file_desc;
            $projectDocument = Util::escapeObject($projectDocument);
            $ret["response"] = false;

            if(!Util::uploadFile($temp_file, $server_path, $document_id."-".$true_name)){
                $ret["message"] = "Error uploading file";
                return $ret;
            } else {
                $ret["upload_name"] = $document_id."-".$true_name;
            }
            //$ret["data"] = var_dump($project);
            if (!($stmt = $sql_conn->prepare("INSERT INTO `UD_P_Documents`(project_id, user_id, document_id, server_path, true_name, document_type, description)
                                            VALUES (?,?,?,?,?,?,?)"))){
                $ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
                return $ret;
            }

            $server_path = $projectDocument->server_path . Util::$ds . $document_id."-".$true_name;
            if(!($stmt->bind_param("sssssss",
                            $projectDocument->project_id,
                            $projectDocument->user_id,
                            $projectDocument->document_id,
                            $server_path,
                            $projectDocument->true_name,
                            $projectDocument->doc_type,
                            $projectDocument->file_desc
                        ))){
                $ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
                return ret; 
            }

            $res = $stmt->execute();
            $ret['response'] = $res;
            $stmt->close();
            
        } else {
            $ret["message"] = "Error : User not logged in";
        }
        mysqli_close($sql_conn);
        
        return $ret;
    }

    function deleteProjectDocument_DB($project_id, $document_id){
        $sql_conn = mysqli_connection();
        //$sql_conn->begin_transaction();

        $ret = array();
        $ret['response'] = false;
        if(isLoggedIn()){
            $projectDocument = new UD_Project_Document();
            $projectDocument->project_id = $project_id;
            $projectDocument->user_id = $_SESSION['user']->_id;
            $projectDocument->document_id = $document_id;

            $projectDocument = Util::escapeObject($projectDocument);
            $ret["response"] = false;


            $where = "WHERE `user_id` like '".$_SESSION['user']->_id."'"." AND `project_id` like '".$project_id."' AND `document_id` like '".$document_id."'";

            $sql = "SELECT * FROM  UD_P_Documents ".$where." ORDER BY `UD_P_Documents`.`sl_no`";
            $udProjectDocuments = array();
            
            try{
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) {
                    $storeFolder = $row["server_path"];
                }
                mysqli_close($sql_conn);
            } catch (Exception $e){
                $res['message'] .= "Error : ".$e->getMessage();
            }

            if(Util::deleteFile($storeFolder)){
                $ret["response"] = true;
                $ret["delete_message"] = "Successfully deleted file : ".$storeFolder;                
            } else if(!file_exists($storeFolder)){
                
            }
            else {
                $ret["response"] = false;
                $ret["delete_message"] = "Failed to delete file : ".$storeFolder;
                return json_encode($ret);                
            }

            $sql_conn = mysqli_connection();
            if (!($stmt = $sql_conn->prepare("DELETE FROM `UD_P_Documents`
                                            WHERE project_id = ? AND user_id = ? AND document_id = ?"))){
                $ret["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error." ll";
                return $ret;
            }

            if(!($stmt->bind_param("sss",
                            $projectDocument->project_id,
                            $projectDocument->user_id,
                            $projectDocument->document_id
                        ))){
                $ret["message"] =  "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
                return ret; 
            }

            $res = $stmt->execute();
            $ret['response'] = $res;
            $stmt->close();
            
        } else {
            $ret["message"] = "Error : User not logged in";
        }
        mysqli_close($sql_conn);
        
        return json_encode($ret);
    }
	
    
    function updateProjectDocuments_DB($project_id, $document_id, $server_path='', $true_name='', $doc_type=''){
        $sql_conn = mysqli_connection();

        $ret = array();
        $ret['response'] = false;
        if(isLoggedIn()){
            $projectDocument = new UD_Project_Document();
            $projectDocument->project_id = $project_id;
            $projectDocument->user_id = $_SESSION['user']->_id;;
            $projectDocument->document_id = $document_id;
            $projectDocument->server_path = $server_path;
            $projectDocument->true_name = $true_name;
            $projectDocument->doc_type = $doc_type;

            $projectDocument = Util::escapeObject($projectDocument);

            $query = "UPDATE  `UD_P_Documents` a
                                INNER JOIN
                                (
                                    SELECT  document_id, 
                                            server_path,
                                            true_name,
                                            doc_type
                                    FROM   `UD_P_Documents`
                                ) b ON  b.document_id = a.document_id
                        SET     a.server_path = IF('$projectDocument->server_path' > '', '$projectDocument->server_path', b.server_path),
                                a.true_name = IF('$projectDocument->true_name' > '', '$projectDocument->true_name', b.true_name),
                                a.doc_type = IF('$projectDocument->doc_type' > '', '$projectDocument->doc_type', b.server_path) 
                        WHERE 
                                    a.project_id = 'a' AND a.user_id = 'a' AND a.document_id = 'a'";

            if (!($stmt = $sql_conn->prepare($query))){
                $resp["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
                $resp["response"] = false;
            }

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

            if($ret){
                $resp["response"] = true;
                $resp["message"] = "";
            }

            $stmt->close();
        } else {
            $ret["message"] = "Error : User not logged in";
        }
        mysqli_close($sql_conn);
        return json_encode($resp);
    }

    function getProjectDocumentDetails_DB($project_id){
		$sql_conn = mysqli_connection();
        $res = array();

        if(isLoggedIn()){
            
            //$where = "WHERE `user_id` like '".$_SESSION['user']->_id."'";
            $where = "WHERE `user_id` IS NOT NULL";
            if($project_id != -1){
                $where = $where." AND `project_id` like '".$project_id."'";
            }

            $sql = "SELECT * FROM  UD_P_Documents ".$where." ORDER BY `UD_P_Documents`.`sl_no`";
            $udProjectDocuments = array();
            
            try{
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) {

                    // hide fields
                    unset($row["user_id"]);
                    unset($row["sl_no"]);
                    unset($row["server_path"]);
                    foreach($row as $key => $val){
                        if(gettype($key) === "integer"){
                            unset($row[$key]);
                        }
                    }
                    $udProjectDocuments[] = $row;
                    $res['success'] = true;
                }
                mysqli_close($sql_conn);
                // $res["data"] = $udProjectDocuments;
                $res = $udProjectDocuments;
            } catch (Exception $e){
                $res['message'] = "Error : ".$e->getMessage();
            }
        } else {
            $res['message'] = "Error : User not logged in";
        }

       
        $res['success'] = true;
        $r = json_encode($res);
        // echo $r;
        // echo "<script>console.log($r)</script>";
        return $res;
		
	}

    function get_required_doc_types_details($project_id)
    {
        $submitted_docs = getProjectDocumentDetails_DB($project_id);
        $required_doc_types = array();
        $required_doc_types = get_required_doc_types();

        // iterate over the each document type
        foreach($required_doc_types as $doc_type_key => $doc_type_value )
        {                    
            foreach ( $submitted_docs as $key => $value )
            {
                if ($key !== "success")
                {
                    $pos = strpos($value["document_type"],$doc_type_key);
                    if($pos)
                    {
                        $required_doc_types[$doc_type_key] = true;
                        break;
                    }
                }         
            }
        }

        foreach($required_doc_types as $doc_type_key => $doc_type_value )
        {
            if ($doc_type_value === false )
            {
                // echo "************ NOT ALL REQUIRED TYPES DOCS SUBMITTED *************";
                $required_doc_types["success"] = false;
                break;
            }    
        }
        
        // $rd = json_encode($required_doc_types);
        // echo "<script>console.log($rd)</script>";
        // $sd = json_encode($submitted_docs);
        // echo "<script>console.log($sd)</script>";
        // print($rd);
        // print($sd);
        return $required_doc_types;
    }

    function get_required_doc_types()
    {
        // to do : read this from the database
        $required_doc_types = array();
        $required_doc_types["Site Plan"] = false;
        $required_doc_types["Building Plans"] = false;
        $required_doc_types["Building Sections"] = false;
        $required_doc_types["Building Elevations"] = false;
        $required_doc_types["Details / Shop Drawings"] = false;
        $required_doc_types["Specifications"] = false;
        // $required_doc_types["Wall / Floor / Ceiling Finish Specifications"] = false;
        // $required_doc_types["Furnishing / Fixture Specifications"] = false;
        // $required_doc_types["Technology / Equipment Specifications"] = false;
        $required_doc_types["Policies"] = false;
        // $required_doc_types["Architect Certification of Complaince with Accessibitiy Laws"] = false;
        $required_doc_types["success"] = true;
        return $required_doc_types;
    }
// getProjectDocumentDetails("pr_1235fdc004");
     function getProjectDocumentDetails($project_id,$document_id = -1)
     {
		$sql_conn = mysqli_connection();
        $res = array();
        $res['success'] = false;

        if(isLoggedIn())
        {         
            $where = "WHERE b.`user_id` like '".$_SESSION['user']->_id."'";
            if($project_id != -1)
            {
                $where = $where." AND b.`project_id` like '".$project_id."'"; 
            }

            if($document_id != -1)
            {
                 $where = $where." AND a.`document_id` like '".$document_id."'";
            }
            
            $sql = "SELECT * FROM  UD_P_Documents as a JOIN `project_team` as b on a.project_id = b.project_id ".$where." ORDER BY a.`sl_no`";
            $udProjectDocuments = array();
            
            try
            {
                $result = mysqli_query($sql_conn, $sql);
                while($row = mysqli_fetch_array($result)) 
                {
                    // hide fields
                    unset($row["user_id"]);
                    unset($row["sl_no"]);
                    unset($row["server_path"]);
                    foreach($row as $key => $val)
                    {
                        if(gettype($key) === "integer")
                        {
                            unset($row[$key]);
                        }
                    }
                    $udProjectDocuments[] = $row;
                }                
                mysqli_close($sql_conn);

                $num_rows = count($udProjectDocuments);
                if($num_rows < 1)
                {
                    $res['success'] = false;
                    $res['message'] = "no_document_for_given_project";
                }
                else if( $document_id == -1 )
                {
                    $res = $udProjectDocuments;
                    $res['success'] = true;
                }
                else
                {
                    $res = $udProjectDocuments["0"];
                    $res['success'] = true;
                }
            } 
            catch (Exception $e)
            {
                $res['message'] = "Error : ".$e->getMessage();
            }
        }
        else 
        {
            $res['message'] = "Error : User not logged in";
        }

        // $r = json_encode($res);
        // echo $r;
        // echo "<script>console.log($r)</script>";
        return $res;
		
	}

    function updateDocumentDetails($project_id, $document_id, $types ,$name , $description)
    {
        if(isLoggedIn())
        { 
            $sql_conn = mysqli_connection();
            if(!($stmt = $sql_conn->prepare('UPDATE `UD_P_Documents` SET `true_name` = "'.$name.'", `document_type` = "'.$types.'", `description` = "'.$description.'" WHERE `document_id` like "'.$document_id.'" AND `project_id` like "'.$project_id.'"')))
            {
                $sql_ret =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
            }
                        
            if (!($sql_ret = $stmt->execute())) 
            {
                $sql_ret =  "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            }
            
            $stmt->close();
            mysqli_close($sql_conn);

            $ret['success'] = ($sql_ret === true);
            return ($ret);
        }
    }

    // getProjectDocumentDetails_DB('pr_019c934964','8ixvsj6z');
    // get_required_doc_types_details('pr_c1f4cc2343');
    // getProjectDocumentDetails('pr_019c934964','308rmjn5');
    // getProjectDocumentDetails('pr_019c934964');
    
    // updateDocumentDetails('pr_019c934964','308rmjn5','document:site planning;abc;xyz','ABC_Name_hahaha.pdf');
?>