package My_UserEventFunctions;

use strict;
use Data::Dumper;
use XML::Simple;

our $CrossAgencyRate=0.2;

#--------------------------------------------------------------------------------------------------
sub new
{
  my $pclass = shift;
  my $pdbhMain = shift;
  my $pGLOBALS = shift;
  my $self = {
    dbh=>$pdbhMain,
    GLOBALS=>$pGLOBALS,
    logger=>Log::Log4perl->get_logger()
  };
  bless $self, $pclass;
  $self->{logger}->info("::DBVersions::Instance Started");
  return $self;
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_list
#@author AUTOAPI
#@description List user events(s) on the system
#@params api_action
#action_content>session_id
#action_content>month
#@params_description
#api_action - The name of the function   
#action_content - Container for all api params
#session_id - session_id for the user
#month - month to return (Eg. yyyy-mm , YYYY=Year mm=Month)
#@return 
#status
#error_description
#message_level
#year
#month
#month_number
#days
#days>day
#days>day>day_date
#days>day>day_of_week
#days>day>today
#days>day>events
#days>day>events>event
#days>day>events>event>user_event_id
#days>day>events>event>user_event_value
#days>day>events>event>user_event_time
#days>day>events>event>user_status_id
#days>day>events>event>user_status_check_in
#days>day>events>event>user_status_check_out
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_list($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $return_date;
  my $day_of_week;
  my $today;
  
  if($xml->{action_content}->{month} eq "")
  {
		$statement = "select left(now(),7)";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;
		$xml->{action_content}->{month} = $sth->fetchrow_array;
  }
		$this->{logger}->info($xml->{action_content}->{month});
  
  if(($rxml=My_GenericFunctions->validate_input_field($this,"month",$xml->{action_content}->{month}."-01","DATE","")) ne "")
  {
    return($rxml);
  }
  
  $return_date = $xml->{action_content}->{month}."-01";

	$statement = "select date_format('$return_date','%Y'),date_format('$return_date','%M'),date_format('$return_date','%c'),left(date_sub('$return_date',interval 1 month),7),left(date_add('$return_date',interval 1 month),7)";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row = $sth->fetchrow_array;	
	$rxml .= "<year>$row[0]</year>";
	$rxml .= "<month>$row[1]</month>";
	$rxml .= "<month_number>$row[2]</month_number>";
	$rxml .= "<prev_month>$row[3]</prev_month>";
	$rxml .= "<next_month>$row[4]</next_month>";

	$statement = "select left(now(),10)";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;
	$today = $sth->fetchrow_array;
  
	$statement = "select '$return_date',date_format('$return_date','%W')";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	($return_date,$day_of_week) = $sth->fetchrow_array;  
  
  $rxml .= "<days>";
  do
  {
    $rxml .= "<day>";
  	$rxml .= "<day_date>$return_date</day_date>";
  	$rxml .= "<day_of_week>$day_of_week</day_of_week>";
  	$rxml .= "<today>".($today eq $return_date ? "1" : "0")."</today>";
  	
  	$rxml .= "<events>";
  		
  		$statement = "select ".My_GenericFunctions->return_var_encode("id","tEVENT").",event_name,event_dbdate,staff_count from tEVENT where event_dbdate between '$return_date 00:00:00' and '$return_date 23:59:59' ";
  		if(index($tUSER_TYPE_value,"Agency")==-1)
  		{
				$statement .= " and id in (select tEVENT_id from tUSER_EVENT where tUSER_id=$tUSER_id and tUSER_STATUS_id <> (select id from tUSER_STATUS where value='Declined') and deleted=0)";
			}
			else
			{
				$statement .= " and id in (select tEVENT_id from tUSER_EVENT where tUSER_id in (select id from tUSER where tAGENCY_id=$tAGENCY_id) and tUSER_STATUS_id <> (select id from tUSER_STATUS where value='Declined') and deleted=0)";
			}
  		$statement .= " and deleted=0";
			$this->{logger}->info($statement);
			$sth = $this->{dbh}->prepare("$statement");
			$sth->execute;  
			while(@row = $sth->fetchrow_array)
			{
				$rxml .= "<event>";

					$rxml .= "<user_event_id>$row[0]</user_event_id>";
					$rxml .= "<user_event_value>".My_GenericFunctions->xml_friendly($row[1])."</user_event_value>";
					$rxml .= "<user_event_time>".substr($row[2],-8)."</user_event_time>";
					$rxml .= "<user_event_staff_count>$row[3]</user_event_staff_count>";
							
					$statement = "select ".My_GenericFunctions->return_var_encode("id","tUSER_EVENT").",".My_GenericFunctions->return_var_encode("tUSER_id","tUSER").",".My_GenericFunctions->return_var_encode("tUSER_STATUS_id","tUSER_STATUS").",check_in,check_out,".My_GenericFunctions->return_var_encode("tUSER_CATEGORY_TYPES_id","tUSER_CATEGORY_TYPES")." from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($row[0],"tEVENT")." and tUSER_id=$tUSER_id and deleted=0";
					$this->{logger}->info($statement);
					$sth2 = $this->{dbh}->prepare("$statement");
					$sth2->execute;  
					while(@row2 = $sth2->fetchrow_array)
					{
						$rxml .= "<user_status_id>$row2[2]</user_status_id>";
						$rxml .= "<user_status_check_in>$row2[3]</user_status_check_in>";
						$rxml .= "<user_status_check_out>$row2[4]</user_status_check_out>";
					}
							
				$rxml .= "</event>";
			}
  		
  	$rxml .= "</events>";
  	
  	##Go Next Day
  	$statement = "select left(date_add('$return_date',interval 1 day),10),date_format(left(date_add('$return_date',interval 1 day),10),'%W')";
    $this->{logger}->info($statement);
    $sth = $this->{dbh}->prepare("$statement");
    $sth->execute;  
    ($return_date,$day_of_week) = $sth->fetchrow_array;
    
    $rxml .= "</day>";
  }while(index($return_date,$xml->{action_content}->{month})>-1);
  
  $rxml .= "</days>";

	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_add
#@author AUTOAPI
#@description Add a events(s) on the system
#@params api_action
#action_content>session_id
#action_content>event_name		
#action_content>event_dbdate
#action_content>event_duration
#action_content>event_address
#action_content>event_staff_count
#action_content>event_auto_select_staff
#action_content>event_special_request
#@params_description
#api_action - The name of the function   
#action_content - Container for all api params
#session_id - session_id for the user
#event_name - Name of the event		
#event_dbdate - DateTime of the event
#event_duration - Duration of the event, in minutes 
#event_address - Address of the event
#event_staff_count - How many staff to be selected
#event_auto_select_staff - Should the system automatically select staff
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_add($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $tEVENT_id;
  
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_name",$xml->{action_content}->{event_name}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_dbdate",$xml->{action_content}->{event_dbdate}."","DATETIME","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_duration",$xml->{action_content}->{event_duration}."","INT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_address",$xml->{action_content}->{event_address}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_staff_count",$xml->{action_content}->{event_staff_count}."","INT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_auto_select_staff",$xml->{action_content}->{event_auto_select_staff}."","BOOL","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_special_request",$xml->{action_content}->{event_special_request}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  
  $statement = "INSERT INTO tEVENT ( `tEVENT_STATUS_id`, `event_name`, `event_dbdate`, `duration`, `address`, `staff_count`, `auto_select_staff`, `can_accept_payment`, `deposit_received`, `deposit_notes`, `full_payment_received`, `full_payment_notes`,`special_notes`) VALUES ( (select id from tEVENT_STATUS where value='New'), \"".$xml->{action_content}->{event_name}."\", \"".$xml->{action_content}->{event_dbdate}."\", \"".$xml->{action_content}->{event_duration}."\", \"".$xml->{action_content}->{event_address}."\", \"".$xml->{action_content}->{event_staff_count}."\", \"".$xml->{action_content}->{event_auto_select_staff}."\", 0, 0, '', 0, '', \"".$xml->{action_content}->{event_special_request}."\");";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  

	$statement = "select LAST_INSERT_ID(),hex(aes_encrypt(LAST_INSERT_ID(),'tEVENT')) ";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row = $sth->fetchrow_array;
	$rxml .= "<user_event_id>$row[1]</user_event_id>";
	
	$tEVENT_id = $row[0];
	
	$statement = "INSERT INTO tUSER_EVENT ( `tUSER_id`, `tEVENT_id`, `tUSER_STATUS_id`, `check_in`, `check_out`, `notes`, `rating`, `estimated_event_cost`, `final_event_cost`, `requires_agency_approval`) VALUES ( $tUSER_id, $tEVENT_id, (select id from tUSER_STATUS where value='Event Orginazer'), 0, 0, '', '', '', '', 0);";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_view
#@author AUTOAPI
#@description View a user event on the system
#@params api_action
#action_content>session_id
#action_content>user_event_id
#@params_description
#api_action - The name of the function   
#action_content - Container for all api params
#session_id - session_id for the user
#user_event_id - ID of the event to view
#@return 
#status
#error_description
#message_level
#user_event_id
#user_event_name
#user_event_dbdate
#user_event_duration
#user_event_address
#user_event_special_request
#user_event_staff_count
#user_event_auto_select_staff
#user_event_can_accept_payment
#user_event_deposit_received
#user_event_payment_received
#user_event_total_cost
#user_event_deposit_amount
#user_event_reference
#user_event_banking_details
#user_status_id 
#event_status_id
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#user_event_id - ID of the event
#user_event_name - Name of the event		
#user_event_dbdate - DateTime of the event
#user_event_duration - Duration of the event, in minutes 
#user_event_address - Address of the event
#user_event_staff_count - How many staff to be selected
#user_event_auto_select_staff - Should the system automatically select staff
#user_event_can_accept_payment
#user_event_deposit_received
#user_event_payment_received
#user_event_reference
#user_event_banking_details
#event_status_id
#user_status_id 
#@document_class both
sub user_event_functions_event_view($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $return_date;
  my $day_of_week;
  my $today;
  my $total_cost=0;
	my $AgencyGlobals=My_GenericFunctions->GetPlatformGlobals($this,$tAGENCY_id);
	my $SystemGlobals=My_GenericFunctions->GetSystemGlobals($this);	

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FK","tEVENT")) ne "")
  {
    return($rxml);
  }


	$statement = "select ".My_GenericFunctions->return_var_encode("id","tEVENT").",event_name,event_dbdate,duration,address,staff_count,auto_select_staff,can_accept_payment,deposit_received,full_payment_received,".My_GenericFunctions->return_var_encode("tEVENT_STATUS_id","tEVENT_STATUS").",special_notes,id from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$rxml .= "<user_event_id>$row[0]</user_event_id>";
		$rxml .= "<user_event_value>".My_GenericFunctions->xml_friendly($row[1])."</user_event_value>";
		$rxml .= "<user_event_time>".$row[2]."</user_event_time>";
		$rxml .= "<user_event_duration>".$row[3]."</user_event_duration>";
		$rxml .= "<user_event_address>".My_GenericFunctions->xml_friendly($row[4])."</user_event_address>";
		$rxml .= "<user_event_staff_count>".$row[5]."</user_event_staff_count>";
		$rxml .= "<user_event_auto_select_staff>".$row[6]."</user_event_auto_select_staff>";
		$rxml .= "<user_event_can_accept_payment>".$row[7]."</user_event_can_accept_payment>";
		$rxml .= "<user_event_deposit_received>".$row[8]."</user_event_deposit_received>";
		$rxml .= "<user_event_payment_received>".$row[9]."</user_event_payment_received>";
		$rxml .= "<event_status_id>$row[10]</event_status_id>";
		$rxml .= "<user_event_special_request>".My_GenericFunctions->xml_friendly($row[11])."</user_event_special_request>";
		$rxml .= "<user_event_reference>$row[12]</user_event_reference>";
	}
		$rxml .= "<user_event_banking_details>".My_GenericFunctions->xml_friendly($SystemGlobals->{"eft_details"})."</user_event_banking_details>";
	
	$statement = "select ".My_GenericFunctions->return_var_encode("id","tUSER_EVENT").",".My_GenericFunctions->return_var_encode("tUSER_id","tUSER").",".My_GenericFunctions->return_var_encode("tUSER_STATUS_id","tUSER_STATUS").",check_in,check_out,".My_GenericFunctions->return_var_encode("tUSER_CATEGORY_TYPES_id","tUSER_CATEGORY_TYPES").",rating from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_id=$tUSER_id and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$rxml .= "<user_status_id>$row[2]</user_status_id>";
		$rxml .= "<user_status_check_in>$row[3]</user_status_check_in>";
		$rxml .= "<user_status_check_out>$row[4]</user_status_check_out>";
		$rxml .= "<user_category_id>$row[5]</user_category_id>";
		$rxml .= "<user_event_rating>$row[6]</user_event_rating>";		
	}
	
	$rxml .= "<user_details>";
		
	$statement = "select ".My_GenericFunctions->return_var_encode("id","tUSER_EVENT").",".My_GenericFunctions->return_var_encode("tUSER_id","tUSER").",".My_GenericFunctions->return_var_encode("tUSER_STATUS_id","tUSER_STATUS").",check_in,check_out,".My_GenericFunctions->return_var_encode("tUSER_CATEGORY_TYPES_id","tUSER_CATEGORY_TYPES").",estimated_event_cost,final_event_cost,client_rating,confirmed,client_check_in,client_check_out from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_id<>$tUSER_id and tUSER_STATUS_id not in (select id from tUSER_STATUS where value in ('Declined','Auto Declined')) and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$rxml .= "<user_detail>";
		
		$rxml .= "<user_event_detail_id>$row[0]</user_event_detail_id>";
		$rxml .= "<user_id>$row[1]</user_id>";
		$rxml .= "<user_status_id>$row[2]</user_status_id>";
		$rxml .= "<user_status_check_in>$row[3]</user_status_check_in>";
		$rxml .= "<user_status_check_out>$row[4]</user_status_check_out>";
		$rxml .= "<user_status_client_check_in>$row[10]</user_status_client_check_in>";
		$rxml .= "<user_status_client_check_out>$row[11]</user_status_client_check_out>";
		$rxml .= "<user_category_id>$row[5]</user_category_id>";		
		$rxml .= "<user_event_cost>".($row[7] eq "" ? $row[6] : $row[7])."</user_event_cost>";		
		$rxml .= "<user_event_client_rating>$row[8]</user_event_client_rating>";		
		$rxml .= "<user_event_confirmed_client>$row[9]</user_event_confirmed_client>";		
		$rxml .= "</user_detail>";
		
		$total_cost += ($row[7] eq "" ? $row[6] : $row[7]);
	}	
	$rxml .= "</user_details>";	
	
	$rxml .= "<event_category_details>";	
	$statement = "select hex(aes_encrypt(tUSER_CATEGORY_TYPES_id,'tUSER_CATEGORY_TYPES')), start_time,duration from tEVENT_CATEGORIES where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$rxml .= "<event_category_detail>";
		$rxml .= "<user_category_id>$row[0]</user_category_id>";
		$rxml .= "<start_time>$row[1]</start_time>";
		$rxml .= "<duration>$row[2]</duration>";
		$rxml .= "</event_category_detail>";
	}	
	$rxml .= "</event_category_details>";	

	$rxml .= "<user_event_total_cost>$total_cost</user_event_total_cost>";
	
	$statement = "select amount from tUSER_PAYMENTS where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows==0)
	{
		$rxml .= "<user_event_deposit_amount>".(($total_cost/100)*$AgencyGlobals->{DepositPercentage})."</user_event_deposit_amount>";
	}
	else
	{
		@row = $sth->fetchrow_array;
		$rxml .= "<user_event_deposit_amount>".$row[0]."</user_event_deposit_amount>";
		
	}
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_edit
#@author AUTOAPI
#@description Edit a user event on the system
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>event_duration
#action_content>event_address
#action_content>event_staff_count
#action_content>event_special_request
#action_content>event_datetime
#@params_description
#api_action - The name of the function   
#action_content - Container for all api params
#session_id - session_id for the user
#user_event_id - ID of the event to view
#event_duration - Duration of the event, in minutes 
#event_address - Address of the event
#event_staff_count - How many staff to be selected
#event_special_request - special request to event staff
#event_datetime - date and time of the event
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_edit($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $return_date;
  my $day_of_week;
  my $today;
  my $event_staff_agency;

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }

  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_duration",$xml->{action_content}->{event_duration}."","INT","")) ne "")
  {
    return($rxml);2
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_address",$xml->{action_content}->{event_address}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_staff_count",$xml->{action_content}->{event_staff_count}."","INT","")) ne "")
  {
    return($rxml);
  }
