<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/
$page_security = 'CRM_PROJECTS';
$path_to_root="../../..";
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/db/custom_fields_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/ui/custom_fields_ui.inc");
add_access_extensions();
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/modules/KvcodesCRM/includes/activity.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/attachment.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/comments.inc");
$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();
}
?>
<style>
.nicEdit-selectTxt {line-height: 16px !important;}
</style>

<?php 
add_js_file('../modules/KvcodesCRM/js/nicEdit-latest.js');
 
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");
page(_("Projects"), @$_REQUEST['popup'], false, "", $js); 

$new_item = get_post('project_id')=='' || get_post('cancel') || get_post('clone'); 
//------------------------------------------------------------------------------------

if (isset($_GET['project_id'])){
	$_POST['project_id'] = $_GET['project_id'];
}
$project_id = get_post('project_id');
if (list_updated('project_id')) {
	$_POST['NewProjectID'] = $project_id = get_post('project_id');
    clear_data();
	$Ajax->activate('details');
	$Ajax->activate('controls');
}

if (get_post('cancel')) {
	$_POST['NewProjectID'] = $project_id = $_POST['project_id'] = '';
    clear_data();
	set_focus('project_id');
	$Ajax->activate('_page_body');
}
/*if (list_updated('category_id') || list_updated('mb_flag') || list_updated('fa_class_id') || list_updated('depreciation_method')) {
	$Ajax->activate('details');
}*/
//display_error($_POST['contacted_today']);
if(isset($_GET['Added'])){
	display_notification(_("A New Project Inserted Successfully!"));
}elseif(isset($_GET['Updated'])){
	display_notification(_("The Selected Project Details Updated Successfully!"));
}elseif(isset($_GET['Deleted'])){
	display_notification(_("The Selected Project Deleted Successfully"));
}
if(get_post('contacted_today')) {
	$_POST['contacted_today'] = 1;	
}
function clear_data(){
	unset($_POST['project_exist_id'] , $_POST['name'] ,$_POST['description'], $_POST['clientid'], $_POST['billing_type'] , $_POST['project_cost'], $_POST['status'], $_POST['progress'], $_POST['deadline'],$_POST['start_date']);
}

