<?php

function can_upload_attachment(&$Mode, $trans_type, $trans_no, $line_id, $description, $selected_id) {
    global $systypes_array;
    
    if (! key_exists($trans_type, $systypes_array)) {
        return array('success' => false, 'message' => "Invalid transaction type.");
    }
    
    if (! ($trans_no > 0)) {
        return array('success' => false, 'message' => "Invalid trans no.");
    }
    
    if (! transaction_exists($trans_type, $trans_no, $line_id)) {
        $line_text = $line_id > 0 ? " and line #$line_id " : '';
        return array('success' => false, 'message' => $systypes_array[$trans_type]." trans #$trans_no $line_text does not exists.");
    } 
    
    if ($selected_id > 0) {
        $row = get_attachment($selected_id);
            if (! (isset($row['id']) && $row['id'] > 0)) {
                return array('success' => false, 'message' => "Could not find attachment #$selected_id.");
            }

        $user_id = $_SESSION['wa_current_user']->user;
            if ($user_id != $row['created_by']) {
                return array('success' => false, 'message' => "Only allow to edit attachment #$selected_id its creator.");
            }
    }
    
    if (! (strlen($description) > 0)) {
        return array('success' => false, 'message' => "Description cannot empty.");
    } 
    
    if ($Mode == 'ADD_ITEM' && (! isset($_FILES['filename']) || $_FILES['filename']['size'] == 0)) {
        return array('success' => false, 'message' => "Select attachment file.");
    }
    
    $filetype = $_FILES['filename']['type'];
    if ($filetype != "application/pdf") {
//        return array('success' => false, 'message' => "Only pdf file can be uploaded. Please file is converted to pdf then upload.");
    }
    
        return array('success' => true, 'message' => "");
}

function upload_attachment(&$Mode, $trans_type, $trans_no, $line_id, $description, $selected_id) {
    $can_update = can_upload_attachment($Mode, $trans_type, $trans_no, $line_id, $description, $selected_id);
        if ($can_update['success'] === false) {
            return $can_update;
        }
        
            //$content = base64_encode(file_get_contents($_FILES['filename']['tmp_name']));
            $tmpname = $_FILES['filename']['tmp_name'];

            $dir =  company_path()."/attachments";
		if (! file_exists($dir)) {
                    mkdir ($dir,0777);
                    $index_file = "<?php\nheader(\"Location: ../index.php\");\n?>";
                    $fp = fopen($dir."/index.php", "w");
                    fwrite($fp, $index_file);
                    fclose($fp);
		}

		$filename = basename($_FILES['filename']['name']);
		$filesize = $_FILES['filename']['size'];
		$filetype = $_FILES['filename']['type'];

		// file name compatible with POSIX
		// protect against directory traversal
		if ($Mode == 'UPDATE_ITEM') {
		    $row = get_attachment($selected_id);
                        if ($row['filename'] == "") {
                            exit();
                        }
                    
                    $unique_name = $row['unique_name'];
			if ($filename && file_exists($dir."/".$unique_name)) {
                            unlink($dir."/".$unique_name);
                        }
		} else {
                    $unique_name = uniqid('');
                }

		//save the file
		move_uploaded_file($tmpname, $dir."/".$unique_name);

		if ($Mode == 'ADD_ITEM') {
                    $in_id = add_attachment($trans_type, $trans_no, $description, $filename, $unique_name, $filesize, $filetype, $line_id);
                        if (! ($in_id > 0)) {
                            return array('success' => false, 'message' => "Could not add new attachment file.");
                        } else {
                            return array('success' => true, 'message' => "Attachment #$in_id has been inserted.");
                        }
		} else {
                    $af_rw = update_attachment($selected_id, $description, $filename, $unique_name, $filesize, $filetype); 
                        if ($af_rw != 1) {
                            return array('success' => false, 'message' => "Could not update attachment #$selected_id.");
                        } else {
                            return array('success' => true, 'message' => "Attachment #$selected_id has been updated.");
                        }
		}
}

