<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Extended HRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/




$page_security = 'CRM_ATTACHMENTS';
$path_to_root="../../..";
if(!isset($page_nested))
	include_once($path_to_root . "/modules/KvcodesCRM/includes/ui/crm_db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();
include_once($path_to_root . "/admin/db/attachments_db.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );


if (isset($_GET['vw']))
	$view_id = $_GET['vw'];
else
	$view_id = find_submit('view');
if ($view_id != -1){	//echo $view_id;
	$row = GetRow('kv_crm_attachments', array('id' => $view_id));
	if ($row['unique_name'] != ""){
		if(in_ajax()) {
			$Ajax->popup($_SERVER['PHP_SELF'].'?vw='.$view_id);
		} else {
			$type = ($row['filetype']) ? $row['filetype'] : 'application/octet-stream';	
    		header("Content-type: ".$type);
    		//header('Content-Length: '.$row['filesize']);
 			header("Content-Disposition: inline");
 			//display_error( company_path(). "/attachments/crmdocs/".$row['unique_name']);
	    	echo file_get_contents(company_path(). "/attachments/crmdocs/".$row['unique_name']);
    		exit();
		}
	}	
}
if (isset($_GET['dl']))
	$download_id = $_GET['dl'];
else
	$download_id = find_submit('download');

if ($download_id != -1){
	$row = GetRow('kv_crm_attachments', array('id' => $download_id));
	if ($row['unique_name'] != ""){
		if(in_ajax()) {
			$Ajax->redirect($_SERVER['PHP_SELF'].'?dl='.$download_id);
		} else {
			
    		header("Content-type: 'application/octet-stream' ");
	    	//header('Content-Length: '.$row['filesize']);
    		header('Content-Disposition: attachment; filename='.$row['filename']);
    		echo file_get_contents(company_path()."/attachments/crmdocs/".$row['unique_name']);
	    	exit();
		}
	}	
}

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}
page(_($help_context = "CRM Attachments"), false, false, "", $js);

simple_page_mode(true);

//----------------------------------------------------------------------------------------
if(isset($_SESSION['wa_current_user']->type))
	$_POST['type_id'] = $_SESSION['wa_current_user']->person;
	//echo '<style> #delete { display : none; } </style>';	
elseif (isset($_GET['type_id']))
	 $type_id = $_POST['type_id'] = $_GET['type_id'];
if (isset($_GET['type']))
	 $type = $_POST['type'] = $_GET['type'];
elseif(!isset($_POST['type']))
	$type = $_POST['type'] = -1; //default Leads.
		
if(isset($_SESSION['wa_current_user']->type))
	$type = $_POST['type'] = $_SESSION['wa_current_user']->type;

if ($Mode == 'ADD_ITEM' || $Mode == 'UPDATE_ITEM'){
	if(!isset($max_image_size))
		$max_image_size = 5000;
	$upload_file = "";
	if (isset($_FILES['kv_attach_name']) && $_FILES['kv_attach_name']['name'] != '') {
		
		$result = $_FILES['kv_attach_name']['error'];
		$upload_file = 'Yes'; 
		$attr_dir = company_path().'/attachments' ; 
		if (!file_exists($attr_dir)){			
			mkdir($attr_dir);
		}
		$attach_dir = $attr_dir.'/crmdocs';
		if (!file_exists($attach_dir)){
			mkdir($attach_dir);
		}	
		$doc_ext = substr(trim($_FILES['kv_attach_name']['name']), strlen($_FILES['kv_attach_name']['name']) - 3) ; 
		if($doc_ext == 'ocx' ) {
			$doc_ext = substr(trim($_FILES['kv_attach_name']['name']), strlen($_FILES['kv_attach_name']['name']) - 4) ; 
		}
		if(isset($_POST['unique_name']) && $_POST['unique_name'] == '')
			$kv_file_name = uniqid();			
		else
			$kv_file_name = $_POST['unique_name']; 
			
		$filename = $attach_dir."/".$kv_file_name; 
		if ( $_FILES['kv_attach_name']['size'] > ($max_image_size * 1024)) { //File Size Check
			display_warning(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $max_image_size);
			$upload_file ='No';
		} elseif (file_exists($filename)){
			$result = unlink($filename);
			if (!$result) 	{
				display_error(_('The existing Docs could not be removed'));
				$upload_file ='No';
			}
		}			
		if ($upload_file == 'Yes'){
			$actual_file_nam = $_FILES['kv_attach_name']['name'];
			$result  =  move_uploaded_file($_FILES['kv_attach_name']['tmp_name'], $filename);
			Update('kv_crm_attachments', array('id' => $_POST['selected_id']), array('type_id' => $_POST['type_id'], 'type' => $_POST['type'], 'title' => $_POST['title'], 'filename' => $actual_file_nam, 'unique_name' => $kv_file_name, 'date' => array($_POST['date'], 'date') )); 
			display_notification(_("The Selected Document has been attached!."));
		}
		refresh_pager('kv_crm_attachments');
		$Ajax->activate('_page_body');
		$Ajax->activate('Attachments');
		display_notification(_("The Selected Attachment Updated Successfully"));
	} else {
		Update('kv_crm_attachments', array( 'id' => $_POST['selected_id']), array('title' => $_POST['title'], 'date' => array($_POST['date'], 'date') ));
		$Ajax->activate('Attachments');
		display_notification(_("The Selected Attachment's Description and date Updated Successfully"));
	}
}

if ($Mode == 'Delete'){
	$row = GetRow('kv_crm_attachments', array('id' => $selected_id));
	$dir =  company_path()."/attachments/crmdocs";
	if (file_exists($dir."/".$row['unique_name']) && !is_dir($dir."/".$row['unique_name']))
		unlink($dir."/".$row['unique_name']);
	Delete('kv_crm_attachments', array('id' => $selected_id));	
	display_notification(_("The Selected Document has been deleted.")); 
	$Mode = 'RESET';
}

if ($Mode == 'RESET'){	
	$selected_id = -1;
}

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

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

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

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

function attachment_display_rows($type){

	$sql = 'SELECT id, title, filename, date, inactive FROM '.TB_PREF.'kv_crm_attachments WHERE 1'; 
	if($type > 0 )
		$sql .=" AND type=".$type;
	if(list_updated('type_id') || get_post('type_id'))
		$sql .= ' AND type_id = '.get_post('type_id');
	if(isset($_SESSION['wa_current_user']->type) && ($_SESSION['wa_current_user']->type == ST_SUPPLIER || $_SESSION['wa_current_user']->type == ST_CUSTOMER))
		$sql .= ' AND inactive = 1';
	
	$cols = array(
		_("ID") => array('name'=>'id', 'ord'=>'desc'),
		_("Docs Title") => array('name'=>'title'),
		_("Filename") => array('name'=>'filename'),	    	    
		_("Date") => array('name'=>'date', 'type'=>'date', 'ord'=>'desc'),	    	    
		_("Status") => array('name'=>'inactive', 'type'=>'inactive'),	    	    
	    	array('insert'=>true, 'fun'=>'at_edit_link'),
	    	//array('insert'=>true, 'fun'=>'at_view_link'),
	    	array('insert'=>true, 'fun'=>'at_download_link'),
	    	array('insert'=>true, 'fun'=>'at_delete_link')
	    );	
	//display_error(json_encode($_POST).$sql);

	if($type != ST_SUPPLIER && $type != ST_CUSTOMER)
		unset($cols[_("Status")]);
		$table =& crm_new_db_pager('kv_crm_attachments', $sql, $cols, 'kv_crm_attachments');
		$table->width = "80%";
		crm_display_db_pager($table);
}

//----------------------------------------------------------------------------------------
$action = $_SERVER['PHP_SELF'];
if(list_updated('type')){
	$type = get_post('type');
	$_POST['type_id'] =0;
	$_POST['selected_id'] = $selected_id = -1;
	$Ajax->activate('AttachmentTypes');	
	$Ajax->activate('type_id');
	$Ajax->activate('Attachments');	
}
	
if ($page_nested)
	$action .= "?type_id=".get_post('type_id');
start_form(true, false, $action);
	div_start('AttachmentTypes');	
	
	start_table(TABLESTYLE_NOBORDER);
	start_row();
		
	if(!$page_nested && !isset($_SESSION['wa_current_user']->type) ){
		crm_attachment_types_list_cells(_("Select a Type"). " :", 'type', null,  _("Select Type"), true);

		// display_error(json_encode($_POST['type']));
	} 
	if (isset($_POST['type']) && $_POST['type'] == ST_LEADS && db_has_leads()) {
		if (!$page_nested){			
			lead_list_cells(_("Select a Lead"). " :", 'type_id', null,  _("Select Lead"), true, false, false, array());
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('lead_id'));
	} elseif(isset($_POST['type']) && $_POST['type'] == ST_OPPORTUNITIES && db_has_opportunities()) {		
		if (!$page_nested){			
			opportunity_list_cells(_("Select an Opportunity"). " :", 'type_id', null,  _("Select Opportunity"), true, false);
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('opportunity_id'));
	} elseif(isset($_POST['type']) && $_POST['type'] == ST_PROJECT && db_has_projects()) {		
		if (!$page_nested){			
			projects_list_cells(_("Select a Project"). " :", 'type_id', null,  _("Select Project"), true, 0);
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('project_id'));
	} elseif(isset($_POST['type']) && $_POST['type'] == ST_TASKS && db_has_tasks()) {		
		if (!$page_nested){			
			tasks_list_cells(_("Select a Task"). " :", 'type_id', null,  _("Select Task"), true, 0);
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('task_id'));
	} elseif(isset($_POST['type']) && $_POST['type'] == ST_CUSTOMER && db_has_customers()  && (!isset($_SESSION['wa_current_user']->type) || $_SESSION['wa_current_user']->type != ST_CUSTOMER)) {	
		if (!$page_nested){			
			customer_list_cells(_("Select a customer") ." :", 'type_id', null,	_('Select customer'), true, 0);
			//check_cells(_("Show Visible files of Customer:"), 'show_inactive', null, true);
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('customer_id'));
	} elseif(isset($_POST['type']) && $_POST['type'] == ST_SUPPLIER && db_has_suppliers() && (!isset($_SESSION['wa_current_user']->type)|| $_SESSION['wa_current_user']->type !=ST_SUPPLIER)) {		
		if (!$page_nested){			
			supplier_list_cells(_("Select a Supplier") ." :", 'type_id', null,	_('Select Supplier'), true, 0);
			$new_item = get_post('type_id')=='';
		} else 
			hidden('type_id', get_post('supplier_id'));
	}else{				
		hidden('type_id', get_post('type_id'));		
	}	
	if (list_updated('type_id')) {
		$type = get_post('type');
		$Ajax->activate('type_id');
		$Ajax->activate('Attachments');	
		set_focus('type_id');
	}
	end_row();
	end_table();
	div_end();	

	div_start('Attachments');
	br(2);
	$type = get_post('type');
	
	attachment_display_rows($type);	
	
	if ($selected_id != -1 || (get_post('type_id') && get_post('type')) ){
		br(2);	
		start_table(TABLESTYLE2);
		
		if($type== ST_LEADS)
			$id_word = _("Lead ID");
		elseif($type==ST_OPPORTUNITIES)
			$id_word = _("Opportunity ID");
		elseif($type==ST_PROJECT)
			$id_word = _("Project ID");
		elseif($type==ST_TASKS)
			$id_word = _("Task ID");
		elseif($type==ST_CUSTOMER)
			$id_word = _("Customer ID");
		elseif($type==ST_SUPPLIER)
			$id_word = _("Supplier ID");
		else
			$id_word=('');
		if($Mode == 'Edit')	{
			$row = GetRow('kv_crm_attachments', array('id' => $selected_id, 'type' => $type));
			$_POST['title']  = $row["title"];			
			hidden('unique_name', $row['unique_name']);			
			label_row(_($id_word), $row['type_id']);
			$_POST['date'] = sql2date($row['date']);
		} else {					
			hidden('unique_name', '');
			$_POST['title'] = '';
			if(isset($id_word)) 
				label_row($id_word, get_post('type_id'));			
		}
		hidden('selected_id', $selected_id);
		date_row(_("Date"), 'date');
		text_row_ex(_("Docs Title").':', 'title', 40);
		file_row(_("Select Docs") . ":", 'kv_attach_name', 'kv_attach_name');

		end_table(1);

		submit_add_or_update_center($selected_id == -1, '', 'process');
	}	
	div_end();
end_form();
end_page();
?>