<?php



class Document {

    private $_conn = null;
	private $_res = null;
	private $_userId = null;
	public function __construct($conn, $userId){
		$this->_conn = $conn;
		$this->_userId = $userId;
	}


    public function getDocuments($filter){
        $query_get = $this->_conn->query("SELECT `documents`.`id`, `documents`.`fileName`, `documents`.`file`, `documentTypes`.`name` as documentType, `documents`.`uploadDate`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM documents, documentTypes, users WHERE `documents`.`modelId` = '".$filter['modelId']."' AND `documents`.`modelName` = '".$filter['modelName']."' AND `documents`.`documentTypeId` = `documentTypes`.`id` AND `documents`.`uploadBy` = `users`.`id` ORDER BY `documents`.`uploadDate` DESC");
        $data = [];
        if($query_get->num_rows > 0){
            while($row_get = $query_get->fetch_assoc()){
                $data[] = $row_get;
            }
            $this->_res = ['status'=>'ok', 'message'=>'', 'data'=>$data];
        }else{
            $this->_res = ['status'=>'error', 'message'=>'No Documents found', 'data'=>$data];
        }

        return $this->_res;
        
    }

    public function deleteDocument($data){

        $query_auth = $this->_conn->query("SELECT `password` FROM `users` WHERE `id` = '".$this->_userId."'");
        $row_auth = $query_auth->fetch_assoc();
        $password = md5($data['password']);

        if($password == $row_auth['password']){
            //$temp = "SELECT * FROM `".$paymentTable."` WHERE `id` = '".$data['id']."'";
            //get payment id
            $query_check = $this->_conn->query("SELECT `modelId`, `modelName`, `file`, `documentTypeId` FROM documents WHERE `id` = '".$data['id']."'");
            if($query_check->num_rows == 1){
                $row_check = $query_check->fetch_assoc();
                $query_delete = $this->_conn->query("DELETE FROM documents WHERE `id` = '".$data['id']."'");
                $path = '../../documents/'.$row_check['modelName'].'/';
                if($query_delete){

                    if($data['modelName'] == 'case' ){
                        if($row_check['documentType'] == '3'){
                            $this->_conn->query("UPDATE `cases` SET `attendanceNoteReceived` = 'No' WHERE `id` = '".$data['modelId']."'");
                        }else if($row_check['documentType'] == '4'){
                            $this->_conn->query("UPDATE `cases` SET `courtBundleReceived` = 'No' WHERE `id` = '".$data['modelId']."'");
                        }else if($row_check['documentType'] == '2'){
                            $this->_conn->query("UPDATE `cases` SET `outstandingDocumentReceived` = 'No' WHERE `id` = '".$data['modelId']."'");
                        }
                    }


                    $filePath = $path.$row_check['file'];
                    if(file_exists($filePath)) unlink($filePath);
                    $query_get = $this->_conn->query("SELECT `documents`.`id`, `documents`.`fileName`, `documents`.`file`, `documentTypes`.`name` as documentType, `documents`.`uploadDate`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM documents, documentTypes, users WHERE `documents`.`modelId` = '".$row_check['modelId']."' AND `documents`.`modelName` = '".$row_check['modelName']."' AND `documents`.`documentTypeId` = `documentTypes`.`id` AND `documents`.`uploadBy` = `users`.`id` ORDER BY `documents`.`uploadDate` DESC");
                    $data = [];
                    if($query_get->num_rows > 0){
                        while($row_get = $query_get->fetch_assoc()){
                            $data[] = $row;
                        }
                    }
                    
                    $this->_res = ['status'=>'ok', 'message'=>'File Deleted nicely!', 'data'=>$data]; 
                }else{
                    $this->_res = ['status'=>'error', 'message'=>'Could not delete file!', 'data'=>null]; 
                }
            }else{
                $this->_res = ['status'=>'error', 'message'=>'No data found to delete!', 'data'=>null]; 
            }
            // $this->_res = ['status'=>'error', 'message'=>'Could not delete payment record!', 'data'=>$temp];
        }else{
            $this->_res = ['status'=>'error', 'message'=>'Authorisation failed. Password did not match!', 'data'=>$data];
        }

        return $this->_res;
    }
    