#   if(($rxml=My_GenericFunctions->validate_input_field($this,"event_special_request",$xml->{action_content}->{event_special_request}."","TEXT","")) ne "")
#   {
#     return($rxml);
#   }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_datetime",$xml->{action_content}->{event_datetime}."","DATETIME","")) ne "")
  {
    return($rxml);
  }

	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}

	$statement = "update tEVENT set event_dbdate=\"".$xml->{action_content}->{event_datetime}."\",duration=\"".$xml->{action_content}->{event_duration}."\",address=\"".$xml->{action_content}->{event_address}."\",staff_count=\"".$xml->{action_content}->{event_staff_count}."\",special_notes=\"".$xml->{action_content}->{event_special_request}."\" where  id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."  and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("Failed to Update Event.","warn"));
	}

	$statement = "select id,tUSER_id,tUSER_CATEGORY_TYPES_id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and estimated_event_cost>0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$event_staff_agency=0;
		
		$statement = "select tAGENCY_id from tUSER where id=$row[1]";
		$this->{logger}->info($statement);
		$sth2 = $this->{dbh}->prepare("$statement");
		$sth2->execute;  
		@row2 = $sth2->fetchrow_array;
		if($row2[0] != $tAGENCY_id)
		{
			$event_staff_agency=1;
		}

		$statement = "update tUSER_EVENT set estimated_event_cost=CEILING((select hourly_cost from tUSER_CATEGORY where tUSER_id=$row[1] and tUSER_CATEGORY_TYPES_id=tUSER_EVENT.tUSER_CATEGORY_TYPES_id)*(select duration/60 from tEVENT_CATEGORIES where tEVENT_CATEGORIES.tEVENT_id=tUSER_EVENT.tEVENT_id and tEVENT_CATEGORIES.tUSER_CATEGORY_TYPES_id=tUSER_EVENT.tUSER_CATEGORY_TYPES_id)".($event_staff_agency eq "1"? "*$CrossAgencyRate": "").")  where  id=$row[0]";
		$this->{logger}->info($statement);
		$sth2 = $this->{dbh}->prepare("$statement");
		$sth2->execute;  		
	}
	

	

  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}
