<?php

class Form {


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


    public function getForms(){
        $query = $this->_conn->query("SELECT `forms`.`id`, `forms`.`fileName`, `forms`.`formFor`, `forms`.`file`, `forms`.`dateAdded`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM `forms`, `users` WHERE `forms`.`uploadedBy` = `users`.`id` ORDER BY dateAdded DESC");
        if($query->num_rows > 0){
            $data = [];
            while($row = $query->fetch_assoc()){
                $data[] = $row;
            }
            $this->_res = ['status'=>'ok', 'message'=>'', 'data'=>$data];
        }else{
            $this->_res = ['status'=>'error', 'message'=>'No form found', 'data'=>null];
        }
        return $this->_res;
    }

    public function saveForm($data){

        $path = '../../documents/forms/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        if(isset($_FILES['file']['name']) && $_FILES['file']['size'] > 0) {
            
            $original_filename = $_FILES['file']['name'];
            $ext = '.'.pathinfo($original_filename, PATHINFO_EXTENSION);
            $t=time();
            $generatedName = md5($t.$original_filename).$ext;
            $filePath = $path.$generatedName;
            $tmp  = $_FILES['file']['tmp_name'];
            //check if file exist
            if(file_exists($filePath)) unlink($filePath);
            
            //upload file
            if(move_uploaded_file($tmp, $filePath)){
                
                $query_string = "INSERT INTO `forms`(`fileName`,  `formFor`, `file`, `uploadedBy` ) VALUES('".$data['fileName']."', '".$data['formFor']."', '".$generatedName."', '".$this->_userId."')";
                $query = $this->_conn->query($query_string);

                if($query){
                    
                    $query_get = $this->_conn->query("SELECT `forms`.`id`, `forms`.`fileName`, `forms`.`formFor`, `forms`.`file`, `forms`.`dateAdded`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM `forms`, `users` WHERE `forms`.`uploadedBy` = `users`.`id` ORDER BY dateAdded DESC");
                    $data = [];
                    while($row_get = $query_get->fetch_assoc()){
                        $data[] = $row_get;
                    }
                    $this->_res = ['status'=>'ok', 'message'=>'Form has been adeed', 'data'=>$data];

                }else{
                    $this->_res = ['status'=>'error', 'message'=>'Caould not upload file, Internal server Error!', 'data'=>null];
                    unlink($filePath);
                }

            }else{
                $this->_res = ['status'=>'error', 'message'=>'Could not upload file, Internal error!', 'data'=>null];
            }
        
        }else{
            $this->_res = ['status'=>'error', 'message'=>'No form found to upload', 'data'=>null];
        }

        return $this->_res;
    }

    public function deleteForm($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']){

            $path = '../../documents/forms/';
            $query_check = $this->_conn->query("SELECT `file` FROM `forms` WHERE id = '".$data['id']."'");
            if($query_check->num_rows == 1){
                $row_check = $query_check->fetch_assoc();
                $file = $row_check['file'];
                $filename = $path.$file;
                $query_delete = $this->_conn->query("DELETE FROM `forms` WHERE `id` = '".$data['id']."'");
                unlink($filename);

                $query_get = $this->_conn->query("SELECT `forms`.`id`, `forms`.`fileName`, `forms`.`formFor`, `forms`.`file`, `forms`.`dateAdded`, CONCAT(`users`.`fname`, ' ', `users`.`lname`) as username FROM `forms`, `users` WHERE `forms`.`uploadedBy` = `users`.`id` ORDER BY dateAdded DESC");
                if($query_get->num_rows > 0){
                    $data = [];
                    while($row_get = $query_get->fetch_assoc()){
                        $data[] = $row_get;
                    }
                    $this->_res = ['status'=>'ok', 'message'=>'Form deleted', 'data'=>$data];
                }else{
                    $this->_res = ['status'=>'ok', 'message'=>'Form deleted', 'data'=>null];
                }

            }else{
                $this->_res = ['status'=>'error', 'message'=>'No forms found to delete!', 'data'=>null];
            }
        }else{
            $this->_res = ['status'=>'error', 'message'=>'Authentication Error!', 'data'=>null];
        }
        return $this->_res;
    }

}

?>