#!/usr/local/bin/perl

require "../sql.pl";
require "../subs.pl";
require "../config.pl";
require "../mparser.pl";
require "../cript.pl";
require "../zip.pl";
require "../mailer.pl";
$protect_seconds=5;		# задержка во время авторизации 







 





$dbh=&user_connect();
if ($dbh)
{
	&hash_create();
	&set_prize();



	$user_data=&login;
	if ($user_data)
	{


#		$voteid=$$user_data{id}*17;
#		$lang=&set_user_language;
#		srand($$user_data{id});
		if ($query->param('action') eq 'show_main')			{&show_main();}
		elsif ($query->param('action') eq 'show_create_schet')	{&show_create_schet();}
		elsif ($query->param('action') eq 'schet_create')	{&schet_create();}
		elsif ($query->param('action') eq 'show_schet_edit')	{&show_schet_edit();}
		elsif ($query->param('action') eq 'show_schet')	{&show_schet();}
		elsif ($query->param('action') eq 'schet_edit')	{&schet_edit();}
		elsif ($query->param('action') eq 'show_licenz'){&show_licenz();}
		else {	&show_main();}
	}
	&sql_disconnect();
}else
{
	&print_header;
	print "Server busy";
}


sub show_licenz()
{
	&print_header;
	if ($$user_data{schet_created})
	{
		$sth = $dbh->prepare("select * from fr_registration where user_id=?") or print $dbh->errstr."\n";
		$sth->execute($$user_data{id}) or print $sth->errstr."\n";
		my $reg_row=$sth->fetchrow_hashref(NAME_lc);



		if ($reg_row)
		{
			$sth = $dbh->prepare("select * from fr_schet where id=?") or print $dbh->errstr."\n";
			$sth->execute($$reg_row{schet_id}) or print $sth->errstr."\n";
			my $schet_row=$sth->fetchrow_hashref(NAME_lc);
			if ($schet_row)
			{
				$sth = $dbh->prepare("select * from fr_registration_product where registration_id=?") or print $dbh->errstr."\n";
				$sth->execute($$reg_row{id}) or print $sth->errstr."\n";
				my (@sub_regs,$row);
				while ($row=$sth->fetchrow_hashref(NAME_lc))
				{
					push @sub_regs,$row;
				}


				foreach my $pid (@d_products)
				{
					$$pid{is_fastrep}=($$pid{product_id}==5 || $$pid{product_id}==4)?1:0;
					
					foreach my $rid (@sub_regs)
					{
						if ($$pid{product_id}==$$rid{product_id})
						{
							foreach my $sc (@{$$pid{count_product}})
							{
								if ($$sc{count}==$$rid{product_count})
								{
									$$sc{selected}=1;
								}
							}
						}
						
					}
				}
				&tmpl_print("tmpl/show_licenz.tmpl",{
				
				schet_numer=>$$schet_row{numer},
				is_modify=>1,
				country_ar=>&ret_rus_country($$user_data{country_id}),
				schet_created=>1,
				products=>\@d_products});



			}
		}
		



	}


}





sub schet_edit
{
	my %out_hash;
	$error_string='';
	$error_count=0;
	$is_show_ur=0;

	&schet_create();
}