#--------------------------------------------------------------------------------------------------
#@function user_event_functions_user_status_list
#@author AUTOAPI
#@description List user status(s) on the ssystem
#@params api_action
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#user_statuses
#user_statuses>user_status
#user_statuses>user_status>user_status_id
#user_statuses>user_status>user_status_value
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#user_statuses
#user_status
#user_status_id
#user_status_value
#@document_class both
sub user_event_functions_user_status_list($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

	
	$statement = "select ".My_GenericFunctions->return_var_encode("id","tUSER_STATUS")." as 'user_status_id', value as 'user_status_value'  from tUSER_STATUS ";
  $rxml .= My_GenericFunctions->execute_and_return_data($this,$xml,$statement,"user_statuses","user_status");	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_status_list
#@author AUTOAPI
#@description List event status(s) on the ssystem
#@params api_action
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#event_statuses
#event_statuses>event_status
#event_statuses>event_status>event_status_id
#event_statuses>event_status>event_status_value
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#event_statuses
#event_status
#event_status_id
#event_status_value
#@document_class both
sub user_event_functions_event_status_list($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

	
	$statement = "select ".My_GenericFunctions->return_var_encode("id","tEVENT_STATUS")." as 'event_status_id', value as 'event_status_value'  from tEVENT_STATUS ";
  $rxml .= My_GenericFunctions->execute_and_return_data($this,$xml,$statement,"event_statuses","event_status");	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}



#--------------------------------------------------------------------------------------------------
#@function user_event_functions_user_status_edit
#@author AUTOAPI
#@description Change the users status for a event on the ssystem
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_status_id
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_user_status_edit($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FK","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_status_id",$xml->{action_content}->{user_status_id}."","FK","tUSER_STATUS")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}
	
	$statement = "select id from tUSER_STATUS where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_status_id},"tUSER_STATUS")." and can_select=1;";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such User Status.","warn"));
	}
	
	$statement = "update tUSER_EVENT set tUSER_STATUS_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_status_id},"tUSER_STATUS")." where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
	}
	
	$statement = "insert into tUSER_NOTIFICATION (tUSER_id,message,shown,dbdate_added) values ((select tUSER_id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer')),concat('A User Changed their status (',(select value from tUSER_STATUS where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_status_id},"tUSER_STATUS")."),') to your event: ',(select event_name from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT").")),0,now())";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	
	$statement = "select staff_count from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row = $sth->fetchrow_array;
	
	$statement = "select count(*) from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Available')";	
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row2 = $sth->fetchrow_array;
	
	if($row[0] eq $row2[0])
	{
		$statement = "update tEVENT set tEVENT_STATUS_id=(select id from tEVENT_STATUS where value='All Staff Confirmed'),can_accept_payment=1 where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		
		$statement = "insert into tUSER_NOTIFICATION (tUSER_id,message,shown,dbdate_added) values ((select tUSER_id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer')),'CAL:".$xml->{action_content}->{user_event_id}."~Event Status Changed to: All Staff Confirmed',0,now())";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		
	}
	else
	{
		$statement = "update tEVENT set tEVENT_STATUS_id=(select id from tEVENT_STATUS where value='New') where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
	}
	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_delete