if (isset($_POST['addupdate'])) {

	$input_error = 0;
	if (strlen($_POST['name']) == 0) {
		display_error(_("The Project Name cannot be empty."));
		set_focus('name');
		$input_error = 1;
	}	
	if (strlen($_POST['code']) == 0) {
		display_error(_("The Project Code cannot be empty."));
		set_focus('code');
		$input_error = 1;
	}elseif($new_item && GetSingleValue('kv_crm_projects', 'COUNT(*)', array('code' => $_POST['code'])))	{
		display_error(_("The Project Code Already Exists. Try Different one."));
		set_focus('code');
		$input_error = 1;
	}
	if (strlen($_POST['description']) == 0) {
		display_error(_("The Description Can't be empty."));
		set_focus('description');
		$input_error = 1;
	}
	if ($_POST['clientid'] == null || $_POST['clientid'] == 0) {
		display_error(_("The Customer Name cannot be empty."));
		set_focus('clientid');
		$input_error = 1;
	}

	if($_POST['billing_type'] == 1 && $_POST['project_cost'] <1){
		display_error(_("The Project Cost Can't be zero for fixed price Projects."));
		set_focus('project_cost');
		$input_error = 1;
	}

	if ($input_error != 1){
		
		$details =array('name' => $_POST['name'],  'code' => $_POST['code'], 'description' => $_POST['description'], 'clientid' => $_POST['clientid'], 'branch_id' => $_POST['branch_id'], 'billing_type' => $_POST['billing_type'], 'project_cost' => $_POST['project_cost'], 'status' => $_POST['status'], 'progress' => $_POST['progress'], 'deadline' => array($_POST['deadline'], 'date'), 'start_date' => array($_POST['start_date'], 'date'), 'sales_account' =>  $_POST['sales_account'],'inventory_account' => $_POST['inventory_account'],	'cogs_account' => $_POST['cogs_account'],	'adjustment_account' => $_POST['adjustment_account'],	'wip_account' => $_POST['wip_account'],		'dimension_id' => $_POST['dimension_id'],	'mb_flag' => $_POST["mb_flag"],	'units' => $_POST["units"], 'project_rate_per_hour' => $_POST['project_rate_per_hour'], 'estimated_hours' =>$_POST['estimated_hours'], 'tax_type_id' => $_POST['tax_type_id']); 
		if($new_item) {	
			$details['addedfrom'] = $_SESSION["wa_current_user"]->user;		
			$details['project_created'] = array(Today(), 'date');		
			$project_id = Insert('kv_crm_projects', $details);
			custom_field_update('project',$project_id);
			// Project Creation mail to Customer
			if(!isset($_POST['branch_id']))
				$_POST['branch_id'] = GetSingleValue('cust_branch', 'branch_code', array('debtor_no'  => $_POST['clientid']));
			$contacts = kv_crm_get_branch_contacts($_POST['branch_id'], null, $_POST['clientid']);
			//display_error(json_encode($contacts));
			$to =  array('name' => $contacts['name'], 'email' => $contacts['email']);

			$details = array('name' => $contacts['name'], 'name2' => '',  'phone' => $contacts['phone'], 'email' => $contacts['email'], 'project_name' => $_POST['name'], 'project_start_date' => $_POST['start_date'], 'project_status' => $_POST['status']);

			$template = array('slug' => 'assigned-to-project',  'details' => $details );
			kv_mail($to, '', '', "html", array(), null, false, $template);

			if(isset($_POST['staff_id'])){
				foreach($_POST['staff_id'] as $staff_id){
					Insert('kv_crm_projectmembers', array('project_id' => $project_id, 'staff_id' => $staff_id));
				}
				foreach($_POST['staff_id'] as $staff_id){
					$staff = GetRow('users', array('id' => $staff_id));
					$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);

					$details = array('name' => $staff['real_name'], 'name2' => '',  'phone' => $staff['phone'], 'email' => $staff['email'], 'project_name' => $_POST['name'], 'project_start_date' => $_POST['start_date'], 'project_status' => $_POST['status']);

					$template = array('slug' => 'staff-added-as-project-member',  'details' => $details );
					kv_mail($to, '', '', "html", array(), null, false, $template);
				}
			}
			meta_forward($_SERVER['PHP_SELF'], "Added=yes&project_id=$project_id");
		}else {
			$project_id =  $_POST['project_id'];
			Update('kv_crm_projects', array('id' => $_POST['project_id']), $details);
			custom_field_update('project',$project_id);
			Delete('kv_crm_projectmembers', array('project_id' => $_POST['project_id']));
			if(isset($_POST['staff_id'])){
				foreach($_POST['staff_id'] as $staff_id){
					Insert('kv_crm_projectmembers', array('project_id' => $project_id, 'staff_id' => $staff_id));
				}
			}
			if($_POST['status'] == 5 ){
				$contacts = kv_crm_get_branch_contacts($_POST['branch_id'], null, $_POST['clientid']);
				
				$to =  array('name' => $contacts['name'], 'email' => $contacts['email']);

				$details = array('name' => $contacts['name'], 'name2' => '',  'phone' => $contacts['phone'], 'email' => $contacts['email'], 'project_name' => $_POST['name'], 'project_start_date' => $_POST['start_date'], 'project_status' => $_POST['status']);

				$template = array('slug' => 'project-finished-to-customer',  'details' => $details );
				kv_mail($to, '', '', "html", array(), null, false, $template);				
			}	
			meta_forward($_SERVER['PHP_SELF'], "Updated=yes&project_id=$project_id");
		}	
			
	}
}elseif(isset($_POST['delete'])){
	$dlt = true;
		if(GetSingleValue('kv_crm_tasks', 'COUNT(*)', array('type' => 2, 'type_id' => $_POST['project_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Project. Some Tasks referring to it"));
		}
		if($dlt && GetSingleValue('kv_crm_attachments', 'COUNT(*)', array('type' => 3, 'type_id' => $_POST['project_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Project. Some attachments referring to it"));
		}
		if( $dlt && GetSingleValue('kv_crm_activities', 'COUNT(*)', array('type' => 3, 'type_id' => $_POST['project_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Project. Some activities referring to it"));
		}
	if($dlt){
		Delete('kv_crm_comments', array('type' => 2, 'type_id' => $_POST['project_id']));
		Delete('kv_crm_projects', array('id' => $_POST['project_id']));
		meta_forward($_SERVER['PHP_SELF'], "Deleted=yes");
	}
}elseif (isset($_POST['clone'])) {
	unset($_POST['project_id']);		
	set_focus('project_exist_id');
	$Ajax->activate('_page_body');
}

function project_settings(&$project_id, $new_item, $person, $allow_customer_to_create_project=false) {

	global $path_to_root, $page_nested;
	$_SESSION['wa_current_user']->person =$person;
	if (!$new_item) {
		$myrow = GetRow('kv_crm_projects', array('id' => $_POST['project_id']));
		$members = GetAll('kv_crm_projectmembers', array('project_id' => $_POST['project_id']));
			
			$_POST['project_exist_id'] = $myrow["id"];
			$_POST['name'] = $myrow["name"];
			$_POST['code'] = $myrow["code"];
			$_POST['description'] = $myrow["description"];
			if(!list_updated('clientid') && !list_updated('category_id') && !list_updated('billing_type'))
				$_POST['clientid'] = $myrow["clientid"];
			$_POST['branch_id'] = $myrow['branch_id'];
			$_POST['billing_type'] = (isset($_POST['billing_type']) ? $_POST['billing_type'] : $myrow["billing_type"]);
			$_POST['project_cost'] = $myrow["project_cost"];
			$_POST['project_rate_per_hour'] = $myrow["project_rate_per_hour"];
			$_POST['status'] = $myrow["status"];
			$_POST['estimated_hours'] = $myrow["estimated_hours"];
			$_POST['tax_type_id'] = $myrow["tax_type_id"];
			$_POST['progress'] = $myrow["progress"];
			
			$_POST['start_date']  = sql2date($myrow["start_date"]);
			$_POST['deadline']  = sql2date($myrow["deadline"]);

			$_POST['sales_account'] =  $myrow['sales_account'];
			$_POST['inventory_account'] = $myrow['inventory_account'];
			$_POST['cogs_account'] = $myrow['cogs_account'];
			$_POST['adjustment_account']	= $myrow['adjustment_account'];
			$_POST['wip_account']	= $myrow['wip_account'];
			$_POST['dimension_id']	= $myrow['dimension_id'];
			$_POST['dimension2_id']	= $myrow['dimension2_id'];
			$_POST['mb_flag']  = $myrow["mb_flag"];
			$_POST['units']  = $myrow["units"];
			$_POST['staff_id'] = array();
			foreach($members as $staff)
				$_POST['staff_id'][] = $staff['staff_id'];
	}elseif(!list_updated('clientid') && !list_updated('category_id') && !list_updated('billing_type')){
		$_POST['project_cost'] = $_POST['estimated_hours'] = 0;
		$_POST['status'] = 14;
		if(!isset($_POST['code']))
			$_POST['code'] ='';
	}

	br();
	start_table();
	text_row(_("Project Code:*"), 'code', null, 20, 20);
	text_row(_("Project Name:*"), 'name', null, 80, 100);
	kv_crm_textarea_row(_("Description:*"), 'description', null, 70, 10);
	end_table();
	br(2);
	start_outer_table(TABLESTYLE2);

	table_section(1);
	$fixed_asset = get_post('fixed_asset');
	table_section_title(_("Project Details"));	
	if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER){
		hidden('clientid', $_SESSION['wa_current_user']->person);
		$_POST['clientid'] = $_SESSION['wa_current_user']->person;
	} else 
		customer_list_row(_("Customer"), 'clientid', null, _("Select a Customer"), true);
	customer_branches_list_row(_("Branch:"), $_POST['clientid'], 'branch_id', null);	

	//$contacts = kv_crm_get_branch_contacts($_POST['branch_id'], null, $_POST['clientid']);
	//display_error(json_encode($contacts));

	if(!isset($_SESSION['wa_current_user']->person))
		stock_categories_list_row(_("Category:"), 'category_id', null, false, $new_item, $fixed_asset);	
	else{
		$_POST['category_id'] = 0;
		hidden('category_id', $_POST['category_id']);
	}
	if ($new_item && (list_updated('category_id') || !isset($_POST['units']))) {

		$category_record = get_item_category($_POST['category_id']);
		$_POST['units']  = $category_record["dflt_units"];
		$_POST['mb_flag'] = $category_record["dflt_mb_flag"];
		$_POST['inventory_account'] = $category_record["dflt_inventory_act"];
		$_POST['cogs_account'] = $category_record["dflt_cogs_act"];
		$_POST['sales_account'] = $category_record["dflt_sales_act"];
		$_POST['adjustment_account'] = $category_record["dflt_adjustment_act"];
		$_POST['wip_account'] = $category_record["dflt_wip_act"];
		$_POST['dimension_id'] = $category_record["dflt_dim1"];
	}

	billing_type_list_row(_('Billing Type'), 'billing_type', null, false, true);
	item_tax_types_list_row(_("Project Tax Type:"), 'tax_type_id', null, !$new_item );
	if(get_post('billing_type') == 1){
		text_row(_("Fixed Budget"), 'project_cost', null, 10, 10);
		hidden('estimated_hours', $_POST['estimated_hours']);
		hidden('project_rate_per_hour', 0);
	}elseif(get_post('billing_type') == 2){
		text_row(_("Estimated Hours"), 'estimated_hours', null, 10, 10);
		text_row(_("Rate Per Hour"), 'project_rate_per_hour', null, 10, 10);
		hidden('project_cost', $_POST['project_cost']);
	}else{
		hidden('project_cost', 0);
		hidden('estimated_hours', 0);
		hidden('project_rate_per_hour', 0);
	}
	$fresh_item = true;
	if (!get_post('fixed_asset') && !isset($_SESSION['wa_current_user']->person) || $_SESSION['wa_current_user']->person == 0)
		stock_item_types_list_row(_("Project Type:"), 'mb_flag', null, $fresh_item);

	stock_units_list_row(_('Units of Measure:'), 'units', null, $fresh_item);

	date_row(_("Start date"), 'start_date', null);
	date_row(_("Deadline"), 'deadline', null, null, 10,2);	
	kv_crm_number_list_row(_("Progress"), 'progress', null, 0, 100);

	//for custom fields
	custom_field_section('project',(isset($_POST['project_id'])? $_POST['project_id'] : ''),1);
	//end custom fields
 	table_section(2);
 	//display_error(json_encode($_SESSION['wa_current_user']));
 	if(!isset($_SESSION['wa_current_user']->person) || $_SESSION['wa_current_user']->person == 0) {
	 	table_section_title(_("GL Accounts"));

		gl_all_accounts_list_row(_("Sales Account:"), 'sales_account', $_POST['sales_account']);

		if (get_post('fixed_asset')) {
			gl_all_accounts_list_row(_("Asset account:"), 'inventory_account', $_POST['inventory_account']);
			gl_all_accounts_list_row(_("Depreciation cost account:"), 'cogs_account', $_POST['cogs_account']);
			gl_all_accounts_list_row(_("Depreciation/Disposal account:"), 'adjustment_account', $_POST['adjustment_account']);
		}elseif (!is_service($_POST['mb_flag'])) {
			gl_all_accounts_list_row(_("Inventory Account:"), 'inventory_account', $_POST['inventory_account']);
			gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
			gl_all_accounts_list_row(_("Inventory Adjustments Account:"), 'adjustment_account', $_POST['adjustment_account']);
		}else {
			gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
			hidden('inventory_account', $_POST['inventory_account']);
			hidden('adjustment_account', $_POST['adjustment_account']);
		}

		if (is_manufactured($_POST['mb_flag']))
			gl_all_accounts_list_row(_("WIP Account:"), 'wip_account', $_POST['wip_account']);
		else
			hidden('wip_account', $_POST['wip_account']);

		$dim = get_company_pref('use_dimension');
		if ($dim >= 1){
			table_section_title(_("Dimensions"));

			dimensions_list_row(_("Dimension")." 1", 'dimension_id', null, true, " ", false, 1);
			if ($dim > 1)
				dimensions_list_row(_("Dimension")." 2", 'dimension2_id', null, true, " ", false, 2);
		}
		if ($dim < 1)
			hidden('dimension_id', 0);
		if ($dim < 2)
			hidden('dimension2_id', 0);
	}
	table_section_title(_("Member Details"));
		
	kv_user_list_row('Assigned To','staff_id', null, _("Select an User"), false, false, false, false, '', true);	
	kv_common_type_row(_('Status'), 'status', null,  false, false, 5);

	//for custom fields
	custom_field_section('project',(isset($_POST['project_id']) ?$_POST['project_id'] : '') ,2);
	//end custom fields
	end_outer_table(1);
	br(2);
	//------------------------------------------------------------------------------------
	if(!isset($_SESSION['wa_current_user']->person) || $_SESSION['wa_current_user']->person == 0 || $allow_customer_to_create_project)	{
		div_start('controls');
		if (@$_REQUEST['popup']) hidden('popup', 1);
		if ( $new_item) 	{
			submit_center('addupdate', _("Insert New Project"), true, '', 'default');
		} else {
			submit_center_first('addupdate', _("Update Project"), '', 	$page_nested ? true : 'default');
			submit_return('select', get_post('project_id'), 	_("Select this items and return to document entry."));
			submit('clone', _("Clone This Project"), true, '', true);
			submit('delete', _("Delete This Project"), true, '', true);
			submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
		}
	}
	div_end();
}

//-------------------------------------------------------------------------------------------- 

start_form(true);

if (db_has_projects()) {
	start_table(TABLESTYLE_NOBORDER);
	start_row();
	//$session_debtor_no = GetSingleValue('debtors_master', 'debtor_no', array('user_id' => $_SESSION['wa_current_user']->user));
	
	$default_type = false;
	if(isset($_SESSION['wa_current_user']->person) && $_SESSION['wa_current_user']->person > 0 ) {
		$current_user = $_SESSION['wa_current_user']->person;
		$allow_customer_to_create_project = GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'allow_customer_to_create_project'));
		if($allow_customer_to_create_project)
			$default_type =  _("New Project");
	}else {		
		$master_role = GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'master_role'));		
		if($master_role != (int)$_SESSION['wa_current_user']->access){
			$session_user_id = GetSingleValue('users', 'id', array('id' => $_SESSION['wa_current_user']->user));
		} else {
			$default_type =  _("New Project");
		}
		$allow_customer_to_create_project = false;
		$current_user = false;
	}
    projects_list_cells(_("Select a Project"). " :", 'project_id', null,  $default_type, true, check_value('show_inactive'), false, false, $current_user);
	$new_item = get_post('project_id')=='';
	check_cells(_("Show inactive:"), 'show_inactive', null, true);
	end_row();
	end_table();

	if (get_post('_show_inactive_update')) {
		$Ajax->activate('project_id');
		set_focus('project_id');
	}
	$session_debtor_no = (isset($_SESSION['wa_current_user']->person)? $_SESSION['wa_current_user']->person : null );
}
else {
	hidden('project_id', get_post('project_id'));
	$session_debtor_no = $allow_customer_to_create_project= 0 ;
}

div_start('details');

$project_id = get_post('project_id');
if (!$project_id)
	unset($_POST['_tabs_sel']); // force settings tab for new customer

$tabs =  array(
		'settings' => array(_('&General'), $project_id, $session_debtor_no, $allow_customer_to_create_project),
		'tasks' => array(_('&Tasks'), $project_id),
		'activity' => array(_('&Activity'), $project_id),		
		'attachments' => array(_('Attachments'), (user_check_access('CRM_ATTACHMENTS') ? $project_id : null)),		
		'comments' => array(_('&Comments'), (user_check_access('CRM_COMMENTS') ? $project_id : null)),
		'invoice' => array(_('&Invoices'), $project_id)
);

tabbed_content_start('tabs', $tabs);

	switch (get_post('_tabs_sel')) {
		default:
		case 'settings':
			project_settings($project_id, $new_item, $session_debtor_no, $allow_customer_to_create_project); 
			break;
		
		case 'attachments':
			/*$_GET['type_id'] = $project_id;
			$_GET['type']= 3;  //projects type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/manage/attachments.php");*/ 
			$_GET['type_id'] = $project_id;	
			$_GET['type']= ST_PROJECT;  //projects type
			$attachments = new attachments('attachment', $project_id, 'leads');
			$attachments->show();

			break;
		case 'activity':			
			$_GET['type_id'] = $project_id;	
			$_GET['type']= ST_PROJECT;  //projects type
			$activity = new activity('activity', $project_id, 'projects');
			$activity->show();			
			break;
		case 'comments':
			$_GET['type_id'] = $project_id;	
			$_GET['type']= ST_PROJECT;  //project type
			$comments = new crm_comments('comments', $project_id, 'leads');
			$comments->show();
			break;

		case 'tasks':
			$_GET['type_id'] = $project_id;
			$_GET['type']= ST_PROJECT;  //projects type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/tasks/index.php");
			break;
		case 'invoice':
			$form_media=0;
			$_GET['type']=	ST_PROJECTINVOICE;
			$_GET['project_id'] = $project_id;
			include_once($path_to_root."/modules/KvcodesCRM/inquires/invoice_inquiry.php");
			break;
	};

br();
tabbed_content_end();

div_end();

end_form();
echo "<script type='text/javascript'> kvcodes_crm_nicEditor();  </script> \n";
end_page(); ?>