#!%PERL% -w

use strict;
use utf8;
use POSIX qw(locale_h);
use HTML::Template;
use locale;
use Locale::gettext;
use CGI;
use CGI::Session;
use Encode;

use lib '%VHFFS_LIB_DIR%';
use Vhffs::User;
use Vhffs::Group;
use Vhffs::Main;
use Vhffs::Functions;
use Vhffs::Panel::Main;
use Vhffs::Panel::Menu;
use Vhffs::Panel::Group;

my $panel = new Vhffs::Panel::Main();
exit 0 unless $panel;
my $session = $panel->get_session;
exit 0 unless $session;

my $vhffs = $panel->{'vhffs'};
my $templatedir = $panel->{templatedir};
my $user = $panel->{'user'};
my $cgi = $panel->{cgi};
my $group = Vhffs::Group::get_by_groupname( $vhffs , $cgi->param('group') );

unless( defined $group && $user->can_modify( $group ) ) {
	my $template = new HTML::Template( filename => $templatedir.'/panel/misc/simplemsg.tmpl' );
	$template->param( MESSAGE => gettext( 'You\'re not allowed to do this (ACL rights)' ) );

	$panel->build( $template );
	$panel->display;
}
else  {
	my $submitted = defined($cgi->param('dns_submit'));
	my $domain_name = '';
	my $description = '';

	if( $submitted ) {
		$domain_name = $cgi->param('DOMAIN_NAME');
		$description = Encode::decode_utf8( $cgi->param('DESCRIPTION') );

		unless( defined $domain_name  &&  defined $description ) {
			$panel->add_error( gettext('CGI Error !') );
		} elsif( !Vhffs::Functions::check_domain_name($domain_name) ) {
			$panel->add_error( gettext('Invalid domain name') );
		} elsif( $description =~ /^\s*$/ ) {
			 $panel->add_error( gettext('You must enter a description') );
		} else {
			my $dns = Vhffs::Panel::DNS::create_dns( $vhffs, $domain_name, $description, $user, $group );
			if( defined $dns ) {
				my $url = '/group/view.pl?group='.$group->get_groupname.'&msg='.gettext('The DNS object was successfully created !');
				$panel->redirect($url);
			} else {
				$panel->add_error( gettext('An error occured while creating the object. The domain is not correct or aleady exists in Vhffs database') );
			}
		}
	}

	if( !$submitted || $panel->has_errors() ) {
		my $template = new HTML::Template( filename => $templatedir.'/panel/dns/create.tmpl' );

		$panel->set_title( gettext('Create a DNS') );

		$template->param( DOMAIN_NAME => gettext('Domain Name') );
		$template->param( DOMAIN_NAME_VALUE => $domain_name );

		$template->param( INFOS_DNS => gettext('Be careful ! You must give the reason why you want to host this domain on our servers.') );
		$template->param( DNS_SERVER => gettext('DNS servers:') );
		$template->param( GROUP_NAME => gettext('Group owning this DNS') );
    
		$template->param( GROUP => $group->get_groupname );
		$template->param( SEND => gettext('Send') );
		$template->param( DESCRIPTION => gettext('Description') );
		$template->param( DESCRIPTION_VALUE => $description );

		$panel->build( $template );
		$panel->display;
	}
}