#@author AUTOAPI
#@description Delete an Event
#@params api_action
#action_content>session_id
#action_content>user_event_id
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_delete($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}
	
	$statement = "update tEVENT set deleted=1 where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
	}
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_check_in
#@author AUTOAPI
#@description Check-In to an event§
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_id
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_check_in($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
	
	if($xml->{action_content}->{user_id} ne "")
	{
		if(($rxml=My_GenericFunctions->validate_input_field($this,"user_id",$xml->{action_content}->{user_id}."","FKND","tUSER")) ne "")
		{
			return($rxml);
		}
			
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}

		$statement = "select id from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and event_dbdate<date_add(now(),interval 10 minute)";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("You may only check in 10 minutes before the event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set client_check_in=now() where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and client_check_in is NULL";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
		
	}
	else
	{
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}
		
		$statement = "select id from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and event_dbdate<date_add(now(),interval 10 minute)";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("You may only check in 10 minutes before the event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set check_in=now() where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and check_in = \"0000-00-00 00:00:00\"";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
		
		$statement = "select msisdn,tAGENCY_id from tUSER where id=(select tUSER_id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."  and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') )";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		@row = $sth->fetchrow_array;
		
		my $uHash = My_GenericFunctions->GetUserGlobals($this,$tUSER_id);
		
		My_GenericFunctions->SendSMS($this,$row[1],$row[0],$uHash->{"Name"}." ".$uHash->{"Surname"}." Just Checked In For your Event.");		
	}
	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_check_out
#@author AUTOAPI
#@description Check-Out to an event§
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_id
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_check_out($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
	
	if($xml->{action_content}->{user_id} ne "")
	{
		if(($rxml=My_GenericFunctions->validate_input_field($this,"user_id",$xml->{action_content}->{user_id}."","FKND","tUSER")) ne "")
		{
			return($rxml);
		}
			
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set client_check_out=now() where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and client_check_in is not null ";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
		
	}
	else
	{
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set check_out=now() where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and check_in<>\"0000-00-00 00:00:00\"";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
	}
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_user_review
#@author AUTOAPI
#@description Review a User/Client after an event
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_id
#action_content>rating
#action_content>review
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_user_review($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"rating",$xml->{action_content}->{rating}."","INT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"review",$xml->{action_content}->{review}."","TEXT","")) ne "")
  {
    return($rxml);
  }
	
	if($xml->{action_content}->{user_id} ne "")
	{
		if(($rxml=My_GenericFunctions->validate_input_field($this,"user_id",$xml->{action_content}->{user_id}."","FKND","tUSER")) ne "")
		{
			return($rxml);
		}
			
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set client_rating=\"".$xml->{action_content}->{rating}."\",client_notes=\"".$xml->{action_content}->{review}."\" where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and check_out is not null ";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
		
	}
	else
	{
		$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("No Such Event.","warn"));
		}
		
		$statement = "update tUSER_EVENT set rating=\"".$xml->{action_content}->{rating}."\",notes=\"".$xml->{action_content}->{review}."\" where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id<>(select id from tUSER_STATUS where value='Event Orginazer') and check_in is not null";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Save Changes.","warn"));
		}
	}
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_user_add
#@author AUTOAPI
#@description Add a staff member to an event
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_id
#action_content>user_category_type_id
#action_content>confirm
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_user_add($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $event_staff_agency=0;
  my $event_staff_agency_id=0;

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_id",$xml->{action_content}->{user_id}."","FKND","tUSER")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_category_type_id",$xml->{action_content}->{user_category_type_id}."","FK","tUSER_CATEGORY_TYPES")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"confirm",$xml->{action_content}->{confirm}."","BOOL","")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}

	$statement = "select tAGENCY_id from tUSER where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row = $sth->fetchrow_array;
	$event_staff_agency_id = $row[0];
	if($row[0] != $tAGENCY_id)
	{
		$event_staff_agency=1;
	}


	$statement = "select confirmed from tUSER_EVENT where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 0 )
	{
		@row = $sth->fetchrow_array;
		if($row[0] eq "1")
		{
    	return(My_GenericFunctions->return_error("Person already used as Event Staff.","warn"));
    }
    
		$statement = "update tUSER_EVENT set confirmed=\"".$xml->{action_content}->{confirm}."\" where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and deleted=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
    
		$statement = "select event_dbdate from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		@row = $sth->fetchrow_array;
		
		$statement = "insert into tUSER_NOTIFICATION (tUSER_id,message,dbdate_added) values (".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER").",\"CAL:".$xml->{action_content}->{user_event_id}."~New Event Request for ".substr($row[0],0,10)."\",now())";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
	
		if($event_staff_agency eq "1")
		{
			$statement = "select id from tUSER where tAGENCY_id=$event_staff_agency_id and deleted=0;";
			$this->{logger}->info($statement);
			$sth = $this->{dbh}->prepare("$statement");
			$sth->execute;  
			while(@row = $sth->fetchrow_array)
			{
				$statement = "insert into tUSER_NOTIFICATION (tUSER_id,message,dbdate_added) values ($row[0],\"RAPP~New Cross Agency Event Staff Request\",now())";
				$this->{logger}->info($statement);
				$sth = $this->{dbh}->prepare("$statement");
				$sth->execute;  
			}		
		}    
	}
	else
	{
		$statement = "insert ignore into tEVENT_CATEGORIES (tEVENT_id,tUSER_CATEGORY_TYPES_id,start_time,duration) values (".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT").",".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_type_id},"tUSER_CATEGORY_TYPES").",(select event_dbdate from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."),(select duration from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."))";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;
	
		$statement = "insert into tUSER_EVENT (tUSER_id,tEVENT_id,tUSER_STATUS_id,tUSER_CATEGORY_TYPES_id,estimated_event_cost,requires_agency_approval,dbdate_added,confirmed) values  (".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER").",".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT").",(select id from tUSER_STATUS where value='Requested Availability'),".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_type_id},"tUSER_CATEGORY_TYPES").",CEILING((select hourly_cost from tUSER_CATEGORY where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tUSER_CATEGORY_TYPES_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_type_id},"tUSER_CATEGORY_TYPES").")*(select duration/60 from tEVENT_CATEGORIES where tEVENT_CATEGORIES.tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tEVENT_CATEGORIES.tUSER_CATEGORY_TYPES_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_type_id},"tUSER_CATEGORY_TYPES").")".($event_staff_agency eq "1"? "*$CrossAgencyRate": "")."),$event_staff_agency,now(),\"".$xml->{action_content}->{confirm}."\")";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows != 1 )
		{
			return(My_GenericFunctions->return_error("Failed to Add Event Staff.","warn"));
		}
		
	}
	

	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_user_delete