sub show_schet_edit
{
	&print_header;
	if ($$user_data{schet_created})
	{
		$sth = $dbh->prepare("select * from fr_registration where user_id=?") or print $dbh->errstr."\n";
		$sth->execute($$user_data{id}) or print $sth->errstr."\n";
		my $reg_row=$sth->fetchrow_hashref(NAME_lc);



		if ($reg_row)
		{
			$sth = $dbh->prepare("select * from fr_schet where id=?") or print $dbh->errstr."\n";
			$sth->execute($$reg_row{schet_id}) or print $sth->errstr."\n";
			my $schet_row=$sth->fetchrow_hashref(NAME_lc);
			if ($schet_row)
			{
				$sth = $dbh->prepare("select * from fr_registration_product where registration_id=?") or print $dbh->errstr."\n";
				$sth->execute($$reg_row{id}) or print $sth->errstr."\n";
				my (@sub_regs,$row);
				while ($row=$sth->fetchrow_hashref(NAME_lc))
				{
					push @sub_regs,$row;
				}


				foreach my $pid (@d_products)
				{
					foreach my $rid (@sub_regs)
					{
						if ($$pid{product_id}==$$rid{product_id})
						{
							foreach my $sc (@{$$pid{count_product}})
							{
								if ($$sc{count}==$$rid{product_count})
								{
									$$sc{selected}=1;
								}
							}
						}
						
					}
				}
				&user_page_print("tmpl/show_create_schet.tmpl",{
				
				schet_numer=>$$schet_row{numer},
				is_modify=>1,
				country_ar=>&ret_rus_country($$user_data{country_id}),
				schet_created=>1,
				products=>\@d_products});



			}
		}
		



	}

}




sub show_schet
{
	if ($$user_data{schet_created})
	{
		$sth = $dbh->prepare("select * from fr_registration where user_id=?") or print $dbh->errstr."\n";
		$sth->execute($$user_data{id}) or print $sth->errstr."\n";
		my $reg_row=$sth->fetchrow_hashref(NAME_lc);
		if ($reg_row)
		{
			$sth = $dbh->prepare("select * from fr_schet where id=?") or print $dbh->errstr."\n";
			$sth->execute($$reg_row{schet_id}) or print $sth->errstr."\n";
			my $schet_row=$sth->fetchrow_hashref(NAME_lc);
			if ($schet_row)
			{
				$sth = $dbh->prepare("select * from fr_registration_product where registration_id=?") or print $dbh->errstr."\n";
				$sth->execute($$reg_row{id}) or print $sth->errstr."\n";
				my (@sub_regs,$row);
				while ($row=$sth->fetchrow_hashref(NAME_lc))
				{
					push @sub_regs,$row;
				}

				my $sumitog=0;
				my $sumitog_r=0;
				my $sumitog_k=0;

				&print_header;

				my $nc=0;

				foreach my $pid (@d_products)
				{
					foreach my $rid (@sub_regs)
					{
						if ($$pid{product_id}==$$rid{product_id})
						{
							$nc++;
							$$pid{nc}=$nc;
							$sumitog+=$$rid{summa_rub};
							$$pid{summa}=$$rid{summa_rub};
							
							$$pid{summa_r}=int($$pid{summa});
							$$pid{summa_k}=int(($$pid{summa}-$$pid{summa_r})*100);
							
							$sumitog_r+=$$pid{summa_r};
							$sumitog_k+=$$pid{summa_k};

							$$pid{prize_r_div}=&razr_div($$pid{prize_r});
							$$pid{summa_r_div}=&razr_div($$pid{summa_r});
							$$pid{summa_k}='0'.$$pid{summa_k} if $$pid{summa_k}<10;
							$$pid{product_count}=$$rid{product_count};
						}
						
					}
				}
				

				my $dk=int($sumitog_k/100);

				$sumitog_r+=$dk;
				$sumitog_k=int(($sumitog_k/100-$dk)*100);


				$sumitog_r_div=&razr_div($sumitog_r);

				&tmpl_print("tmpl/show_schet.tmpl",{
				
				schet_numer=>$$schet_row{numer},

				firm=>$$user_data{firm},
				


				d_day=>substr($$schet_row{schet_date},8,2),
				d_month=>substr($$schet_row{schet_date},5,2),
				d_year=>substr($$schet_row{schet_date},0,4),
				str_month=>$months[-1+substr($$schet_row{schet_date},5,2)],
				                      
				is_pechat=>1,
				sumitog=>$sumitog,
				sumitog_k=>$sumitog_k,
				sumitog_r=>$sumitog_r,
				sumitog_r_div=>$sumitog_r_div,
				
				str_sum=>&num2str($sumitog),

				schet_created=>1,
				products=>\@d_products});



			}
		}
	}
}

