package Cyber::User;
use strict;
use warnings;

use Data::Dumper;
use String::Random;
use POSIX 'strftime';
use Digest::MD5 qw(md5 md5_hex md5_base64);

use Cyber::Database;

#Constructor
sub new {
	my $class = shift;
	
	my $obj = {};
	
	my $obj_database = new Cyber::Database;
	$obj->{'obj_database'} = $obj_database;
	
	bless $obj, $class;
	
	return $obj;
}

#Fetch User Static Type
sub fetch_user_type {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $user_type = $class->{'obj_database'}->get({
		'table'  => 'sysconfig_user_type',
		'hash'   => 1,
		'select' => 'id, type',
	});
	
	if ( ref $user_type ne 'ARRAY' ) {
		$user_type = [$user_type];
	}
	
	my $user_type_hash = {};
	foreach my $user ( @$user_type ) {
		$user_type_hash->{$user->{'id'}} = $user->{'type'};
	}
	$class->{'user_type'} = $user_type_hash;
}

sub fetch_user_list {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};
	
	my $user_list = $class->{'obj_database'}->get({
		'table'  => 'user_master U, user_access A',
		'hash'   => 1,
		'select' => [
			'U.username as username',
			'U.useremail as useremail',
			'U.create_date as create_date',
			'A.add_property as add_property',
			'A.add_reservation as add_reservation',
		],
		'join' => [
			'U.id = A.user_id',
		],
		'where' => {
			'U.id' => $class->{'user_id'}
		},
	});

	if ( scalar @$user_list ) {
		$class->{'user_list'} = $user_list;
	}
	else {
		$class->{'user_list'} = [];
	}
}

#Authenticate User
sub validate_user {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};

	my $incoming_string = 'AVanti'.$cgi_params->{'password'}.'111';
	my $incoming_password = md5_hex($incoming_string);

	my $user_record = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, email as username, user_type, password',
		'where'  => {
			'email' => $cgi_params->{'email'},
			'password' => $incoming_password,
			'user_status' => 1,
		}
	});

	if ( scalar @$user_record ) {
		$class->{'tbl_user'} = $user_record->[0];

		# if ( $class->{'tbl_user'}->{'password'} !~ /^\s*$/ ) {
		# 	my $incoming_string = 'AVanti'.$cgi_params->{'password'}.'111';
		# 	my $incoming_password = md5_hex($incoming_string);
		# 	my $tbl_password = $class->{'tbl_user'}->{'password'};

		# 	if ( $tbl_password =~ /^$incoming_password$/i ) {
		# 		return 1;
		# 	}
		# }
		# return 0;
		return 1;
	}
	return 0;
}

#Authenticate User
sub validate_email {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	#Check user name
	my $useremail = lc($cgi_params->{'email'});

	my $user_email = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, user_type, email as username',
		'where'  => {
			'LOWER(email)' => $useremail
		}
	});

	if ( scalar @$user_email ) {
		$class->{'tbl_user'} = $user_email->[0];
		return 1;
	}
	return 0;
}

#Authenticate User
sub validate_username {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	#Check user name
	my $username = lc($cgi_params->{'username'});

	my $user_username = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, user_type, username',
		'where'  => {
			'LOWER(username)' => $username
		}
	});
	
	if ( scalar @$user_username ) {
		$class->{'tbl_user'} = $user_username->[0];
		return 1;
	}
	return 0;
}