#@author AUTOAPI
#@description Delete a staff member from an event
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_id
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_user_delete($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $event_staff_agency=0;
  my $event_staff_agency_id=0;

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_id",$xml->{action_content}->{user_id}."","FKND","tUSER")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}

	$statement = "select id from tUSER_EVENT where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("User not linked to Event.","warn"));
	}
	
	$statement = "update tUSER_EVENT set deleted=1 where tUSER_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_id},"tUSER")." and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." ";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("Failed to delete Staff from Event.","warn"));
	}
	
	$statement = "select tUSER_CATEGORY_TYPES_id from tEVENT_CATEGORIES where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$statement = "select id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_CATEGORY_TYPES_id=$row[0] and deleted=0";
		$this->{logger}->info($statement);
		$sth2 = $this->{dbh}->prepare("$statement");
		$sth2->execute;  
		if($sth2->rows==0)
		{
			$statement = "delete from tEVENT_CATEGORIES where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_CATEGORY_TYPES_id=$row[0]";
			$this->{logger}->info($statement);
			$sth = $this->{dbh}->prepare("$statement");
			$sth->execute;  
		}
	}
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_category_edit
#@author AUTOAPI
#@description Edit Event Details for a Category
#@params api_action
#action_content>session_id
#action_content>user_event_id
#action_content>user_category_id
#action_content>event_datetime
#action_content>event_duration
#@params_description
#api_action - The name of the function   
#user_event_id - 
#user_category_id - 
#event_datetime - 
#event_duration - 
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_category_edit($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $event_staff_agency=0;
  my $event_staff_agency_id=0;

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_id",$xml->{action_content}->{user_event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_category_id",$xml->{action_content}->{user_category_id}."","FK","tUSER_CATEGORY_TYPES")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_datetime",$xml->{action_content}->{event_datetime}."","DATETIME","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_duration",$xml->{action_content}->{event_duration}."","INT","")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tUSER_id=$tUSER_id and tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer') and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}

	$statement = "select id from tEVENT_CATEGORIES
 where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_CATEGORY_TYPES_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_id},"tUSER_CATEGORY_TYPES")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Category.","warn"));
	}
	
	$statement = "update tEVENT_CATEGORIES set start_time=\"".$xml->{action_content}->{event_datetime}."\",duration=\"".$xml->{action_content}->{event_duration}."\"  where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and tUSER_CATEGORY_TYPES_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_category_id},"tUSER_CATEGORY_TYPES")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	
	$statement = "select id,tUSER_id,tUSER_CATEGORY_TYPES_id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_id},"tEVENT")." and estimated_event_cost>0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$event_staff_agency=0;
		
		$statement = "select tAGENCY_id from tUSER where id=$row[1]";
		$this->{logger}->info($statement);
		$sth2 = $this->{dbh}->prepare("$statement");
		$sth2->execute;  
		@row2 = $sth2->fetchrow_array;
		if($row2[0] != $tAGENCY_id)
		{
			$event_staff_agency=1;
		}

		$statement = "update tUSER_EVENT set estimated_event_cost=CEILING((select hourly_cost from tUSER_CATEGORY where tUSER_id=$row[1] and tUSER_CATEGORY_TYPES_id=tUSER_EVENT.tUSER_CATEGORY_TYPES_id)*(select duration/60 from tEVENT_CATEGORIES where tEVENT_CATEGORIES.tEVENT_id=tUSER_EVENT.tEVENT_id and tEVENT_CATEGORIES.tUSER_CATEGORY_TYPES_id=tUSER_EVENT.tUSER_CATEGORY_TYPES_id)".($event_staff_agency eq "1"? "*$CrossAgencyRate": "").")  where  id=$row[0]";
		$this->{logger}->info($statement);
		$sth2 = $this->{dbh}->prepare("$statement");
		$sth2->execute;  		
	}
	
	

  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_agency_accept_booking