sub clean_text
{
    my $sr=@_[0];
	$sr=~s/"/''/g;
	$sr=~ s/<//g;
	$sr=~ s/>//g;
	return $sr;
}


sub schet_create
{
	my %out_hash;
	$error_string='';
	$error_count=0;
	$is_show_ur=0;


	&clean_text('name');
	&clean_text('family');
	&clean_text('otch');
	&clean_text('email');

	&clean_text('phone');
	&clean_text('icq');
	&clean_text('country');
	&clean_text('firm');


	&clean_text('ur_address');
	&clean_text('ur_index');
	&clean_text('fact_address');
	&clean_text('fact_index');
	&clean_text('inn');
	&clean_text('litco');
	&clean_text('dolzhn');
	&clean_text('okpo');
	&clean_text('okonh');
	&clean_text('bank');
	&clean_text('rs');
	&clean_text('ks');
	&clean_text('bik');

	&clean_text('doprekvisit');
	&clean_text('prc_4');
	&clean_text('prc_5');
	&clean_text('prc_6');
	&clean_text('prc_7');
	&clean_text('prc_8');
	&clean_text('prc_9');
	&clean_text('prc_10');


	my %hash_err;

    if ($query->param('name') eq '')
    {
       $error_string.=($error_string?'<br>':'').'Введите имя!';
       $hash_err{is_name_error}='Введите имя!';
       $error_count++;
    }

    if ($query->param('email') eq '')
    {
       $error_string.=($error_string?'<br>':'').'Укажите E-Mail!';
       $hash_err{is_email_error}='Введите имя!';
       $error_count++;
    }

    if ($query->param('firm') eq '')
	{
        $error_string.=($error_string?'<br>':'').'Укажите наименование организации!';
        $hash_err{is_firm_error}='Укажите наименование организации!';
		$error_count++;
    }

	if ($query->param('ur_address') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите юридический адрес!';
        $hash_err{is_ur_address_error}='Укажите юридический адрес!';
    	$error_count++;
	}

	if ($query->param('ur_index') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите индекс!';
        $hash_err{is_ur_index_error}='Укажите индекс!';
    	$error_count++;
	}

	if ($query->param('fact_address') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите фактический адрес!';
        $hash_err{is_fact_address_error}='Укажите фактический адрес!';
    	$error_count++;
	}

	if ($query->param('fact_index') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите индекс!';
        $hash_err{is_fact_index_error}='Укажите индекс!';
    	$error_count++;
	}

	if ($query->param('inn') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите ИНН!';
        $hash_err{is_inn_error}='Укажите ИНН!';
	    $error_count++;
	}

	if ($query->param('litco') eq '')
    {
		$error_string.=($error_string?'<br>':'').'Укажите лицо заключающее договор!';
        $hash_err{is_litco_error}='Укажите лицо заключающее договор!';
    	$error_count++;
    }

    if ($query->param('dolzhn') eq '')
   	{
        $error_string.=($error_string?'<br>':'').'Укажите должность!';
        $hash_err{is_dolzhn_error}='Укажите должность!';
   		$error_count++;
    }

    my $c_count=0;
	foreach my $i (@d_products)
	{
		if ($query->param('prc_'.$$i{product_id})>0)
		{
			$c_count+=$query->param('prc_'.$$i{product_id});
		}
	}
    if ($c_count==0)
    {
		$error_string.=($error_string?'<br>':'').'Не выбран продукт!';
		$error_count++;
    }


    if ($error_count>0)
   	{
   		&print_header();
#		&user_page_print("tmpl/back_form.tmpl",{schet_created=>0,error=>$error_string});




		&user_page_print("tmpl/show_create_schet.tmpl",
		{
			%hash_err,
			error=>$error_string,
			schet_created=>0,
			country_ar=>&ret_rus_country(),
			schet_numer=>$$schet_row{numer},
			is_modify=>0,

name=>$query->param('name'),
family=>$query->param('family'),
otch=>$query->param('otch'),
email=>$query->param('email'),
phone=>$query->param('phone'),
icq=>$query->param('icq'),
firm=>$query->param('firm'),
ur_address=>$query->param('ur_address'),
ur_index=>$query->param('ur_index'),
fact_address=>$query->param('fact_address'),
fact_index=>$query->param('fact_index'),
inn=>$query->param('inn'),
litco=>$query->param('litco'),
dolzhn=>$query->param('dolzhn'),
okpo=>$query->param('okpo'),
okonh=>$query->param('okonh'),
bank=>$query->param('bank'),
rs=>$query->param('rs'),
ks=>$query->param('ks'),
bik=>$query->param('bik'),
doprekvisit=>$query->param('doprekvisit'),
			
			
			products=>\@d_products});



				







    }else
    {
		$query->param(-name=>'login',-value=>&gen_login($query->param('email')));
		$query->param(-name=>'password',-value=>&gen_pass());

		$sth = $dbh->prepare("insert into fr_user (
			login,
			birth,
			name,
			family,
			otch,
			sex,
			password,
			status_int,
			user_type_int,
			email,
			icq,
			country_id,
			address,
			phone
		) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)") or print $dbh->errstr."\n";

		$sth->execute(
			$query->param('login'),
			"0000-00-00",
			$query->param('name'),
			$query->param('family'),
			$query->param('otch'),
			0,
			$query->param('password'),
			$_USER_STATUS{NOINIT},
			13,
			$query->param('email'),
			$query->param('icq'),
			$query->param('country'),
			'',
			$query->param('phone')
		) or print $sth->errstr."\n";
		&bitrix_insert($query->param('login'),'login');

		
		
		my $new_user_id;
		$sth = $dbh->prepare("select max(id) as max_id from fr_user") or print $dbh->errstr."\n";
		$sth->execute() or print $sth->errstr."\n";
		my $row=$sth->fetchrow_hashref(NAME_lc);
		my $new_user=$$row{max_id};
		my $next_schet_id=0;
		my $curs_usd=$config{curs_usd};
		my $curs_eur=$config{curs_eur};
		my $valuta_int=2;
			$sth = $dbh->prepare("insert into fr_user_ur (
				user_id,
				firm,
				ur_address,
				ur_index,
				fact_address,
				fact_index,
				inn,
				litco,
				dolzhn,
				okpo,
				okonh,
				bank,
				rs,
				ks,
				bik,
				doprekvisit
			) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") or print $dbh->errstr."\n";
				$sth->execute(
				$new_user,
				$query->param('firm'),
				$query->param('ur_address'),
				$query->param('ur_index'),
				$query->param('fact_address'),
				$query->param('fact_index'),
				$query->param('inn'),
				$query->param('litco'),
				$query->param('dolzhn'),
				$query->param('okpo'),
				$query->param('okonh'),
				$query->param('bank'),
				$query->param('rs'),
				$query->param('ks'),
				$query->param('bik'),
				$query->param('doprekvisit')
			) or print $sth->errstr."\n";

			$sth = $dbh->prepare("update fr_config set schet_numer=schet_numer+1") or print $dbh->errstr."\n";
			$sth->execute() or print $sth->errstr."\n";
			$sth = $dbh->prepare("select schet_numer from fr_config") or print $dbh->errstr."\n";
			$sth->execute() or print $sth->errstr."\n";
			$row=$sth->fetchrow_hashref(NAME_lc);
			my $next_schet_numer=$$row{schet_numer};
			$sth = $dbh->prepare("insert into fr_schet (numer,schet_date) values (?,NOW())") or print $dbh->errstr."\n";
			$sth->execute($next_schet_numer) or print $sth->errstr."\n";
			$sth = $dbh->prepare("select max(id) as max_id from fr_schet") or print $dbh->errstr."\n";
			$sth->execute() or print $sth->errstr."\n";
			$row=$sth->fetchrow_hashref(NAME_lc);
			$next_schet_id=$$row{max_id};
			my $new_x_id=&gen_x_id($query->param('email'),$query->param('family').$query->param('name'));

		$sth = $dbh->prepare("insert into fr_registration (
			x_id,
			convertation_type_int,
			date,
			sys_date,
			schet_id,
			user_id,
			mail_id,
			registration_type_int,
			status_int,
			diler_id,
			robot_id,
			worker_id
		) values (?,?,NOW(),NOW(),?,?,?,?,?,?,?,?)") or print $dbh->errstr."\n";

		$sth->execute(
			$new_x_id,
			$_CONVERTATION_TYPE{MANUAL},
			$next_schet_id,
			$new_user,
			'',
			13,
			$_REGISTRATION_STATUS{SCHET},
			0,
			0,
			0
		) or print $sth->errstr."\n";

		$sth = $dbh->prepare("select max(id) as max_id from fr_registration") or print $dbh->errstr."\n";
		$sth->execute() or print $sth->errstr."\n";
		my $row=$sth->fetchrow_hashref(NAME_lc);
		my $new_reg_id=$$row{max_id};

		my $products=&ret_products_list;

		my ($vs_summa_usd,$vs_summa_rub,$vs_summa_eur)=(0,0,0);

		$sth = $dbh->prepare("update fr_user set registration_id=? where id=?") or print $dbh->errstr."\n";
		$sth->execute($new_reg_id,$new_user) or print $sth->errstr."\n";

		foreach my $i (@$products)
		{
			if ($query->param('prc_'.$$i{product_id})>0)
			{

				my ($summa_usd,$summa_rub,$summa_eur,$skidka_usd,$skidka_rub,$skidka_eur);

				

				$summa_rub=$query->param('prc_'.$$i{product_id})*$$i{prize_rub_ur};
				$skidka_rub=0;



					$summa_usd=$summa_rub/$curs_usd;
					$skidka_usd=0;
					$summa_eur=$summa_rub/$curs_eur;
					$skidka_eur=0;
				$vs_summa_usd+=$summa_usd;
				$vs_summa_rub+=$summa_rub;
				$vs_summa_eur+=$summa_eur;
				$sth = $dbh->prepare("insert into fr_registration_product (
					registration_id,
					skidka_usd,
					skidka_rub,
					skidka_eur,
					summa_usd,
					summa_rub,
					summa_eur,
					valuta,
					product_id,
					product_bild_id,
					product_count
				) values (?,?,?,?,?,?,?,?,?,?,?)") or print $dbh->errstr."\n";
				$sth->execute(
					$new_reg_id,
					$skidka_usd,
					$skidka_rub,
					$skidka_eur,
					$summa_usd,
					$summa_rub,
					$summa_eur,
					2,
					$$i{product_id},
					$$i{id},
					$query->param('prc_'.$$i{product_id})
				) or print $sth->errstr."\n";
			}
		}
		&create_reg_key($new_reg_id);
		
		$sth = $dbh->prepare("update fr_cookie set user_id=? where cookie=?") or print $dbh->errstr."\n";
		$sth->execute($new_user,$query->cookie('lcookie')) or print $sth->errstr."\n";
		&move_to("?popup_schet=1");



    }
}




