<?php
/****************************************
/*  Author  : Kvvaradha
/*  Module  : Kvcodes CRM
/*  E-mail  : admin@kvcodes.com
/*  Version : 1.0
/*  Http    : www.kvcodes.com
*****************************************/
include_once($path_to_root. '/includes/ui/simple_crud_class.inc');


class attachments extends crm_simple_crud {
	var $selected_id;
	var $entity;
	var $sub_class;
	var $class;
	
	function __construct($name, $id, $class, $subclass=null) {
		$fields = array('at_type', 'type_id','title','filename','date');
		parent::__construct($name, $fields);
		$this->class = $class;
		$this->subclass = $subclass;
		$this->entity = $id;
		
	}

	function list_view() {
		global $Ajax, $path_to_root;
		br();
		if(isset($_POST['attachmentDownload'])){
			$keys =  array_keys($_POST['attachmentDownload']);
			$row = GetRow('kv_crm_attachments', array('id' => $keys[0]));
			
			if ($row['unique_name'] != ""){
				if(in_ajax()) {
					$Ajax->redirect($path_to_root.'/modules/KvcodesCRM/manage/attachments.php?dl='.$keys[0]);
				} 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();
				}
			}
		}
		if(isset($_POST['attachmentView'])){
			$keys =  array_keys($_POST['attachmentView']);
			$row = GetRow('kv_crm_attachments', array('id' => $keys[0]));
			
			if ($row['unique_name'] != ""){
				if(in_ajax()) {
					$Ajax->redirect($path_to_root.'/modules/KvcodesCRM/manage/attachments.php?vw='.$keys[0]);
				} 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();
				}
			}
		}
		$filters = array('type_id' => $this->entity, 'type' => (isset($_GET['task_type']) ? $_GET['task_type'] : $_GET['type']));

		if(isset($_SESSION['wa_current_user']->type) && ($_SESSION['wa_current_user']->type == ST_SUPPLIER || $_SESSION['wa_current_user']->type == ST_CUSTOMER))
			$filters['inactive'] = 1;

		$attachments = GetAll('kv_crm_attachments', $filters); 
		start_table(TABLESTYLE, "width=80%");
		$th = array(_("ID"), _("Docs Title"), _("Filename"), _("Date"),  "", /* "", */"", "");	
		table_header($th);	
		if($attachments){	
			foreach($attachments as $de) {				
				label_cell($de['id']);					
				label_cell($de['title']);
				label_cell($de['filename']);
				label_cell(sql2date($de['date']));					
				edit_button_cell("{$this->name}Edit[{$de['id']}]", _("Edit"));
				button_cell("{$this->name}Download[{$de['id']}]", _("Download"), false, ICON_DOWN);
				//button_cell("{$this->name}View[{$de['id']}]", _("View"), false, ICON_VIEW);
				delete_button_cell("{$this->name}Delete[{$de['id']}]", _("Delete"));
				end_row();	
			}
		}
		end_table(1);
	}
	
	function editor_view(){
		//global $Ajax;

		$this->list_view();
		br();
		div_start('Attachment_Details');	
		start_outer_table(TABLESTYLE);
	
		table_section(1);
		table_section_title(_("Attachment Detail"));
		
		if($this->selected_id != null || $this->selected_id != "") {
			$row = GetRow('kv_crm_attachments', array( 'id' => $this->selected_id));
			hidden('unique_name', $row['unique_name']);	
			$_POST['date'] = sql2date($row['date']);
			$_POST['title'] = $row['title'];					
			$_POST['type_id'] = $row['type_id'];					
		}else
			$_POST['type_id'] = $this->entity;

		if(isset($_GET['task_type']))
			$type = $_GET['task_type'];
		else
			$type= $_GET['type'];

		//display_error($type. $_GET['Mode']);
		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");
		label_row(_($id_word), $_POST['type_id']);	
		date_row(_("Date"), 'date');
		text_row_ex(_("Docs Title").':', 'title', 40);
		file_row(_("Select Docs") . ":", 'kv_attach_name', 'kv_attach_name');
		hidden('unique_name', '');
		if(isset($_SESSION['wa_current_user']->type) && ($_SESSION['wa_current_user']->type == ST_SUPPLIER || $_SESSION['wa_current_user']->type == ST_CUSTOMER))
			hidden('inactive',  1);
		else
			hidden('inactive',  0);
		hidden('at_type', (isset($_GET['task_type']) ? $_GET['task_type'] : $_GET['type']));		
		end_outer_table(1);	
		div_end();
	}

	function _bottom_controls()	{
		$title=false;
		$async='both';
		$base=$this->name;

		$cancel = $async;

		if ($async === 'both') {
			$async = 'default'; $cancel = 'cancel';
		} 
		else if ($async === 'default')
			$cancel = true;
		else if ($async === 'cancel')
			$async = true;
		echo "<center>";

		if ($this->Mode == '' || $this->Mode == 'RESET')
			submit("{$base}NEW", _("Add new"), true, $title, $async);
		else {
			if ($this->Mode == 'NEW' || $this->selected_id==$this->_none)
				
				submit("{$base}ADD", _("Add"), true, $title, $async);
			else {
				submit("{$base}UPDATE[{$this->selected_id}]", _("Update"), true, _("Submit changes"), $async);				
			}
			submit("{$base}RESET", _("Cancel"), true, _("Cancel edition"), $cancel);
		}
		echo "</center>";
	}
	
	function db_insert() {
		$dat = $this->data;		
		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);
				$id =  Insert('kv_crm_attachments', array('type_id' => $this->entity, 'type' => $dat['at_type'],'title' => $_POST['title'], 'filename' => $actual_file_nam, 'unique_name' => $kv_file_name, 'date' => array($_POST['date'], 'date'), 'inactive' => $_POST['inactive'],'filesize'=>$_FILES['kv_attach_name']['size']));
			}
			display_notification(_("A New Attachment Added Successfully"));
			return $id;
		} else 
			display_warning(_("There is no attachment selected to Save this entry."));
	}

	function db_update() {
		$dat = $this->data;		
		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' => $this->selected_id), array('type_id' => $this->entity, 'type' => $dat['at_type'],'title' => $_POST['title'], 'filename' => $actual_file_nam, 'unique_name' => $kv_file_name, 'date' => array($_POST['date'], 'date') ));
			}
			display_notification(_("The Selected Attachment Updated Successfully"));
		} else {
			 Update('kv_crm_attachments', array( 'id' => $this->selected_id), array('title' => $_POST['title'], 'date' => array($_POST['date'], 'date') ));
			display_notification(_("The Selected Attachment's Description and date Updated Successfully"));
			return true;
		}
	}

	function insert_check() {
		
		if (strlen($_POST['title']) == 0) {
			display_error(_("Description cannot be empty."));
			set_focus('title');
			return false;
		}
		
		return true; 
	}

	function db_read() {
		return GetAll('kv_crm_attachments', array('type_id' => $this->entity));
	}
	function db_edit_read() {
		return GetAll('kv_crm_attachments', array('type_id' => $this->selected_id));
	}
	
	function delete_check() {
		return true;
	}
	//	Delete all degree for degree in current class/entity
	function db_delete() {
		$row = GetRow('kv_crm_attachments', array('id' => $this->selected_id));
		$dir =  company_path()."/attachments/crmdocs";
		if ($row['unique_name'] && file_exists($dir."/".$row['unique_name']))
			unlink($dir."/".$row['unique_name']);

		if (Delete('kv_crm_attachments', array('id' => $this->selected_id))) {	
			display_notification(_("The Selected Attachment Deleted Successfully"));
		}
		return false;
	}
}

?>