#@author AUTOAPI
#@description Delete a staff member from an event
#@params api_action
#action_content>session_id
#action_content>user_event_booking_id
#action_content>user_event_booking_rate
#@params_description
#api_action - The name of the function   
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_agency_accept_booking($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $event_staff_agency=0;
  my $event_staff_agency_id=0;

  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_booking_id",$xml->{action_content}->{user_event_booking_id}."","FKND","tUSER_EVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"user_event_booking_rate",$xml->{action_content}->{user_event_booking_rate}."","FLOAT","")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_booking_id},"tUSER_EVENT")." and requires_agency_approval=1 and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("No Such Event.","warn"));
	}


	$statement = "update tUSER_EVENT set requires_agency_approval=0,final_event_cost=\"".$xml->{action_content}->{user_event_booking_rate}."\" where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{user_event_booking_id},"tUSER_EVENT")." and requires_agency_approval=1 and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("Failed to update.","warn"));
	}	
	
  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}


#--------------------------------------------------------------------------------------------------
#@function user_event_functions_event_make_payment
#@author AUTOAPI
#@description Accept a payment for a event booking
#@params api_action
#action_content>session_id
#action_content>event_id
#action_content>card_number
#action_content>card_owner_name
#action_content>card_owner_surname
#action_content>card_exp_year
#action_content>card_exp_month
#action_content>card_cvv
#@params_description
#api_action - The name of the function   
#event_id
#card_number
#card_owner_name
#card_owner_surname
#card_exp_year
#card_exp_month
#card_cvv
#@return 
#status
#error_description
#message_level
#@return_description 
#status - Status of the Call (True=Success/False=Faiure)
#error_description - Error description if any
#message_level - The message level, warning or critical
#@document_class both
sub user_event_functions_event_make_payment($)
{
  my $this      = shift;
  my ($xml)     = @_;
  my $extXml    = "";
  my $cmd       = "";
  my $rxml      = "";
  my $frxml     = "";
  my $statement = "";
  my $ustatement = "";
  my $sth;
  my $sth2;
  my $sth3;
  my $sth4;
  my @row;
  my @row2;
  my $tUSER_id=$this->{GLOBALS}{tUSER_id};
  my $tUSER_TYPE_value=$this->{GLOBALS}{tUSER_TYPE_value};
  my $tAGENCY_value=$this->{GLOBALS}{tAGENCY_value};
  my $tAGENCY_id=$this->{GLOBALS}{tAGENCY_id};  
  my $event_staff_agency=0;
  my $event_staff_agency_id=0;
  my $total_cost;
	my $amount;
	my $billed=0;
	my $sts_err;
	my $rHash;
	my $ptype;
	
	my $AgencyGlobals=My_GenericFunctions->GetPlatformGlobals($this,$tAGENCY_id);
	my $SystemGlobals=My_GenericFunctions->GetSystemGlobals($this);	
	
  if(($rxml=My_GenericFunctions->validate_input_field($this,"event_id",$xml->{action_content}->{event_id}."","FKND","tEVENT")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_number",$xml->{action_content}->{card_number}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_owner_name",$xml->{action_content}->{card_owner_name}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_owner_surname",$xml->{action_content}->{card_owner_surname}."","TEXT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_exp_year",$xml->{action_content}->{card_exp_year}."","INT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_exp_month",$xml->{action_content}->{card_exp_month}."","INT","")) ne "")
  {
    return($rxml);
  }
  if(($rxml=My_GenericFunctions->validate_input_field($this,"card_cvv",$xml->{action_content}->{card_cvv}."","INT","")) ne "")
  {
    return($rxml);
  }
	
	$statement = "select id from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT")." and tUSER_id=$tUSER_id and tUSER_STATUS_id=(select id from tUSER_STATUS where value='Event Orginazer')";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	if($sth->rows != 1 )
	{
    return(My_GenericFunctions->return_error("You are not the event owner.","warn"));
	}

	$statement = "select ".My_GenericFunctions->return_var_encode("id","tUSER_EVENT").",".My_GenericFunctions->return_var_encode("tUSER_id","tUSER").",".My_GenericFunctions->return_var_encode("tUSER_STATUS_id","tUSER_STATUS").",check_in,check_out,".My_GenericFunctions->return_var_encode("tUSER_CATEGORY_TYPES_id","tUSER_CATEGORY_TYPES").",estimated_event_cost,final_event_cost,client_rating,confirmed from tUSER_EVENT where tEVENT_id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT")." and tUSER_id<>$tUSER_id and tUSER_STATUS_id not in (select id from tUSER_STATUS where value in ('Declined','Auto Declined')) and deleted=0";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	while(@row = $sth->fetchrow_array)
	{
		$total_cost += ($row[7] eq "" ? $row[6] : $row[7]);
	}	

	#$rxml .= "<user_event_total_cost>$total_cost</user_event_total_cost>";
	#$rxml .= "<user_event_deposit_amount>".(($total_cost/100)*$AgencyGlobals->{DepositPercentage})."</user_event_deposit_amount>";
	
	$statement = "select ".My_GenericFunctions->return_var_encode("id","tEVENT").",event_name,event_dbdate,duration,address,staff_count,auto_select_staff,can_accept_payment,deposit_received,full_payment_received,".My_GenericFunctions->return_var_encode("tEVENT_STATUS_id","tEVENT_STATUS").",special_notes from tEVENT where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT")."";
	$this->{logger}->info($statement);
	$sth = $this->{dbh}->prepare("$statement");
	$sth->execute;  
	@row = $sth->fetchrow_array;