    public function saveDocument($data){
        $path = '../../documents/'.$data['modelName'].'/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $query_string = "";
        $uploadedFile = [];
        $uploadedId = [];
        $total_files = count($_FILES['file']['name']);

        for($key = 0; $key < $total_files; $key++) {

            $documentType = $data['type'][$key];
            // Check if file is selected
            if(isset($_FILES['file']['name'][$key]) && $_FILES['file']['size'][$key] > 0) {
            
                $original_filename = $_FILES['file']['name'][$key];
                $ext = '.'.pathinfo($original_filename, PATHINFO_EXTENSION);
                $t=time();
                $generatedName = md5($t.$original_filename).$ext;
                $filePath = $path.$generatedName;
                $tmp  = $_FILES['file']['tmp_name'][$key];
                //check if file exist
                if(file_exists($filePath)) unlink($filePath);
                
                //upload file
                if(move_uploaded_file($tmp, $filePath)){
                    
                    $query_string = "INSERT INTO `documents`(`modelId`,  `modelName`, `fileName`, `file`, `documentTypeId`, `uploadBy` ) VALUES('".$data['modelId']."', '".$data['modelName']."', '".$original_filename."', '".$generatedName."', '".$documentType."', '".$this->_userId."')";
                    $query = $this->_conn->query($query_string);

                    if($data['modelName'] == 'case' ){
                        if($documentType == '3'){
                            $this->_conn->query("UPDATE `cases` SET `attendanceNoteReceived` = 'Yes' WHERE `id` = '".$data['modelId']."'");
                        }else if($documentType == '4'){
                            $this->_conn->query("UPDATE `cases` SET `courtBundleReceived` = 'Yes' WHERE `id` = '".$data['modelId']."'");
                        }else if($documentType == '2'){
                            $this->_conn->query("UPDATE `cases` SET `outstandingDocumentReceived` = 'Yes' WHERE `id` = '".$data['modelId']."'");
                        }
                    }

                    if($query){
                        $uploadedId[] = $this->_conn->insert_id;
                        $uploadedFile[] = ['file'=>$generatedName];
                    }else{
                        unlink($filePath);
                    }

                }
            
            }
            
        }
        if(count($uploadedFile) > 0){
            $query_get = $this->_conn->query("SELECT `documents`.`id`, `documents`.`fileName`, `documents`.`file`, `documentTypes`.`name` as documentType, `documents`.`uploadDate`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM documents, documentTypes, users WHERE `documents`.`modelId` = '".$data['modelId']."' AND `documents`.`modelName` = '".$data['modelName']."' AND `documents`.`documentTypeId` = `documentTypes`.`id` AND `documents`.`uploadBy` = `users`.`id` ORDER BY `documents`.`uploadDate` DESC");
            $data = [];
            if($query_get->num_rows > 0){
                while($row_get = $query_get->fetch_assoc()){
                    $data[] = $row_get;
                }
            }
            $this->_res = ['status'=>'ok', 'message'=>'File uploaded nicely!', 'data'=>$data];
        }else{
            foreach($uploadedId as $id){
                $query_check = $this->_conn->query("SELECT `file` FROM documents WHERE `id` = '".$id."'");
                if($query_check->num_rows == 1){
                    $row_check = $query_check->fetch_assoc();
                    $query_delete = $this->_conn->query("DELETE FROM documents WHERE `id` = '".$id."'");
                    if($query_delete){
                        $filePath = $path.$row_check['file'];
                        if(file_exists($filePath)) unlink($filePath);
                    }
                }
            }
            $this->_res = ['status'=>'error', 'message'=>'Error uploading files!', 'data'=>$query_string];
        }

        return $this->_res;
    }
}

?>