function delete_attachment_file($selected_id) {
    $row = get_attachment($selected_id);
        if (! is_array($row)) {
            return array('success' => false, 'message' => "Attachment #$selected_id is already deleted by another user.");
        }
        
    $user_id = $_SESSION['wa_current_user']->user;
        if ($user_id != $row['created_by']) {
            return array('success' => false, 'message' => "Only allow to delete attachment #$selected_id its creator.");
        }
        
    $dir =  company_path()."/attachments";
	if (file_exists($dir."/".$row['unique_name'])) {
            unlink($dir."/".$row['unique_name']);
        }
        
    $af_row = delete_attachment($selected_id);
        if ($af_row != 1) {
            return array('success' => false, 'message' => "Attachment #$selected_id could not delete.");
        } else {
            return array('success' => true, 'message' => "Attachment #$selected_id has been deleted.");
        }
}

function trans_view($trans) {
    return get_trans_view_str($trans["type_no"], $trans["trans_no"]);
}

function _line_id($trans) {
    return $trans["line_id"] > 0 ? $trans["line_id"] : null;
}

function _created_by($trans) {
    $row = get_user($trans["created_by"]);
        if (isset($row['id']) && $row['id'] > 0) {
            return $row['real_name'];
        } else {
            return;
        }
}

function edit_link($row) {
    return button('Edit'.$row["id"], _("Edit"), _("Edit"), ICON_EDIT);
}

function view_link($row) {
    return button('view'.$row["id"], _("View"), _("View"), ICON_VIEW);
}

function download_link($row) {
    return button('download'.$row["id"], _("Download"), _("Download"), ICON_DOWN);
}

function delete_link($row) {
    return button('Delete'.$row["id"], _("Delete"), _("Delete"), ICON_DELETE);
}

function display_attachments_details($type, $trans_no=0, $line_id=0) {
    $sql = get_sql_for_attached_documents($type, $trans_no, $line_id);
	$cols = array(
            _("Id") => array('name'=>'id', 'align' => 'center', 'ord'=>''),
            _("Trans#") => array('fun'=>'trans_view'),
            _("Line Id") => array('fun'=>'_line_id', 'align' => 'center'),
	    _("Description") => array('name'=>'description'),
	    _("Filename") => array('name'=>'filename'),
	    _("Size") => array('name'=>'filesize'),
	    _("Filetype") => array('name'=>'filetype'),
	    _("Creator") => array('fun'=>'_created_by'),
	    _("Date Uploaded") => array('name'=>'tran_date', 'type'=>'date'),
	    	array('insert'=>true, 'fun'=>'edit_link'),
	    	array('insert'=>true, 'fun'=>'view_link'),
	    	array('insert'=>true, 'fun'=>'download_link'),
	    	array('insert'=>true, 'fun'=>'delete_link')
	    );	
		$table =& new_db_pager('trans_tbl', $sql, $cols);

		$table->width = "90%";

		display_db_pager($table);
}

function view_attachments_details($type, $trans_no=0, $line_id=0) {
    $sql = get_sql_for_attached_documents($type, $trans_no, $line_id);
	$cols = array(
            _("Id") => array('name'=>'id', 'align' => 'center', 'ord'=>''),
            _("Trans#") => array('fun'=>'trans_view'),
            _("Line Id") => array('fun'=>'_line_id', 'align' => 'center'),
	    _("Description") => array('name'=>'description'),
	    _("Filename") => array('name'=>'filename'),
	    _("Size") => array('name'=>'filesize'),
	    _("Filetype") => array('name'=>'filetype'),
	    _("Date Uploaded") => array('name'=>'tran_date', 'type'=>'date'),
	    	array('insert'=>true, 'fun'=>'view_link'),
	    	array('insert'=>true, 'fun'=>'download_link')
	    );	
		$table =& new_db_pager('trans_tbl', $sql, $cols);

		$table->width = "80%";

		display_db_pager($table);
}

function display_attachment_control(&$Mode, &$selected_id) {
    start_table(TABLESTYLE2);

        if ($selected_id > 0) {
            if ($Mode == 'Edit') {
                $row = get_attachment($selected_id);
                    $_POST['description'] = $row["description"];
                    hidden('trans_no', $row['trans_no']);
                    hidden('unique_name', $row['unique_name']);
                    label_row(_("Id #"), $selected_id);
            }	
            hidden('selected_id', $selected_id);
        } 
        
        text_row_ex(_("Description:"), 'description', 40);
        file_row(_("Attached File:"), 'filename', 'filename');

    end_table(1);

    submit_add_or_update_center($selected_id == -1, '', 'process');
}