# 		$rxml .= "<user_event_can_accept_payment>".$row[7]."</user_event_can_accept_payment>";
# 		$rxml .= "<user_event_deposit_received>".$row[8]."</user_event_deposit_received>";
# 		$rxml .= "<user_event_payment_received>".$row[9]."</user_event_payment_received>";
	
	if($row[7] ne "1")
	{
    return(My_GenericFunctions->return_error("This event cant accept payment yet.","warn"));
	}
	if($row[8] eq "0")
	{
		$ptype = "Deposit Payment";
		$amount = (($total_cost/100)*$AgencyGlobals->{DepositPercentage});
	}
	else
	{
		$ptype = "Outstanding Payment";
		$amount = ($total_cost-(($total_cost/100)*$AgencyGlobals->{DepositPercentage}));
	}
	
	$billed=0;
	my $sts_xml_to_send = '<CreditCardController.CreditCardRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Smartcalltech.Payments.Controllers">
  <AmountInRandsAndCents>'.$amount.'</AmountInRandsAndCents>
  <CVV>'.$xml->{action_content}->{card_cvv}.'</CVV>
  <Cardnumber>'.$xml->{action_content}->{card_number}.'</Cardnumber>
  <Clientnumber>'.$tUSER_id.'</Clientnumber>
  <Contactnumber>27824624213</Contactnumber>
  <Expirdate>'.$xml->{action_content}->{card_exp_year}.'-'.$xml->{action_content}->{card_exp_month}.'-01</Expirdate>
  <MerchantName>VIDI</MerchantName>
  <Name>'.$xml->{action_content}->{card_owner_name}.'</Name>
  <ProductDescription>VIDI</ProductDescription>
  <ProductName>VIDI</ProductName>
  <Surname>'.$xml->{action_content}->{card_owner_surname}.'</Surname>
  </CreditCardController.CreditCardRequest>';
	$rHash = do_api_request_sts_cc('https://smartcalltech.co.za/MerchantPayments/api/creditcard/process/',$sts_xml_to_send);
	if(defined($rHash))
	{
		#<CreditCardController.CreditCardResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Smartcalltech.Payments.Controllers"><AmountCollected>0.00</AmountCollected><AmoutExcludingCostToClient>0.00</AmoutExcludingCostToClient><BankReferenceNumber></BankReferenceNumber><ClientNumber>000000005</ClientNumber><ContractNumber>+27824624213</ContractNumber><CostToClient>0.00</CostToClient><NextAttemptDate></NextAttemptDate><ReferenceNumber>20099711</ReferenceNumber><ResponseCode>T8</ResponseCode><ResponseDescription i:nil="true" /><Sequence>1</Sequence><Status>Failed</Status><Success>false</Success><TransactionNumber>74216586</TransactionNumber><TransmissionDate>2016-01-12 12:58:40</TransmissionDate></CreditCardController.CreditCardResponse>|
		if($rHash->{Success} eq "false")
		{
			if($rHash->{ResponseCode} eq '1') { $sts_err = (('Refer to card issuer'));}
			elsif($rHash->{ResponseCode} eq '2') { $sts_err = (('Refer to card issuer, special condition'));}
			elsif($rHash->{ResponseCode} eq '3') { $sts_err = (('Invalid merchant or service provider'));}
			elsif($rHash->{ResponseCode} eq '4') { $sts_err = (('Pickup card'));}
			elsif($rHash->{ResponseCode} eq '5') { $sts_err = (('Do not honor'));}
			elsif($rHash->{ResponseCode} eq '6') { $sts_err = (('Error'));}
			elsif($rHash->{ResponseCode} eq '7') { $sts_err = (('Pickup card, special condition (other than lost/stolen card)'));}
			elsif($rHash->{ResponseCode} eq '10') { $sts_err = (('Partial Approval'));}
			elsif($rHash->{ResponseCode} eq '11') { $sts_err = (('V.I.P. approval'));}
			elsif($rHash->{ResponseCode} eq '12') { $sts_err = (('Invalid transaction'));}
			elsif($rHash->{ResponseCode} eq '13') { $sts_err = (('Invalid amount (currency conversion field overflow) or amount exceeds maximum for card program'));}
			elsif($rHash->{ResponseCode} eq '14') { $sts_err = (('Invalid account number (no such number)'));}
			elsif($rHash->{ResponseCode} eq '15') { $sts_err = (('No such issuer'));}
			elsif($rHash->{ResponseCode} eq '19') { $sts_err = (('Re-enter transaction'));}
			elsif($rHash->{ResponseCode} eq '21') { $sts_err = (('No action taken (unable to back out prior transaction)'));}
			elsif($rHash->{ResponseCode} eq '25') { $sts_err = (('Unable to locate record in file, or account number is missing from the inquiry'));}
			elsif($rHash->{ResponseCode} eq '28') { $sts_err = (('File is temporarily unavailable'));}
			elsif($rHash->{ResponseCode} eq '41') { $sts_err = (('Pickup card (lost card)'));}
			elsif($rHash->{ResponseCode} eq '43') { $sts_err = (('Pickup card (stolen card)'));}
			elsif($rHash->{ResponseCode} eq '51') { $sts_err = (('Insufficient funds'));}
			elsif($rHash->{ResponseCode} eq '52') { $sts_err = (('No checking account'));}
			elsif($rHash->{ResponseCode} eq '53') { $sts_err = (('No savings account'));}
			elsif($rHash->{ResponseCode} eq '54') { $sts_err = (('Expired card'));}
			elsif($rHash->{ResponseCode} eq '55') { $sts_err = (('Incorrect PIN'));}
			elsif($rHash->{ResponseCode} eq '57') { $sts_err = (('Transaction not permitted to cardholder'));}
			elsif($rHash->{ResponseCode} eq '58') { $sts_err = (('Transaction not allowed at terminal'));}
			elsif($rHash->{ResponseCode} eq '59') { $sts_err = (('Suspected fraud'));}
			elsif($rHash->{ResponseCode} eq '61') { $sts_err = (('Activity amount limit exceeded'));}
			elsif($rHash->{ResponseCode} eq '62') { $sts_err = (('Restricted card (for example, in Country Exclusion table)'));}
			elsif($rHash->{ResponseCode} eq '63') { $sts_err = (('Security violation'));}
			elsif($rHash->{ResponseCode} eq '65') { $sts_err = (('Activity count limit exceeded'));}
			elsif($rHash->{ResponseCode} eq '75') { $sts_err = (('Allowable number of PIN-entry tries exceeded'));}
			elsif($rHash->{ResponseCode} eq '76') { $sts_err = (('Unable to locate previous message (no match on Retrieval Reference number)'));}
			elsif($rHash->{ResponseCode} eq '77') { $sts_err = (('Previous message located for a repeat or reversal, but repeat or reversal data are inconsistent with original message'));}
			elsif($rHash->{ResponseCode} eq '78') { $sts_err = (('’Blocked, first used’—The transaction is from a new cardholder, and the card has not been properly unblocked.'));}
			elsif($rHash->{ResponseCode} eq '80') { $sts_err = (('Visa transactions: credit issuer unavailable. Private label and check acceptance: Invalid date'));}
			elsif($rHash->{ResponseCode} eq '81') { $sts_err = (('PIN cryptographic error found (error found by VIC security module during PIN decryption)'));}
			elsif($rHash->{ResponseCode} eq '82') { $sts_err = (('Negative CAM, dCVV, iCVV, or CVV results'));}
			elsif($rHash->{ResponseCode} eq '83') { $sts_err = (('Unable to verify PIN'));}
			elsif($rHash->{ResponseCode} eq '85') { $sts_err = (('No reason to decline a request for account number verification, address verification, CVV2 verification, or a credit voucher or merchandise return'));}
			elsif($rHash->{ResponseCode} eq '91') { $sts_err = (('Issuer unavailable or switch inoperative (STIP not applicable or available for this transaction)'));}
			elsif($rHash->{ResponseCode} eq '92') { $sts_err = (('Destination cannot be found for routing'));}
			elsif($rHash->{ResponseCode} eq '93') { $sts_err = (('Transaction cannot be completed, violation of law'));}
			elsif($rHash->{ResponseCode} eq '96') { $sts_err = (('System malfunction, System malfunction or certain field error conditions'));}
			elsif($rHash->{ResponseCode} eq 'B1') { $sts_err = (('Surcharge amount not permitted on Visa cards (U.S. acquirers only)'));}
			elsif($rHash->{ResponseCode} eq 'N0') { $sts_err = (('Force STIP'));}
			elsif($rHash->{ResponseCode} eq 'N3') { $sts_err = (('Cash service not available'));}
			elsif($rHash->{ResponseCode} eq 'N4') { $sts_err = (('Cashback request exceeds issuer limit'));}
			elsif($rHash->{ResponseCode} eq 'N7') { $sts_err = (('Decline for CVV2 failure'));}
			elsif($rHash->{ResponseCode} eq 'P2') { $sts_err = (('Invalid biller information'));}
			elsif($rHash->{ResponseCode} eq 'P5') { $sts_err = (('PIN Change/Unblock request declined'));}
			elsif($rHash->{ResponseCode} eq 'P6') { $sts_err = (('Unsafe PIN'));}
			elsif($rHash->{ResponseCode} eq 'Q1') { $sts_err = (('Card Authentication failed'));}
			elsif($rHash->{ResponseCode} eq 'XA') { $sts_err = (('Forward to issuer'));}
			elsif($rHash->{ResponseCode} eq 'XD') { $sts_err = (('Forward to issuer'));}
			elsif($rHash->{ResponseCode} eq 'Z3') { $sts_err = (('Unable to go online'));}
			#elsif($rHash->{ResponseCode} eq 'T8') { $sts_err = (('Test Card Failure'));}
			elsif($rHash->{ResponseDescription} ne '') { $sts_err = (("Billing Failed. Unknown Error ".$rHash->{ResponseDescription}));}
			else
			{
				$sts_err = (("Billing Failed. Unknown Error ".$rHash->{ResponseCode},"warn"));
			}
		}
		else
		{
			$billed=1;
		}
	}
	
	if($billed==0)
	{
		$statement = "insert into tUSER_PAYMENTS (tUSER_id,tEVENT_id,received,amount,dbdate_added,payment_desc) values ($tUSER_id,".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT").",1,$amount,now(),'$ptype')";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		
		$statement = "update tEVENT set deposit_received=1 where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT")." and deposit_received=0";
		$this->{logger}->info($statement);
		$sth = $this->{dbh}->prepare("$statement");
		$sth->execute;  
		if($sth->rows==0)
		{
			$statement = "update tEVENT set full_payment_received=1,tEVENT_STATUS_id=(select id from tEVENT_STATUS where value='Payment Confirmed') where id=".My_GenericFunctions->return_var_decode($xml->{action_content}->{event_id},"tEVENT")." and deposit_received=1";
			$this->{logger}->info($statement);
			$sth = $this->{dbh}->prepare("$statement");
			$sth->execute;  
		}		
	}	
	else
	{
    return(My_GenericFunctions->return_error($sts_err,"warn"));
	}

  $frxml .= "<\?xml version=\"1.0\"\?>";
  $frxml .= "\n<api>";
  $frxml .= "\n<status>true</status>";
  $frxml .= "$rxml\n";
  $frxml .= "\n</api>";
  return($frxml);    
}