sub show_main
{
	&print_header;
	&user_page_print("",{%$user_data,popup_schet=>$query->param('popup_schet')});

}

sub show_create_schet
{
	&print_header;
	foreach my $pid (@d_products)
	{
		if ($query->param('product_'.$$pid{product_id})>0)
		{
			foreach my $i (@$pid{count_product})
			{
				foreach my $j (@$i)
				{
					if ($$j{count}==$query->param('product_'.$$pid{product_id}))
					{
						$$j{selected}=1;
					}
				}
			}
		}
	}
	&user_page_print("tmpl/show_create_schet.tmpl",{schet_created=>0,country_ar=>&ret_rus_country(),products=>\@d_products});
}




sub user_page_print
{
	my ($template,$hash,$cont_menu)=@_;
	my $page_content=&ret_page(($template?$template:"tmpl/main_content.tmpl"),{%$user_data,%$hash});
	my $main_menu=&ret_page("tmpl/main_menu.tmpl",{%$user_data,%$hash});
	my $sub_menu=&ret_page($cont_menu,{%$user_data,%$hash}) if ($cont_menu);
	&tmpl_print("tmpl/main_page.tmpl",{%$user_data,($query->param('action')?$query->param('action'):"show_main")=>1,page_content=>$$page_content,main_menu=>$$main_menu,sub_menu=>$$sub_menu});
}



