<?php

if (!defined('sugarEntry') || !sugarEntry)
	die('Not A Valid Entry Point');
/* * *******************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 * ****************************************************************************** */
require_once ('include/upload_file.php');

// User is used to store Forecast information.
class Document extends SugarBean {

	var $id;
	var $document_name;
	var $doc_symbol;
	var $currency_value;
	var $description;
	var $document_date;
	var $category_id;
	var $subcategory_id;
	var $status_id;
	var $status;
	var $created_by;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $active_date;
	var $exp_date;
	var $document_revision_id;
	var $filename;
	var $img_name;
	var $img_name_bare;
	var $related_doc_id;
	var $related_doc_name;
	var $related_doc_rev_id;
	var $related_doc_rev_number;
	var $is_template;
	var $template_type;
	//additional fields.
	var $revision;
	var $last_rev_create_date;
	var $last_rev_created_by;
	var $last_rev_created_name;
	var $file_url;
	var $file_url_noimage;
	var $table_name = "documents";
	var $object_name = "Document";
	var $user_preferences;
	var $encodeFields = Array();
	// This is used to retrieve related fields from form posts.
	var $additional_column_fields = Array('revision');
	var $new_schema = true;
	var $module_dir = 'Documents';
	var $save_file;
	var $relationship_fields = Array(
		'contract_id' => 'contracts',
	);

	function Document() {
		parent :: SugarBean();
		$this->setupCustomFields('Documents'); //parameter is module name
		$this->disable_row_level_security = false;
	}