#--------------------------------------------------------------------------------------------------
sub do_api_request_sts_cc($$)
{
	my %ua;
	my %cache;
  #my $this=shift;
  my ($api_url, $api_request) = @_;
  
  my %request;
  my $response;
  my $responseText;
  my $responseHash;
  my $logger=Log::Log4perl->get_logger();
  #$logger->info("do_api_request|$api_url|$api_request");
  
  if(!defined($request{"$api_url"}))
  {
    #$logger->info("do_api_request|new|$api_url|$api_request");
  
    $ua{"$api_url"} = new LWP::UserAgent;

     #$ua{"$api_url"}->proxy( ['http'], 'http://192.168.11.10:8080' );
     #$ua{"$api_url"}->proxy( ['https'], 'http://192.168.11.10:8080' );
     $ua{"$api_url"}->ssl_opts(verify_hostname => 0,SSL_verify_mode => 0x00);
        
    $cache{"$api_url"} = LWP::ConnCache->new;
    $ua{"$api_url"}->conn_cache( $cache{"$api_url"} );

    my $headers = HTTP::Headers->new('Content-Type' => 'application/xml; charset=utf-8');  
    $request{"$api_url"} = HTTP::Request->new('POST',"$api_url",$headers);
  }
  
  $request{"$api_url"}->authorization_basic('smart', '12851');  

  $request{"$api_url"}->content("$api_request");
  

  $logger->info("$api_url|".$api_request . "");

  $response = $ua{"$api_url"}->request($request{"$api_url"});

  $responseText = $response->content;

  $logger->info("".$responseText . "");
  
  if($response->is_success)
  {
    #$logger->info("".$responseText . "");

    eval
    {
     $responseHash = XMLin($responseText,SuppressEmpty => undef);
    };
   
    if($@) {$logger->info("".$@ . "");  $responseHash = ""; }  
  }
  
  return $responseHash;
}
1;