sub login
{
	$login_result={};	
	if ($query->cookie('lcookie'))
	{
		$sth = $dbh->prepare("select * from fr_cookie where cookie=?") or print $dbh->errstr."\n";
		$sth->execute($query->cookie('lcookie')) or print $sth->errstr."\n";
		my $lcookie;
		if ($lcookie=$sth->fetchrow_hashref(NAME_lc))
		{
			$$login_result{cookie}=$$lcookie{cookie};
			if ($$lcookie{user_id}>0)
			{
				$$login_result{schet_created}=1;
				my $user_row;
				$sth = $dbh->prepare("select * from fr_user where id=? AND status_int=21") or print $dbh->errstr."\n";
				$sth->execute($$lcookie{user_id}) or print $sth->errstr."\n";
				if ($user_row=$sth->fetchrow_hashref(NAME_lc))
				{

					my $ur_row;
					$sth = $dbh->prepare("select * from fr_user_ur where user_id=?") or print $dbh->errstr."\n";
					$sth->execute($$lcookie{user_id}) or print $sth->errstr."\n";
					$ur_row=$sth->fetchrow_hashref(NAME_lc);
					$login_result={%$login_result,%$user_row,%$ur_row};
					$$login_result{id}=$$lcookie{user_id};
					return $login_result;

				}else
				{
					$n_cookie=&new_cookie();
					print "Content-Type: text/html\n";
					print "Set-Cookie: lcookie=$n_cookie; expires=Sun, 27-Sep-2037 00:00:00 GMT; path=/\n\n";
					&user_page_print("",{schet_created=>0});
					return '';
				}
			}else
			{
				$$login_result{schet_created}=0;
			}
		}
		return $login_result;



	}else
	{
		$n_cookie=&new_cookie();
		print "Content-Type: text/html\n";
		print "Set-Cookie: lcookie=$n_cookie; expires=Sun, 27-Sep-2037 00:00:00 GMT; path=/\n\n";
		&user_page_print("",{schet_created=>0});
		exit;

	}





}

sub ret_rus_country
{
	my $selected=@_[0];
	my @out_ar;
	$sth = $dbh->prepare("select * from fr_country where LOCATE('_',country)=0 AND  (country_type_int=27 or country_type_int=29)") or print $dbh->errstr."\n";
	$sth->execute() or print $sth->errstr."\n";
	while($row=$sth->fetchrow_hashref(NAME_lc))
	{
		$selected=$$row{id} if(!$selected && $_COUNTRY_TYPE{RU}==$$row{country_type_int});
		push @out_ar,{value=>$$row{id},charcode=>$$row{charcode},caption=>$$row{country},selected=>($selected==$$row{id}?1:0)};

	}
    @out_ar=sort {$a->{caption} cmp $b->{caption}} (@out_ar);
    return \@out_ar;
}






















