#!/usr/bin/perl
BEGIN { use lib $ENV{HTTP_PERL5LIB} };

###
### Hauptmenu
###
### $Id: main.pl,v 1.7 2007/06/27 20:14:51 stefan Exp $
###

package main;
use strict;
use app_config;
use CGI qw(:standard *table);
use Data::Dumper;
use Parts::active_customer;
use Parts::last_modified_customer;
use Parts::customer_search_form;
use html;
use layout;

#print "content-type: text/plain\n\n";
my ( $session, $cgi, $logger ) = &app_config::get_app_ctx();

# Berechtigungen checken
my $auth = auth->new;
my $act_user;
my $act_cust;

$logger->debuginfo( 'User-ID:'.$auth->get_user_id  );

# ggf. Web-User als Active User laden
if ( $auth->is_web_user() ) {
	$logger->debuginfo( "is_webuser");
	
	$act_user = Persist::User->retrieve( $auth->get_user_id );
	my @customers = $act_user->customers;
	my $count     = scalar(@customers);
	die "More than one Customer Records for web_user" if $count > 1;

	unless (@customers) {

		# wenn noch keine Stammdaten erfasst sind, weiterleiten
		my $cust = Persist::Customer->create(
			{
				name      => $act_user->name,
				firstname => $act_user->firstname
			}
		);

		print CGI->redirect(
			app_config::get_url(
				'/process/customer_edit/edit.pl?id=' . $cust->id
			)
		);
		exit;
	}

	my $act_cust = Parts::active_customer->new( $customers[0]->id );

}

# HTTP-Header mit Cookie senden
print $cgi->header(&app_config::get_http_header);

# Layout-Objekt erzeugen
my $layout = layout->new("Hauptmenue");
print $layout->page_header();

print html::get_message();

## Daten des aktiven Kunden ausgeben
my $act_cust = Parts::active_customer->new();

## Such-Formular (CGI-Formbuild-Obj)
my $search_form = Parts::customer_search_form::init($cgi);

my $vars = {
	active_customer => $act_cust->render(),

	#	last_modified_customer => Parts::last_modified_customer->render(),
	#	search_form            => $search_form->render()
};

$vars->{last_modified_customer} = Parts::last_modified_customer->render()
  if $auth->is_admin || $auth->is_editor;
$vars->{search_form} = $search_form->render()
  if $auth->is_admin || $auth->is_editor;

print TT_Wrapper->process( "main_tt.htm", $vars );

# Footer ausgeben
print $layout->page_footer();

#$session->flush();