#Set Session
sub set_session {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $user = $class->{'tbl_user'};
	if ( ref $user ne 'HASH' ) {
		$user = {$user};
	}
	
	my $ipaddr = $ENV{'REMOTE_ADDR'};
		
	unless ($ipaddr =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
		#die('Invalid IP address: '. $ipaddr);
	}
		
	#Check existing session
	unless ( $class->check_session() ) {
		while ( $class->random_key() ) {
			unless ( $class->{'obj_database'}->get({
				'table'  => 'session_master',
				'select' => 'count(*)',
				'where'  => {
					'session_id' => $class->{'random_key'},
				}})->[0]->[0]
			) {
				last;
			}
		}

		my $request_uri = $ENV{'REQUEST_URI'};
		
		eval {
			$class->{'obj_database'}->set(
				'table' => 'session_master',
				'insert' => {
					'session_id'   => $class->{'random_key'},
					'user_master_id' => $user->{'user_id'},
					'user_type' => $user->{'user_type'} || 1,
					'ipaddress'    => $ipaddr,
					'request_uri'  => $request_uri,
					'is_active'    => 1,
					'create_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
					'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				},
			);
		};
		if ( $@ ) {
			print $@;
		}
	}
	else {
		$class->{'obj_database'}->set(
			'table' => 'session_master',
			'update' => {
				'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where'  => {
				'session_id' => $class->{'random_key'},
				'ipaddress'  => $ipaddr,
				'is_active'  => '1'
			}
		);	
	}	
}

#Check Session
sub check_session {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $user = $class->{'tbl_user'};
	if ( ref $user ne 'HASH' ) {
		$user = {$user};
	}
	
	my $ipaddr = $ENV{'REMOTE_ADDR'};
	
	my $existing_session = $class->{'obj_database'}->get({
		'table'  => 'session_master',
		'hash'   => 1,
		'select' => 'session_id',
		'where'  => {
			'user_master_id' => $user->{'user_id'},
			'user_type' => $user->{'user_type'},
			'ipaddress'    => $ipaddr,
			'is_active'    => '1'
		}});
	
	if ( scalar @$existing_session ) {
		$class->{'random_key'} = $existing_session->[0]->{'session_id'};
		return 1;
	}
	return 0;
}

#Fetch User Static Type
sub validate_session {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $ipaddr = $ENV{'REMOTE_ADDR'};
	
	my $session_data = $class->{'obj_database'}->get({
		'table'  => 'session_master',
		'hash'   => 1,
		'select' => 'user_master_id as user_id, user_type, TIMESTAMPDIFF(MINUTE, modify_date, NOW()) as minutes',
		'where'  => {
			'session_id' => $cgi_params->{'session_id'},
			# 'ipaddress'  => $ipaddr,
			'is_active'  => 1
		}});
	
	if ( scalar @$session_data ) {
		$session_data    = $session_data->[0];
		my $user_id      = $session_data->{'user_id'};
		my $user_type_id = $session_data->{'user_type'};
		
		$class->{'session_data'} = $session_data;
		
		#Check Session Time
		my $session_time_diff = $session_data->{'minutes'};
		if ( $session_time_diff < 60 ) {
			$class->{'obj_database'}->set(
				'table' => 'session_master',
				'update' => {
					'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				},
				'where'  => {
					'session_id' => $cgi_params->{'session_id'},
					# 'ipaddress'  => $ipaddr,
					'is_active'  => 1
				}
			);
			
			$class->{'tbl_session'} = $session_data;
			return 1;
		}
		else {
			$class->{'obj_database'}->set(
				'table' => 'session_master',
				'update' => {
					'is_active'  => 0,
				},
				'where'  => {
					'session_id' => $cgi_params->{'session_id'},
					# 'ipaddress'  => $ipaddr,
					'is_active'  => 1
				}
			);
			
			return 0;
		}
	}
	return 0;
}

#Fetch User Static Type
sub validate_random_number {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $session_data = $class->{'obj_database'}->get({
		'table'  => 'forgot_password_random_master',
		'hash'   => 1,
		'select' => 'id, TIMESTAMPDIFF(MINUTE, create_date, NOW()) as minutes',
		'where'  => {
			'random_key' => $cgi_params->{'random_key'},
			'is_active'  => 'Y'
		}});
	
	if ( scalar @$session_data ) {
		$session_data    = $session_data->[0];
		
		#Check Session Time
		my $session_time_diff = $session_data->{'minutes'};
		if ( $session_time_diff < 30 ) {
			return 1;
		}
		else {
			return 0;
		}
	}
	return 0;
}

#Delete Session
sub delete_session {
	my $class = shift;
	my $cgi_params = $class->{'cgi_params'};
	
	my $ipaddr = $ENV{'REMOTE_ADDR'};
	
	$class->{'obj_database'}->set(
		'table' => 'session_master',
		'update' => {
			'is_active' => 0
		},
		'where'  => {
			'session_id' => $cgi_params->{'session_id'},
			# 'ipaddress'  => $ipaddr
		}
	);
	return 1;
	#my $sid = $cgi_params->{'cgi_object'}->cookie('CGISESSID') || $cgi_params->{'cgi_object'}->param('CGISESSID') || undef;
	#
	#my $session = load CGI::Session(undef, $sid, { Directory=>"/tmp" });
	#
	#$session->delete();
	#
	#undef($session);
}

#Create Random Number
sub random_key {
	my $class = shift;
	
	my $string_rand = new String::Random();
	
	my $random_key = $string_rand->randregex('[0-9]{12}');
	$random_key .= time();
	
	$random_key =~ s/^0+//;
	# ::log($random_key);
	$class->{'random_key'} = $random_key;
}

#Fetch Template List
#sub find_template {
#	my $class = shift;
#	
#	my $template_list =::table('sysconfig_session')->get(
#		'hash'   => 1,
#		'select' => 'user_type_id, template_name, layout_path',
#		'where'  => {
#			'user_type_id' => $class->{'user'}->{'user_type_id'},
#		}
#	);
#
#	if ( ref $template_list ne 'ARRAY' ) {
#		$template_list = [$template_list];
#	}
#	
#	my $template_type_hash = {};
#	foreach my $template ( @$template_list ) {
#		$template_type_hash->{$template->{'user_type_id'}} = {
#			'template_name' => $template->{'template_name'},
#			'layout_path'   => $template->{'layout_path'}
#		};
#	}
#	
#	$class->{'template_list'} = $template_type_hash;
#}
#
##Find Redirect Page
#sub find_redirect_page {
#	my $class = shift;
#	
#	my $template_id     = $class->{'template_id'};
#	my $page_type_id    = $class->{'page_type_id'};
#	my $page_section_id = $class->{'page_section_id'};
#	
#	my $redirect_page = $class->{'obj_database'}->get({
#		'table'  => 'sysconf_page',
#		'hash'   => 1,
#		'select' => 'name, display_name, link',
#		'where'  => {
#			'template_id'     => $template_id,
#			'page_type_id'    => $page_type_id,
#			'page_section_id' => $page_section_id
#		}}
#	)->[0];
#	
#	$class->{'redirect_page'} = $redirect_page->{'link'};
#}
#
##Find Redirect Page
#sub find_pages {
#	my $class = shift;
#	
#	my $template_id     = $class->{'template_id'};
#	my $page_type_id    = $class->{'page_type_id'};
#	
#	my $pages = $class->{'obj_database'}->get({
#		'table'  => 'sysconf_page p, sysconf_section s',
#		'hash'   => 1,
#		'select' => [
#			'p.name as name',
#			'p.display_name as display_name',
#			'p.link as link',
#			'p.page_section_id as page_section_id',
#			'p.priority as priority',
#			's.page_section as page_section',
#			's.location as location',
#		],
#		'join' => [
#			'p.page_section_id = s.id',
#			'p.template_id     = s.template_id',
#		],
#		'where'  => {
#			'p.template_id'     => $template_id,
#			'p.page_type_id'    => $page_type_id
#		},
#		'order' => 'p.priority'}
#	);
#	
#	if ( ref $pages ne 'ARRAY' ) {
#		$pages = [$pages];
#	}
#	
#	my $page_group = {};
#	foreach my $page ( @$pages ) {
#		if ( exists $page_group->{$page->{'location'}}->{$page->{'page_section'}} ) {
#			my $temp_group = $page_group->{$page->{'location'}}->{$page->{'page_section'}};
#			push @$temp_group, {
#				'link'         => $page->{'link'},
#				'display_name' => $page->{'display_name'},
#			};
#			$page_group->{$page->{'location'}}->{$page->{'page_section'}} = $temp_group;
#		}
#		else {
#			$page_group->{$page->{'location'}}->{$page->{'page_section'}} = [{
#				'link'         => $page->{'link'},
#				'display_name' => $page->{'display_name'},
#			}];
#		}
#	}
#	
#	$class->{'pages'} = $page_group;
#}
#
sub create_user {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	# if ( !$class->validate_email() ) {
		eval {
			my $pass = $cgi_params->{'password'};
			my $string = 'AVanti'.$pass.'111';
			my $password = md5_hex($string);

			$class->{'obj_database'}->set(
				'table' => 'user_master',
				'insert' => {
					'company_name'    => $cgi_params->{'company_name'},
					'company_address' => $cgi_params->{'company_address'},
					'vat_no'          => $cgi_params->{'vat_no'},
					'association_no'  => $cgi_params->{'assoc_no'},
					'group_name'      => $cgi_params->{'group'},
					'contact_name'    => $cgi_params->{'contact_name'},
					'position'        => $cgi_params->{'position'},
					'tel'             => $cgi_params->{'telephone'},
					'email'           => $cgi_params->{'email'},
					'password'        => $password,
					'last_login'      => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
					'login_count'     => 0,
					'user_type'       => 2,
					'user_status'     => 2,
					'activation_key'  => $class->{'activation_key'},
					'create_date'     => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
					'modify_date'     => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				},
			);

			$class->{'created_user_id'} = $class->{'obj_database'}->last_insert_id();
		};
		if ( $@ ) {
			$class->{'is_error'} = 1;
			$class->{'error_message'} = 'system issue please contact to support';
			return 0;
		}
	# }
	# else {
	# 	$class->{'is_error'} = 1;
	# 	$class->{'error_message'} = 'Email Already exists';
	# 	return 0;
	# }
	return 1;
}

sub check_user_email {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $user_record = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, email as username, user_type, password',
		'where'  => {
			'email' => $cgi_params->{'email'},
		}
	});

	if ( scalar @$user_record ) {
		$class->{'tbl_user'} = $user_record->[0];
		return 1;
	}
	else {
		return 0;
	}
}

sub check_new_user {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $user_record = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, email as username, user_type, password',
		'where'  => {
			'id' => $cgi_params->{'user_id'},
			'activation_key' => $cgi_params->{'activation_key'},
			'user_status' => 2,
		}
	});

	if ( scalar @$user_record ) {
		$class->{'tbl_user'} = $user_record->[0];
		return 1;
	}
	else {
		return 0;
	}
}

