package Cyber::Contact;
use strict;
use warnings;

use Data::Dumper;
use String::Random;
use POSIX 'strftime';
use Encode;
use JSON;
use LWP::UserAgent;
use IO::Compress::Gzip qw(gzip);
use IO::Uncompress::Gunzip qw( gunzip );
use Cyber::Database;
use Date::Simple qw(date);
no warnings "uninitialized";

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

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

	eval {

		$class->{'obj_database'}->set(
			'table' => 'contact_info_master',
			'insert' => {
				'name' => $cgi_params->{'name'},
				'telephone' => $cgi_params->{'tel'},
				'email' => $cgi_params->{'email'},
				'enquiry' => $cgi_params->{'message'},
				'create_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
				'modify_date'  => strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
			},
		);
	};
	if ( $@ ) {
		return 1;
	}

	return 1;
}

sub send_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 = 'bill@avantigroup.co.uk';
	my $subject = "Florida Villas Contact From:".$cgi_params->{'name'};
	my $body = "<html><body>
		<p><b>Name: </b>$cgi_params->{'name'}</p>
		<p><b>EmailL </b>$cgi_params->{'email'}</p>
		<p><b>Telephone: </b>$cgi_params->{'tel'}</p>
		<p><b>Message: </b>$cgi_params->{'message'}</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 ],
	);
	# my $email = Email::Simple->create(
	# 	header => [
	# 		To      => $to,
	# 		From    => $from,
	# 		Subject => $subject,
	# 	],
	# 	body => 'Testing',
	# );
	# $email->header_set( 'content-type' => 'text/html' );
	$email->content_type_set( 'text/html' );
	eval {
		sendmail($email, { transport => $transport });
	};
	if ( $@ ) {
		print $@;
	}
}

1;