	function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean, $singleSelect = false) {
		global $current_user;
		$ret_array = parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
		// filtrowanie po dacie od do
		// filtrowanie po dacie od do
		$ret_array['where'] = str_replace("documents.date_start =", "documents.active_date > ", $ret_array['where']);
		$ret_array['where'] = str_replace("documents.date_end =", "documents.active_date < ", $ret_array['where']);
		$ret_array['where'] = preg_replace("/'%'(\w+)'%'/", '\'%${1}%\'', $ret_array['where']);
		$ret_array['where'] = str_replace("((documents.assigned_user_id = '" . $current_user->id . "'))", "(documents.id IN (SELECT rr.document_id from documents_user rr where rr.user_id='" . $current_user->id . "' and rr.accepted = '0'))", $ret_array['where']);
		return $ret_array;
	}

	function save($check_notify = false) {
	 /*
		if (empty($this->id) || $this->new_with_id) {
		  echo $this->id.'oks';
		  var_dump($this->uploadfile);
		  die();
			if (!empty($this->uploadfile)) {
				$this->uploadfile = $this->uploadfile;
				if (empty($this->id)) {
					$this->id = create_guid();
					$this->new_with_id = true;
				}
				/*
				$Revision = new DocumentRevision();
				//save revision.
				$Revision->change_log = translate('DEF_CREATE_LOG', 'Documents');
				$Revision->revision = $this->revision;
				$Revision->document_id = $this->id;
				$Revision->filename = $this->uploadfile;
				$Revision->file_ext = $this->file_ext;
				$Revision->file_mime_type = $this->file_mime_type;
				$Revision->save();
            
				//Move file saved during populatefrompost to match the revision id rather than document id
				echo UploadFile :: get_url($this->uploadfile, $this->id);
				die();

				//update document with latest revision id
				$this->process_save_dates = false; //make sure that conversion does not happen again.
				//$this->document_revision_id = $Revision->id;
			}

			//set relationship field values if contract_id is passed (via subpanel create)
			if (!empty($_POST['contract_id'])) {
				$save_revision['document_revision_id'] = $this->document_revision_id;
				$this->load_relationship('contracts');
				$this->contracts->add($_POST['contract_id'], $save_revision);
			}

			if ((isset($_POST['load_signed_id']) and ! empty($_POST['load_signed_id']))) {
				$query = "update linked_documents set deleted=1 where id='" . $_POST['load_signed_id'] . "'";
				$this->db->query($query);
			}
		}
		*/
		$return_id = parent::save($check_notify);
		// kontrahent // do zapłąty wieksze od 0 i termin
		//categories
		$json = getJSONobj();
		$pll = array();
		$exp = explode("||||", $_POST['position_list3']);
		foreach ($exp as $ep) {
			if ($ep) {
				$pll[] = $json->decode(htmlspecialchars_decode($ep));
			}
		}
		$_POST['position_list3'] = $pll;
		$this->savePositions3($_POST['position_list3']);
		// save parent list
		$pll = array();
		$f = 0;

		foreach ($_POST['list_id'] as $key => $value) {
			$pll[$key]['id'] = $_POST['list_id'][$key];
			$pll[$key]['parent_name'] = $_POST['parent_name'][$key];
			$pll[$key]['parent_type'] = $_POST['parent_type'][$key];
			$pll[$key]['parent_id'] = $_POST['parent_id'][$key];

			if ($pll[$key]['parent_id'] != '' && $pll[$key]['parent_type'] == 'Accounts' && $f == 0) {
				$this->parent_id = $pll[$key]['parent_id'];
				$this->parent_name = $pll[$key]['parent_name'];
				$f = 1;
			}
		}

		$this->saveParentList($pll);
		$vat_id = explode(',', $_POST['tblAppendGrid_rowOrder']);
		$vat_array = array();

		foreach ($vat_id as $value) {

			$vat_array[$value]['netto'] = $_POST['tblAppendGrid_netto_' . $value];
			$vat_array[$value]['vat'] = $_POST['tblAppendGrid_vat_' . $value];
			$vat_array[$value]['vat_id'] = $_POST['tblAppendGrid_vat_id_' . $value];
			$vat_array[$value]['vat_value'] = $_POST['tblAppendGrid_vat_value_' . $value];
		}

		$this->saveVatList($vat_array);
		// and saving parent list
		//save user list start Szparag
//        var_dump($_POST['user_id']);
//		die();
		$plluser = array();
		foreach ($_POST['user_id'] as $key => $value) {
			$plluser[$key]['user_id'] = $_POST['user_id'][$key];
			$plluser[$key]['accepted_description'] = $_POST['accepted_description'][$key];
			$plluser[$key]['accepted'] = $_POST['accepted'][$key];
			$plluser[$key]['date_accepted'] = $_POST['date_accepted'][$key];
		}
		$this->saveUserList($plluser);
		$res = $this->db->fetchByAssoc($this->db->query("select id from ecmtransactions where record_id='" . $return_id . "'"));

		if ($this->parent_name != '' && $this->parent_id != '' && $this->left_paid!='' && $this->payment_date != '') {

			if ($res['id'] == '')
				$this->saveTransaction($return_id, $this->left_paid);
			else
				$this->db->query("update ecmtransactions set value='" . $this->left_paid . "',parent_name='" . $this->parent_name . "',parent_id='" . $this->parent_id . "' where id='" . $res['id'] . "'");
		}
		// var_dump($ppluser);
		//save user list end
		return $return_id;
	}

	function saveTransaction($id, $total_brutto) {
		global $current_user;

		$t = new EcmTransaction ();
	
			$t->name = $this->document_name;
		
		$t->record_type = 'Documents';
		$t->record_id = $id;
		$t->created_by = $current_user->id;
		$t->deleted = 0;
		$t->assigned_user_id = $this->assigned_user_id;
		$t->parent_name = $this->parent_name;
		$t->parent_id = $this->parent_id;
		$t->payment_date = $this->payment_date;
		$t->type = 1;
		$t->type3=$this->transaction_type;
		$t->register_date = $this->document_date;
		$t->currency_id = $this->currency_id;
		$t->currency_value = $this->currency_value;
		$t->value = $total_brutto;
		$t->save(true);
	}

	function get_summary_text() {
		return "$this->document_name";
	}

	function is_authenticated() {
		return $this->authenticated;
	}

	function fill_in_additional_list_fields() {
		$this->fill_in_additional_detail_fields();
	}

	function getVatList($array = false) {
		if (isset($this->id) && $this->id != '') {

			$query = "SELECT * FROM documents_vat WHERE document_id='" . $this->id . "' AND deleted='0' order by position";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {

				while ($w = $this->db->fetchByAssoc($r)) {

					$return_array [] = $w;
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	function saveVatList($pl) {
		global $current_user;
		$exists = array();
		if ($this->id != '') {
			$GLOBALS['db']->query("delete FROM documents_vat WHERE document_id='" . $this->id . "'");
		}
		$positon = 0;
		foreach ($pl as $p) {
			//insert new record
			$id = create_guid();
			$t = array(
				$id,
				$this->id,
				addslashes($p['vat_value']),
				addslashes($p['vat_id']),
				addslashes($p['netto']),
				'0',
				addslashes($p['vat']),
				$positon,
			);
			$q = "INSERT INTO documents_vat VALUES ('" . implode("','", $t) . "')";
			$positon++;
			$GLOBALS['db']->query($q);
			$exists[] = $id;
		}
		//delete old
		// $GLOBALS['db']->query("UPDATE accounts_websites SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}

	function showVatList($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM documents_vat WHERE document_id='" . $this->id . "' AND deleted='0' ORDER BY position";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$return_array [] = $w;
				}

				$json = getJSONobj();
				return $array ? $return_array : $return_array;
			}
		}

		return $array ? false : '[]';
	}

	// multi connections start
	function getParentList($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM documents_accounts WHERE document_id='" . $this->id . "' AND deleted='0'";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					if ($w['parent_type'] != '') {
						$new = new $w['parent_type'];
						$new->retrieve($w['parent_id']);
						if (substr($w['parent_type'], 0, 3) != 'Ecm') {
							$w['parent_name'] = htmlspecialchars($new->name);
						} else {
							$w['parent_name'] = htmlspecialchars($new->document_no);
						}
						unset($new);
					}
					$return_array [] = $w;
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	function showParentList($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM documents_accounts WHERE document_id='" . $this->id . "' AND deleted='0'";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					if ($w['parent_type'] != '') {
						$new = new $w['parent_type'];
						$new->retrieve($w['parent_id']);
						if (substr($w['parent_type'], 0, 3) != 'Ecm') {
							$w['parent_name'] = $new->name;
						} else {
							$w['parent_name'] = $new->document_no;
						}
						unset($new);
					}
					$return_array [] = $w;
				}
				$json = getJSONobj();
				return $array ? $return_array : $return_array;
			}
		}
		return $array ? false : '[]';
	}

	function saveParentList($pl) {
		global $current_user;
		$exists = array();
		if ($this->id != '') {
			$GLOBALS['db']->query("delete FROM documents_accounts WHERE document_id='" . $this->id . "'");
		}
		foreach ($pl as $p) {
			if (!isset($p['parent_id']) || $p['parent_id'] == '')
				continue;

			//insert new record
			$id = create_guid();
			$t = array(
				$id,
				$this->id,
				addslashes($p['parent_id']),
				date("Y-m-d"),
				addslashes(substr($p['parent_type'], 0, -1)),
				'0',
				date("Y-m-d"),
			);
			$q = "INSERT INTO documents_accounts VALUES ('" . implode("','", $t) . "')";
			$GLOBALS['db']->query($q);
			$exists[] = $id;
		}
		//delete old
		// $GLOBALS['db']->query("UPDATE accounts_websites SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}

	//Start UserList
	function getUserList($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM documents_user WHERE document_id='" . $this->id . "'";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$new = new User();
					$new->retrieve($w['user_id']);
					$w['user_name'] = $new->first_name . ' ' . $new->last_name;
					unset($new);
					$return_array [] = $w;
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	//save into Documents_user list
	function saveUserList($pl) {
		global $current_user;
		$exists = array();
		if ($this->id != '') {
			$GLOBALS['db']->query("DELETE FROM documents_user WHERE document_id='" . $this->id . "'");
		}
		foreach ($pl as $p) {
			if (!isset($p['user_id']) || $p['user_id'] == '')
				continue;
			//insert new record
			$id = create_guid();
			$t = array(
				$id, //id
				$this->id, //document id
				addslashes($p['user_id']), //user id
				date("Y.m.d"), //date entered
				$p['date_accepted'], //date accepted
				$p['accepted'], //status accepted
				$p['accepted_description'], //status opis
			);
			$q = "INSERT INTO documents_user VALUES ('" . implode("','", $t) . "')";
			echo $q;
			$GLOBALS['db']->query($q);
			$exists[] = $id;
		}
		//delete old
		// $GLOBALS['db']->query("UPDATE accounts_websites SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}

	function showUserList($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM documents_user WHERE document_id='" . $this->id . "'";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$new = new User();
					$new->retrieve($w['user_id']);
					$w['user_name'] = $new->first_name . ' ' . $new->last_name;
					unset($new);
					$return_array [] = $w;
				}
				return $array ? $return_array : $return_array;
			}
		}
		return $array ? false : '[]';
	}

	//End UserList
	// multi connections end
	function fill_in_additional_detail_fields() {
		global $theme;
		global $current_language;
		global $timedate;
		global $locale;

		parent::fill_in_additional_detail_fields();

		$mod_strings = return_module_language($current_language, 'Documents');

		$query = "SELECT filename,revision,file_ext FROM document_revisions WHERE id='$this->document_revision_id'";

		$result = $this->db->query($query);
		$row = $this->db->fetchByAssoc($result);

		//popuplate filename
		if (isset($row['filename']))
			$this->filename = $row['filename'];
		//$this->latest_revision = $row['revision'];
		if (isset($row['revision']))
			$this->revision = $row['revision'];

		//populate the file url. 
		//image is selected based on the extension name <ext>_icon_inline, extension is stored in document_revisions.
		//if file is not found then default image file will be used.
		global $img_name;
		global $img_name_bare;
		if (!empty($row['file_ext'])) {
			$img_name = SugarThemeRegistry::current()->getImageURL(strtolower($row['file_ext']) . "_image_inline.gif");
			$img_name_bare = strtolower($row['file_ext']) . "_image_inline";
		}

		//set default file name.
		if (!empty($img_name) && file_exists($img_name)) {
			$img_name = $img_name_bare;
		} else {
			$img_name = "def_image_inline"; //todo change the default image.						
		}
		if ($this->ACLAccess('DetailView')) {
			$this->file_url = "<a href='index.php?entryPoint=download&id=" . basename(UploadFile :: get_url($this->filename, $this->document_revision_id)) . "&type=Documents' target='_blank'>" . SugarThemeRegistry::current()->getImage($img_name, 'alt="' . $mod_strings['LBL_LIST_VIEW_DOCUMENT'] . '"  border="0"') . "</a>";
			$this->file_url_noimage = basename(UploadFile :: get_url($this->filename, $this->document_revision_id));
		} else {
			$this->file_url = "";
			$this->file_url_noimage = "";
		}

		//get last_rev_by user name.
		$query = "SELECT first_name,last_name, document_revisions.date_entered as rev_date FROM users, document_revisions WHERE users.id = document_revisions.created_by and document_revisions.id = '$this->document_revision_id'";
		$result = $this->db->query($query, true, "Eror fetching user name: ");
		$row = $this->db->fetchByAssoc($result);
		if (!empty($row)) {
			$this->last_rev_created_name = $locale->getLocaleFormattedName($row['first_name'], $row['last_name']);

			$this->last_rev_create_date = $timedate->to_display_date_time($row['rev_date']);
		}

		global $app_list_strings;
		if (!empty($this->status_id)) {
			//_pp($this->status_id);
			$this->status = $app_list_strings['document_status_dom'][$this->status_id];
		}
		$this->related_doc_name = Document::get_document_name($this->related_doc_id);
		$this->related_doc_rev_number = DocumentRevision::get_document_revision_name($this->related_doc_rev_id);
		$this->save_file = basename($this->file_url_noimage);
	}

	function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
		return $list_form;
	}

	function create_export_query(&$order_by, &$where, $relate_link_join = '') {
		$custom_join = $this->custom_fields->getJOIN(true, true, $where);
		if ($custom_join)
			$custom_join['join'] .= $relate_link_join;
		$query = "SELECT
						documents.*";
		if ($custom_join) {
			$query .= $custom_join['select'];
		}
		$query .= " FROM documents ";
		if ($custom_join) {
			$query .= $custom_join['join'];
		}

		$where_auto = " documents.deleted = 0";

		if ($where != "")
			$query .= " WHERE $where AND " . $where_auto;
		else
			$query .= " WHERE " . $where_auto;

		if ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY documents.document_name";

		return $query;
	}

	function get_list_view_data() {
		global $current_user , $app_list_strings;
		$path = $GLOBALS['sugar_config']['upload_dir'] . basename(UploadFile :: get_url($this->filename, $this->document_revision_id));
		$document_fields = $this->get_list_view_array();
		$document_fields['FILE_URL'] = '<a href="' . $path . '" target="new"><img src="themes/Sugar5/images/def_image_inline.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"/></a>'; //$this->file_url;
		$document_fields['FILE_URL_NOIMAGE'] = $this->file_url_noimage;
		$document_fields['LAST_REV_CREATED_BY'] = $this->last_rev_created_name;
		$document_fields['CATEGORY_ID'] = empty($this->category_id) ? "" : $app_list_strings['document_category_dom'][$this->category_id];
		$r = $this->db->query('SELECT id,accepted,date_accepted,user_id,accepted_description from documents_user where user_id="' . $current_user->id . '" and document_id="' . $this->id . '"');
		if ($r->num_rows > 0) {
			$d = $this->db->fetchByAssoc($r);
			if ($d['accepted'] == 0) {
				$document_fields['TO_ACCEPT'] = '<a onclick="$( \'#userDiv_' . $d['id'] . '\' ).toggle(\'slow\');">Akceptuj</a><div id="userDiv_' . $d['id'] . '" style="display:none;">
		        <table class="olCgClass" style="width:200px;">
		        <tr><td>Opis</td></tr>
		        <tr><td><textarea name="userAcceptDes" id="userAcceptDes_' . $d['id'] . '" rows="4" style="width: 100%"></textarea></td></tr>
		        <tr><td>
				         <select id="statusik_' . $d['id'] . '">
                            <option value="1">Akceptuj</option>
                            <option value="0">Oczekuj</option>
                            <option value="2">Odrzuć</option>
                        </select>
						<input type="button"
											id="userSaveDes_' . $d['id'] . '"
											value="Zapisz"
											onclick="location.href=\'index.php?module=Documents&action=accept&status=\'+$(\'#statusik_' . $d['id'] . ' :selected\').val()+\'&record=' . $d['id'] . '&user_id=' . $d['user_id'] . '&doc_id=' . $this->id . '&des=\'+$(\'#userAcceptDes_' . $d['id'] . '\').val()+\'\'">
						<input type="button" value ="Anuluj" id="userCancel_' . $d['id'] . '" onclick="$( \'#userDiv_' . $d['id'] . '\' ).toggle(\'slow\');">
					</td></tr>
		        </table>
		        </div>';
			} else {
				$document_fields['TO_ACCEPT'] = '<a onclick="$( \'#userDiv_' . $d['id'] . '\' ).toggle(\'slow\');">Pokaż</a><div id="userDiv_' . $d['id'] . '" style="display:none;">
		        <table class="olCgClass" style="width:200px;">
		        <tr><td>Data: ' . date("d.m.Y", strtotime($d['id'])) . '</td></tr>
		        <tr><td>Opis: ' . str_replace('XVZC', '<br>', $d['accepted_description']) . '</td></tr>
				<tr><td><input type="button" value ="Zamknij" id="userCancel_' . $d['id'] . '" onclick="$( \'#userDiv_' . $d['id'] . '\' ).toggle(\'slow\');"></td></tr>
		        </table>
		        </div>';
			}
		}
		if ($document_fields['VALUE'] != '') {
			$document_fields['VALUE'] = number_format($document_fields['VALUE'], 2, ',', '.');
		}
		$r = $this->db->query('SELECT parent_id,parent_type from documents_accounts where document_id="' . $this->id . '" limit 1');
		if ($r->num_rows > 0) {
			$d = $this->db->fetchByAssoc($r);
			$new = new $d['parent_type'];
			$new->retrieve($d['parent_id']);
			if (substr($d['parent_type'], 0, 3) != 'Ecm') {
				$d['parent_name'] = $new->name;
			} else {
				$d['parent_name'] = $new->document_no;
			}

			$document_fields['PARENT_NAME'] = '<a href="index.php?module=' . $d['parent_type'] . 's&action=DetailView&record=' . $d['parent_id'] . '" target="new">' . $d['parent_name'] . '</a>';
		}
		//$document_fields['DOCUMENT_NAME_JAVASCRIPT'] = $GLOBALS['db']->helper->escape_quote($document_fields['DOCUMENT_NAME']);
		return $document_fields;
	}

	function mark_relationships_deleted($id) {
		//do nothing, this call is here to avoid default delete processing since  
		//delete.php handles deletion of document revisions.
	}

	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL' :
				return true;
		}
		return false;
	}

	//static function.
	function get_document_name($doc_id) {
		if (empty($doc_id))
			return null;

		$db = DBManagerFactory::getInstance();
		$query = "select document_name from documents where id='$doc_id'";
		$result = $db->query($query);
		if (!empty($result)) {
			$row = $db->fetchByAssoc($result);
			if (!empty($row)) {
				return $row['document_name'];
			}
		}
		return null;
	}

	//start managing categories
	function savePositions3($pl) {
		global $current_user;
		$exists = array();

		//$GLOBALS['db']->query("INSERT INTO log VALUES ('".addslashes(json_encode($pl))."')");
		foreach ($pl as $p) {
			if (!isset($p['ecmproductcategory_id']) || $p['ecmproductcategory_id'] == '')
				continue;
			if (isset($p['id']) && $p['id'] != '') {
				//update exists
				$q = "
				UPDATE ecmproductcategories_bean set
					date_modified = '" . date("Y-m-d H:i:s") . "',
					modified_user_id = '" . $current_user->id . "',
					bean_id = '" . addslashes($this->id) . "',
					ecmproductcategory_id = '" . addslashes($p['ecmproductcategory_id']) . "'
					WHERE id = '" . $p['id'] . "'
				";

				//$GLOBALS['db']->query("INSERT INTO log VALUES ('".addslashes($q)."')");
				$GLOBALS['db']->query($q);
				$exists[] = $p['id'];
			} else {
				//insert new record
				$id = create_guid();
				$t = array(
					$id,
					addslashes($p['ecmproductcategory_id']),
					$this->id,
					"Documents",
					date("Y-m-d H:i:s"),
					date("Y-m-d H:i:s"),
					$current_user->id,
					$current_user->id,
					'0'
				);
				$q = "INSERT INTO ecmproductcategories_bean VALUES ('" . implode("','", $t) . "')";
				$GLOBALS['db']->query($q);
				$exists[] = $id;
			}
		}
		//delete old
		$GLOBALS['db']->query("UPDATE ecmproductcategories_bean SET deleted='1', modified_user_id='" . $current_user->id . "',date_modified = '" . date("Y-m-d H:i:s") . "' WHERE bean_id='" . $this->id . "' AND id NOT IN ('" . implode("','", $exists) . "')");
	}

	function getPositionList3($array = false) {
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM ecmproductcategories_bean WHERE bean_id='" . $this->id . "' AND deleted='0' AND bean_name='Documents'";

			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {

				while ($w = $this->db->fetchByAssoc($r)) {
					//get category name && assigned_file
					$n = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT name, assigned_file FROM ecmproductcategories WHERE id='" . $w['ecmproductcategory_id'] . "'"));
					$w['ecmproductcategory_name'] = $n['name'];
					$w['assigned_file'] = $n['assigned_file'];
					$return_array [] = $w;
				}
				$json = getJSONobj();

				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	function showPositions3() {
		$arr = $this->getPositionList3(true);

		global $mod_strings;
		if (count($arr) > 0) {
			$table = '
			<table cellpadding="0" cellspacing="0" border="0" class="list view" width="40%">
			<tr class="oddListRowS1">
				<th><b>' . $mod_strings['LBL_CATEGORY_NAME'] . '</b></td>
				<th><b>' . $mod_strings['LBL_CATEGORY_ASSIGNED_FILE'] . '</b></td>
			</tr>
			';
			$i == 0;
			foreach ($arr as $a) {
				$i++;
				//assigned file
				if ($a['assigned_file'] != "" && $a['assigned_file']) {
					$tmp = explode(".", $a['assigned_file']);
					if (end($tmp) == 'jpeg' || end($tmp) == 'jpg' || end($tmp) == 'png' || end($tmp) == 'bmp')
						$af = '<img src="modules/EcmProductCategories/files/' . $a['assigned_file'] . '"/>';
					else
						$af = '<a href="modules/EcmProductCategories/files/' . $a['assigned_file'] . '" target="new">' . $a['assigned_file'] . '</a>';
				}
				$table.='
				<tr class="oddListRowS1">
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;"><a href="index.php?module=EcmProductCategories&action=DetailView&record=' . $a['ecmproductcategory_id'] . '">' . $a['ecmproductcategory_name'] . '</a></td>
	
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">' . $af . '</td>
	
				';
			}
			$table.='</table>';
		}

		return $table;
	}

	//end managing categories
}

?>