sub activate_new_user {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_master',
			'update' => {
				'user_status' => 1,
				'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	return 1;
}

sub send_agent_email {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $credential = $::config{'credential'};

    my $smtpserver   = $credential->{'EMAIL_HOST'};
	my $smtpport     = $credential->{'EMAIL_PORT'};
	my $smtpuser     = $credential->{'EMAIL_USER'};
	my $smtppassword = $credential->{'EMAIL_PASS'};

	use Email::Sender::Simple qw(sendmail);
	use Email::Sender::Transport::SMTPS ();
	use Email::Simple ();
	use Email::Simple::Creator ();
	use Email::MIME;

	my $transport = Email::Sender::Transport::SMTPS->new({
	 	host => $smtpserver,
	 	port => $smtpport,
	  	# ssl => "starttls",
	  	sasl_username => $smtpuser,
	  	sasl_password => $smtppassword,
	});
	
	my $from = $credential->{'EMAIL_FROM'};
	my $to = $cgi_params->{'email'};
	my $subject = "Agent Registration Notification";
	my $body = "<html><body>
		<p>Dear Agent</p>
		<p>Thank you for registering with Avanti Florida Villas</p>
		<p>Avanti Florida Villas Admin Team will activate your account soon.</p>
		<p>A confirmation letter will follow and an information pack will be posted to you.</p>
		<p>Thank You</p>
	</body></html>";

	my @parts = (
	    Email::MIME->create(
	        attributes => {
	            content_type => "text/html",
	            disposition  => "attachment",
	            charset      => "UTF-8",
	            encoding     => "base64",
	        },
	        body_str => $body,
	    ),
	);

	my $email = Email::MIME->create(
	    header_str => [
	        From => $from,
	        To => $to,
	        Subject => $subject,
	    ],
	    parts      => [ @parts ],
	);

	$email->content_type_set( 'text/html' );
	eval {
		sendmail($email, { transport => $transport });
	};
	if ( $@ ) {
		# print $@;
	}
}

sub send_agent_confirmation_email {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $credential = $::config{'credential'};

    my $smtpserver   = $credential->{'EMAIL_HOST'};
	my $smtpport     = $credential->{'EMAIL_PORT'};
	my $smtpuser     = $credential->{'EMAIL_USER'};
	my $smtppassword = $credential->{'EMAIL_PASS'};

	use Email::Sender::Simple qw(sendmail);
	use Email::Sender::Transport::SMTPS ();
	use Email::Simple ();
	use Email::Simple::Creator ();
	use Email::MIME;

	my $transport = Email::Sender::Transport::SMTPS->new({
	 	host => $smtpserver,
	 	port => $smtpport,
	  	# ssl => "starttls",
	  	sasl_username => $smtpuser,
	  	sasl_password => $smtppassword,
	});
	
	my $user_date = $class->{'tbl_user'};

	my $from = $credential->{'EMAIL_FROM'};
	my $to = $user_date->{'username'};
	my $subject = "Agent Registration Confirmation";
	my $body = "<html><body>
		<p>Dear Agent</p>
		<p>Thank you for registering with Avanti Florida Villas</p>
		<p>Your account is activated by Avanti Florida Villas.</p>
		<p>You can access it using your username and password.</p>
		<p>Thank You</p>
	</body></html>";

	my @parts = (
	    Email::MIME->create(
	        attributes => {
	            content_type => "text/html",
	            disposition  => "attachment",
	            charset      => "UTF-8",
	            encoding     => "base64",
	        },
	        body_str => $body,
	    ),
	);

	my $email = Email::MIME->create(
	    header_str => [
	        From => $from,
	        To => $to,
	        Subject => $subject,
	    ],
	    parts      => [ @parts ],
	);

	$email->content_type_set( 'text/html' );
	eval {
		sendmail($email, { transport => $transport });
	};
	if ( $@ ) {
		# print $@;
	}
}

sub send_agent_email_to_admin {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $credential = $::config{'credential'};

    my $smtpserver   = $credential->{'EMAIL_HOST'};
	my $smtpport     = $credential->{'EMAIL_PORT'};
	my $smtpuser     = $credential->{'EMAIL_USER'};
	my $smtppassword = $credential->{'EMAIL_PASS'};

	use Email::Sender::Simple qw(sendmail);
	use Email::Sender::Transport::SMTPS ();
	use Email::Simple ();
	use Email::Simple::Creator ();
	use Email::MIME;

	my $transport = Email::Sender::Transport::SMTPS->new({
	 	host => $smtpserver,
	 	port => $smtpport,
	  	# ssl => "starttls",
	  	sasl_username => $smtpuser,
	  	sasl_password => $smtppassword,
	});
	
	my $activation_url = "$::config{'root_url'}->{'url'}/Scripts/agent_activate.pl?user_id=$class->{'created_user_id'}&activation_key=$class->{'activation_key'}";

	my $from = $credential->{'EMAIL_FROM'};
	my $to = 'contact@avantifloridavillas.com';
	# my $to = 'shyarakishor@gmail.com';
	my $subject = "New Agent Registered";
	my $body = "<html><body>
		<p><b>Company Name: </b>$cgi_params->{'company_name'}</p>
		<p><b>Company Address: </b>$cgi_params->{'company_address'}</p>
		<p><b>Vat No: </b>$cgi_params->{'vat_no'}</p>
		<p><b>Association No: </b>$cgi_params->{'assoc_no'}</p>
		<p><b>Group Name: </b>$cgi_params->{'group'}</p>
		<p><b>Contact Name: </b>$cgi_params->{'contact_name'}</p>
		<p><b>Position: </b>$cgi_params->{'position'}</p>
		<p><b>Telephone: </b>$cgi_params->{'telephone'}</p>
		<p><b>Email: </b>$cgi_params->{'email'}</p>
		<p>Activate account please <a href='".$activation_url."' >click here</a></p>
		<p>Thank You</p>
	</body></html>";

	my @parts = (
	    Email::MIME->create(
	        attributes => {
	            content_type => "text/html",
	            disposition  => "attachment",
	            charset      => "UTF-8",
	            encoding     => "base64",
	        },
	        body_str => $body,
	    ),
	);

	my $email = Email::MIME->create(
	    header_str => [
	        From => $from,
	        To => $to,
	        Subject => $subject,
	    ],
	    parts      => [ @parts ],
	);

	$email->content_type_set( 'text/html' );
	eval {
		sendmail($email, { transport => $transport });
	};
	if ( $@ ) {
		# print $@;
	}
}

sub fetch_module_list {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $module_list = $class->{'obj_database'}->get({
		'table'  => 'system_module_master',
		'hash'   => 1,
		'where' => {
			'level' => $class->{'module_level'}
		},
	});
	
	if ( scalar @$module_list ) {
		$class->{'module_list'} = $module_list;
	}
	else {
		$class->{'module_list'} = [];
	}
}

sub fetch_admin_user_list {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $user_list = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'where' => {
			'user_type' => $class->{'user_type'}
		},
	});
	
	if ( scalar @$user_list ) {
		$class->{'user_list'} = $user_list;
	}
	else {
		$class->{'user_list'} = [];
	}

}

sub fetch_property_user_list {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $property_id = $cgi_params->{'property_id'};
	
	my $user_list = $class->{'obj_database'}->get({
		'table'  => 'user_master U, user_access A',
		'hash'   => 1,
		'select' => [
			'U.id as user_id',
			'U.username as username',
			'U.email as email',
			'U.create_date as create_date'
		],
		'join' => [
			'U.id = A.user_id',
		],
		'where' => {
			'A.property_id' => $property_id,
			'U.is_active'   => 'Y'
		},
	});
	
	if ( scalar @$user_list ) {
		$class->{'property_user_list'} = $user_list;
	}
	else {
		$class->{'property_user_list'} = [];
	}
}

sub fetch_property_user_detail_by_id {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $property_id = $cgi_params->{'property_id'};
	my $user_id     = $cgi_params->{'user_id'};
	
	my $user_detail = $class->{'obj_database'}->get({
		'table'  => 'user_master U, user_access A, user_role_master R',
		'hash'   => 1,
		'select' => [
			'U.id as user_id',
			'U.password as password',
			'U.username as username',
			'U.first_name',
			'U.last_name',
			'U.mobile',
			'U.email as email',
			'U.create_date as create_date',
			'R.allow_module_list'
		],
		'join' => [
			'U.id = A.user_id',
			'A.user_id = R.user_id'
		],
		'where' => {
			'A.property_id' => $property_id,
			'A.id'          => $user_id
		},
	});
	
	if ( scalar @$user_detail ) {
		$class->{'property_user_detail'} = $user_detail->[0];
	}
	else {
		$class->{'property_user_detail'} = {};
	}
}

sub fetch_admin_user_detail_by_id {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $user_id     = $cgi_params->{'user_id'};
	
	my $user_detail = $class->{'obj_database'}->get({
		'table'  => 'user_master U, user_access A, user_role_master R',
		'hash'   => 1,
		'select' => [
			'U.id as user_id',
			'U.password as password',
			'U.username as username',
			'U.first_name',
			'U.last_name',
			'U.mobile',
			'U.email as email',
			'U.create_date as create_date',
			'R.allow_module_list'
		],
		'join' => [
			'U.id = A.user_id',
			'A.user_id = R.user_id'
		],
		'where' => {
			'A.id'          => $user_id
		},
	});
	
	if ( scalar @$user_detail ) {
		$class->{'admin_user_detail'} = $user_detail->[0];
	}
	else {
		$class->{'admin_user_detail'} = {};
	}
}

sub fetch_user_role {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $user_id = $class->{'session_data'}->{'user_id'};
	
	my $user_role_access = $class->{'obj_database'}->get({
		'table'  => 'user_role_master',
		'hash'   => 1,
		'select' => 'allow_module_list',
		'where' => {
			'user_id' => $user_id
		},
	});

	if ( scalar @$user_role_access ) {
		$class->{'user_roles'} = $user_role_access->[0]->{'allow_module_list'};
	}
	else {
		#If nothing set that means user allowed all the things
		if ( $class->{'session_data'}->{'user_type'} == 1 ) {
			$class->{'user_roles'} = '1,2,3,4,5,6,7,8,9,10,11,12,25,26,29'
		}
		elsif ( $class->{'session_data'}->{'user_type'} == 2 ) {
			$class->{'user_roles'} = '13,14,15,16,17,18,19,20,21,22,23,24,30,31,32,33,34,35,36,37,38,39,40,41'
		}
		else {
			$class->{'user_roles'} = undef;
		}

		#Set user role for all
		eval {
			$class->{'obj_database'}->set(
				'table' => 'user_role_master',
				'insert' => {
					'user_id'     => $user_id,
					'allow_module_list' => $class->{'user_roles'},
					'create_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
					'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				},
			);
		};
		# if ( $@ ) {
		# 	$class->{'is_error'} = 1;
		# 	$class->{'error_message'} = 'system issue please contact to support';
		# 	return 0;
		# }
	}
}


sub add_user_role {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	$cgi_params->{'module_list'} =~ s/,$//;

	if ( $cgi_params->{'module_list'} =~ /^41$|^.*,41$|^.*,41,.*|^41,.*$/ ) {
		##Fetch permission list for property user
		my $module_list = $class->{'obj_database'}->get({
			'table'  => 'system_module_master',
			'hash'   => 1,
			'where' => {
				'level' => '2'
			},
		});
		
		if ( scalar @$module_list ) {
			foreach my $module ( @$module_list ) {
				my $module_master_id = $module->{'module_master_id'};
				$cgi_params->{'module_list'} .= ",";
				$cgi_params->{'module_list'} .= $module_master_id;
			}
		}
	}

	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_role_master',
			'insert' => {
				'user_id'     => $class->{'created_user_id'},
				'allow_module_list' => $cgi_params->{'module_list'},
				'create_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support';
		return 0;
	}
	return 1;
}

sub edit_property_user {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};
	
	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_master',
			'update' => {
				'username'     => $cgi_params->{'username'},
				'password'     => $cgi_params->{'password'},
				'email'        => $cgi_params->{'useremail'},
				'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_role_master',
			'update' => {
				'allow_module_list' => $cgi_params->{'module_list'},
				'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'user_id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	return 1;
}

sub edit_admin_user {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};
	
	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_master',
			'update' => {
				'password'   => $cgi_params->{'password'},
				'first_name' => $cgi_params->{'first_name'},
				'last_name'  => $cgi_params->{'last_name'},
				'mobile'     => $cgi_params->{'mobile'},
				'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	$cgi_params->{'module_list'} =~ s/,$//;

	if ( $cgi_params->{'module_list'} =~ /^41$|^.*,41$|^.*,41,.*|^41,.*$/ ) {
		##Fetch permission list for property user
		my $module_list = $class->{'obj_database'}->get({
			'table'  => 'system_module_master',
			'hash'   => 1,
			'where' => {
				'level' => '2'
			},
		});
		
		if ( scalar @$module_list ) {
			foreach my $module ( @$module_list ) {
				my $module_master_id = $module->{'module_master_id'};
				if ( $cgi_params->{'module_list'} !~ /^$module_master_id$|^.*,$module_master_id$|^.*,$module_master_id,.*|^$module_master_id,.*$/ ) {
					$cgi_params->{'module_list'} .= ",";
					$cgi_params->{'module_list'} .= $module_master_id;
				}
			}
		}
	}

	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_role_master',
			'update' => {
				'allow_module_list' => $cgi_params->{'module_list'},
				'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'user_id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	return 1;
}

sub delete_property_user {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};
	
	eval {
		$class->{'obj_database'}->set(
			'table' => 'user_master',
			'update' => {
				'user_status' => 0,
				'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'id' => $cgi_params->{'user_id'}
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support'.$@;
		return 0;
	}

	return 1;
}

sub fetch_property_name_by_id {
	my $class = shift;
	
	my $cgi_params = $class->{'cgi_params'};

	my $property_id = $cgi_params->{'property_id'};

	my $property_detail = {};
	if ( $cgi_params->{'property_id'} !~ /^\s*$/ ) {
		$property_detail = $class->{'obj_database'}->get({
			'table'  => 'property_profile_master',
			'select' => 'property_id, name, label, city, zipcode, email, mobile',
			'hash'   => 1,
			'where'  => {
				'property_id' => $property_id
			}
		})->[0];
	}
	
	if ( scalar keys %$property_detail ) {
		$class->{'property_detail'} = $property_detail;
	}
	else {
		$class->{'property_detail'} = {};
	}
	return 1;
}

sub send_forgot_password_email {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $credential = $::config{'credential'};

    my $smtpserver   = $credential->{'EMAIL_HOST'};
	my $smtpport     = $credential->{'EMAIL_PORT'};
	my $smtpuser     = $credential->{'EMAIL_USER'};
	my $smtppassword = $credential->{'EMAIL_PASS'};

	use Email::Sender::Simple qw(sendmail);
	use Email::Sender::Transport::SMTPS ();
	use Email::Simple ();
	use Email::Simple::Creator ();
	use Email::MIME;

	my $transport = Email::Sender::Transport::SMTPS->new({
	 	host => $smtpserver,
	 	port => $smtpport,
	  	# ssl => "starttls",
	  	sasl_username => $smtpuser,
	  	sasl_password => $smtppassword,
	});
	
	##generate random number and link
	$class->random_key();

	##store forgot password random number in table
	my $link = undef;
	eval {
		$class->{'obj_database'}->set(
			'table' => 'forgot_password_random_master',
			'insert' => {
				'random_key'  => $class->{'random_key'},
				'email'       => $cgi_params->{'email'},
				'is_active'   => 'Y',
				'create_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				'modify_date' => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
		);

		$link = "$::config{'root_url'}->{'url'}/Scripts/forgot_password.pl?random_key=$class->{'random_key'}&email=$cgi_params->{'email'}";
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support';
		return 0;
	}

	my $from = $credential->{'EMAIL_FROM'};
	my $to = $cgi_params->{'email'};
	my $subject = "Forgot password";
	my $body = "<html><body>
		<p>Thank you for contact us about recover your password.</p>
		<p>Please use below link to reset your password. Make sure below link will expired within 30 minutes.</p>
		<p>$link</p>
		<p>Thank You</p>
	</body></html>";

	my @parts = (
	    Email::MIME->create(
	        attributes => {
	            content_type => "text/html",
	            disposition  => "attachment",
	            charset      => "UTF-8",
	            encoding     => "base64",
	        },
	        body_str => $body,
	    ),
	);

	my $email = Email::MIME->create(
	    header_str => [
	        From => $from,
	        To => $to,
	        Subject => $subject,
	    ],
	    parts      => [ @parts ],
	);

	$email->content_type_set( 'text/html' );
	eval {
		sendmail($email, { transport => $transport });
	};
	if ( $@ ) {
		print $@;
	}
}

sub reset_password {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $email = lc($cgi_params->{'email'});
	my $random_key = $cgi_params->{'random_key'};
	my $password = $cgi_params->{'password'};

	##check input email is correct
	my $user_email = $class->{'obj_database'}->get({
		'table'  => 'forgot_password_random_master',
		'hash'   => 1,
		'select' => '*',
		'where'  => {
			'LOWER(email)' => $email,
			'random_key'   => $random_key
		}
	});
	
	if ( scalar @$user_email ) {
		##reset password
		my $string = 'AVanti'.$password.'111';
		my $new_password = md5_hex($string);

		eval {
			$class->{'obj_database'}->set(
				'table' => 'user_master',
				'update' => {
					'password'  => $new_password,
				},
				'where'  => {
					'email' => $cgi_params->{'email'},
					'user_status'  => '1'
				}
			);
		};
		if ( $@ ) {
			return 0;
		}

		return 1;
	}
	return 0;
}

sub fetch_user_detail {
	my $class = shift;
	
	my $user_id = $class->{'user_id'};

	my $user_detail = {};
	if ( $user_id !~ /^\s*$/ ) {
		$user_detail = $class->{'obj_database'}->get({
			'table'  => 'user_master',
			'select' => '*',
			'hash'   => 1,
			'where'  => {
				'id' => $user_id,
				'user_status' => 1
			}
		})->[0];
	}
	
	if ( scalar keys %$user_detail ) {
		$class->{'user_detail'} = $user_detail;
	}
	else {
		$class->{'user_detail'} = {};
	}
	return 1; 
}

sub save_account_detail {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	eval {

		$class->{'obj_database'}->set(
			'table' => 'user_master',
			'update' => {
				'company_name'    => $cgi_params->{'company_name'},
				'company_address' => $cgi_params->{'company_address'},
				'vat_no'          => $cgi_params->{'vat_no'},
				'association_no'  => $cgi_params->{'assoc_no'},
				'group_name'      => $cgi_params->{'group'},
				'contact_name'    => $cgi_params->{'contact_name'},
				'position'        => $cgi_params->{'position'},
				'tel'             => $cgi_params->{'telephone'},
				'modify_date'     => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
			'where' => {
				'id' => $cgi_params->{'user_id'},
				'user_status' => 1
			}
		);
	};
	if ( $@ ) {
		$class->{'is_error'} = 1;
		$class->{'error_message'} = 'system issue please contact to support';
		return 0;
	}

	return 1;
}

sub save_password_data {
	my $class = shift;

	my $cgi_params = $class->{'cgi_params'};

	my $incoming_string = 'AVanti'.$cgi_params->{'old_password'}.'111';
	my $incoming_password = md5_hex($incoming_string);

	my $user_record = $class->{'obj_database'}->get({
		'table'  => 'user_master',
		'hash'   => 1,
		'select' => 'id as user_id, email as username, user_type, password',
		'where'  => {
			'email' => $cgi_params->{'email'},
			'password' => $incoming_password,
			'id' => $cgi_params->{'user_id'},
			'user_status' => 1,
		}
	})->[0];

	if ( defined $user_record && ref $user_record eq 'HASH' && scalar keys %$user_record ) {
		$incoming_string = 'AVanti'.$cgi_params->{'new_password'}.'111';
		$incoming_password = md5_hex($incoming_string);

		eval {

			$class->{'obj_database'}->set(
				'table' => 'user_master',
				'update' => {
					'password'        => $incoming_password,
					'modify_date'     => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				},
				'where' => {
					'email' => $cgi_params->{'email'},
					'id' => $cgi_params->{'user_id'},
					'user_status' => 1
				}
			);
		};
		if ( $@ ) {
			$class->{'is_error'} = 1;
			$class->{'error_message'} = 'system issue please contact to support';
			return 0;
		}

		return 1;
	}

	return 1;
}

1;
