#!/usr/bin/perl
unshift(@INC,"sfera/cgi/");
require "mysql.pl";
require "template.pl";


$id=$query->param("id");
$lang=$query->param("lang");
$img=$query->param("img");

$file_small=$query->param("file_small");
$file_big=$query->param("file_big");

$alert=$query->param("alert");
$download=$query->param("download");

$date=$query->param('date');
$date=~/(\d{2})\.(\d{2})\.(\d{4})/;
$date=$3."-".$2."-".$1;

#print"Content-type:text/html\n\n";

if($img){

$sth1=$dbh->prepare("select DATE_FORMAT(date,'%d.%m.%Y') from images_date where img='".$id."_".$img."'") or print $dbh->errstr; 
$sth1->execute() or print $sth1->errstr;

while($row = $sth1->fetchrow_arrayref) {
$img_date=$row->[0];
}
	
}

if($update||$insert||$upload){
$history_text=$query->param('history_text');
$history_text=~s/\'/\\\'/g;
$history=$query->param('history');
}

if($download){

#print "Content-Type: type/subtype\n";
print "Content-Type: application/download\n";
#print "Content-Type: application/vnd.visio\n";

#print 'Content-Disposition: attachment; filename="11.jpg"\n';

$file=$download;
$file=~s/(.*)\///g;
if($ENV{HTTP_USER_AGENT}=~/opera/i){
	print "Content-Disposition: filename=\"$file \";\n";
	print "Content-Disposition: attachment;\n";
	}else{
	print "Content-Type: application/download\n";
	print "Content-Disposition:application/octet-stream; filename=$file\n";
	}
	
#print "Content-Disposition:  filename=11.jpg\n";

#print "Content-Disposition: attachment; filename=\"11.jpg\"\n";




print "\n";

open(zip, $download) or print "$! $download";

binmode(zip);
binmode(STDOUT);
while (<zip> ) {
	print;
	}
close(zip);

exit 0;

}

@contents = glob($pref."images/".$id."_*.jpg");

if(scalar @contents){
$img_big=convert_sm2big($contents[$img-1]);
}

	sub convert_sm2big{
	my $n=$_[0];
	my $img_big=$n;
	$img_big=~s/\/($id)\_/\/$1big\_/;	
	return $img_big;
	}

if(($upload||$edit||$delete)&&$img){
	$new_im=@contents[(scalar @contents)-1];

	$new_im=~/\/(\d+)\_(\d+)\./;
	$n=$2+1;
	$new_im=~s/\/(\d+)\_(\d+)\./\/$1_$n\./;
#	print $new_im."<br>$img";
	if(!$new_im){$new_im=$pref."images/".$id."_1.jpg"}
	push(@contents,$new_im);
	
	

use POSIX qw(strftime);

	

	set_history();

    $date_now=  strftime "%d.%m.%Y", localtime;
	$h{date}=  $img_date|| $date_now;
	
	if($upload || $delete){
	$img_big=convert_sm2big($contents[$img-1]);
	
	if($file_small){
	binmode($file_small);
    open (OUTFILE,">".$contents[$img-1])||print "Content-type:text/html\n\n".$contents[$img-1]."- not save";
	binmode(OUTFILE);
        while ($bytesread=read($file_small,$buffer,2024)) {
          print OUTFILE $buffer;
        }
	close OUTFILE;
	system("chmod 0666 ".$contents[$img-1]);			
	}
	
	if($file_big){
	binmode($file_big);
    open (OUTFILE,">".$img_big)||print "Content-type:text/html\n\n".$img_big."- <b>not save</b><br><pre>";
	binmode(OUTFILE);
        while ($bytesread=read($file_big,$buffer,2024)) {
          print OUTFILE $buffer;
        }
	close OUTFILE;
	system("chmod 0666 ".$img_big);			
	}

	if($delete){
	$sth1=$dbh->do("delete from  images_date where img='$id"."_"."$img'");
	unlink ($contents[$img-1])||print "Content-type:text/html\n\n".$contents[$img-1]."- <b>not delete</b><br><pre>";
	if(-e $img_big){
		unlink ($img_big)||print "Content-type:text/html\n\n".$img_big."- not delete";		
		}
	print $query->redirect("$ENV{'SCRIPT_NAME'}?id=$id&img=1&edit=1");
	exit 0;
	}
	

if($img_date){	
	$sth1=$dbh->do("update  images_date SET date='$date' where img='$id"."_"."$img'");
	}else{
	$sth1=$dbh->do("INSERT INTO images_date SET img='$id"."_"."$img',date='$date'");
	}
	
	print $query->redirect("$ENV{'SCRIPT_NAME'}?id=$id&img=$img&edit=1");
	exit 0;
	}
	}




if($update||$insert){
$name=$query->param('name');
$name=~s/\'/\\\'/g;
$name_eng=$query->param('name_eng');
$name_eng=~s/\'/\\\'/g;
$pol=$query->param('pol');
$otez=$query->param('otez');
$otez=~s/\'/\\\'/g;
$zavod=$query->param('zavod');
$zavod=~s/\'/\\\'/g;
$fzavod=$query->param('fzavod');
$zvanie=$query->param('zvanie');
$owner=$query->param('owner');
$owner=~s/\'/\\\'/g;
$owner_eng=$query->param('owner_eng');
$owner_eng=~s/\'/\\\'/g;
$mama=$query->param('mama');
$mama=~s/\'/\\\'/g;
$pitom=$query->param('pitom');
}



if(!$img&&$update){
$sth1=$dbh->do("UPDATE dogs SET name='$name',name_eng='$name_eng',pol='$pol',otez='$otez',mama='$mama',owner='$owner',owner_eng='$owner_eng',zavod='$zavod',fzavod='$fzavod',zvanie='$zvanie',pitom='$pitom',date='$date' where id=".$id); 
set_history();
print $query->redirect("$ENV{'SCRIPT_NAME'}?id=".$id."&edit=1&alert=1");
exit 0;
}

if(!$img&&$delete){
print"Content-type:text/html;charset=windows-1251\n\n";
$sth1=$dbh->do("delete from  dogs where id=".$id); 
print "Собака удалена !!!";
#foreach $env_var (keys %ENV){

#print "<I>$env_var=$ENV{$env_var}</I><BR>\n";

#}

exit 0;
}

if($delete_history){
print"Content-type:text/html;charset=windows-1251\n\n";
$sth1=$dbh->do("delete from  history where num=".$delete_history); 
print "Событие удалено !!!";
#foreach $env_var (keys %ENV){

#print "<I>$env_var=$ENV{$env_var}</I><BR>\n";

#}

exit 0;
}

if($insert){
$sth1=$dbh->do("INSERT INTO dogs SET name='$name',name_eng='$name_eng',pol='$pol',otez='$otez',mama='$mama',owner='$owner',owner_eng='$owner_eng',zavod='$zavod',fzavod='$fzavod',zvanie='$zvanie',pitom='$pitom',date='$date'"); 
my $newid=$dbh->{'mysql_insertid'};
set_history();
print $query->redirect("$ENV{'SCRIPT_NAME'}?id=$newid&edit=1&alert=1");
exit 0;
}

print"Content-type:text/html; charset=windows-1251\n\n";

if($alert){
print qq~
<script>
alert("операция прошла успешно !!!");

</script>
~;
}

if($img){
	if($edit||$new){
	$SEARCH_TEMPLATE = $templ.'katalog_img_det.htm';
	}else{
	$SEARCH_TEMPLATE = $lang?$templ.'katalog_img_eng.htm':$templ.'katalog_img.htm';
	}
	
}else{
	if($edit||$new){
	$SEARCH_TEMPLATE = $templ.'katalog_det_edit.htm';
	}else{
	$SEARCH_TEMPLATE = $templ.'katalog_det.htm';
	}
}

if($new){

get_pitom();
$h{action}="insert";
$h{history}="Добавлена собака";
$h{history_checked}="checked";
$template = new Template($SEARCH_TEMPLATE);

$html=$template->cast(\%h);
print $html;
exit 0;
}


$sth1=$dbh->prepare("select t.id,t.owner,t.name,DATE_FORMAT(t.date,'%d.%m.%Y'),t.pol,t.zvanie,p.name,p.owner,p.adress,p.tel,t.otez,t.mama,t.pitom,t.zavod,t.fzavod,t.name_eng,t.owner_eng  from dogs as t,pitom as p where (t.pitom=p.id or (t.pitom =0 and p.id =0)) and t.id=".$id) or print $dbh->errstr; 
$sth1->execute() or print $sth1->errstr;

if ($sth1->rows){



while($row = $sth1->fetchrow_arrayref) {

	$h{id}= $row->[0];
	$h{name}= $row->[2];
	$h{name_eng}=$row->[15];
	$pitom=$row->[12];
if($img eq ""){
	$h{owner}=$row->[1];
	$h{owner_eng}=$row->[16];

	$h{date}=$row->[3] eq "00.00.0000"?"":$row->[3];
	$h{otez}=$row->[10];
	$h{mama}=$row->[11];
	$h{zavod}=$row->[13];
	$h{fzavod}=$row->[14];
	if(-e $row->[14]){
		$h{fzavod_im}='<img src="'.$row->[14].'" height="80" border="0" align="right" alt="Фото заводчика" hspace="8" vspace="8">';
		}
	$h{pname}= $row->[6];
	$row->[7]=~s/\n/<br>/g;	
	$h{powner}= $row->[7];	
	$row->[8]=~s/\n/<br>/;
	$h{padress}= $row->[8];
	$row->[9]=~s/\n/<br>/;
	$h{ptel}= $row->[9];
		
	if($row->[4] eq "m"){
	$h{pol}="Кобель"};
	if($row->[4] eq "f"){
	$h{pol}="Сука";
	}
	
	$h{zvanie}= $row->[5]?"чемпион":"";
	
	if($edit){
	$h{history}= "Изменение информации";
	$h{'pol'.$row->[4]}=  "selected";
	$h{zvanie}= $row->[5]?"checked":"";
	$h{action}="update";
	get_pitom();
	}
	
	if(scalar @contents||$edit){$h{img}="<b>>></b>&nbsp;<u>фото</u>"}
	}else{
	$h{history}= "Добавление картинки";
	$h{img}="<b>&middot;</b>";


	$h{img_date}=$img_date?($lang?"Date of Photo":"Дата добавления фото").":<b>$img_date</b>":"";
	foreach $im (@contents){
	$a=" <a href='$ENV{SCRIPT_NAME}?lang=$lang&id=".$id."&img=".(++$i).($edit?"&edit=1":"")."'>&nbsp;<u>&nbsp;<b>";
	$a_="</b>&nbsp;</u>&nbsp;</a> ";
	if($im eq $new_im){$i_txt="new";}else{$i_txt=$i;};
#	print $im."<br>\n";
	$h{img}.=($img!=$i)?$a.$i_txt.$a_:"&nbsp;&nbsp; <b> ".$i_txt." </b>&nbsp;&nbsp;";
	$h{img}.="<b>&middot;</b>";
	}
	
	if(-e $img_big){
        ($filesize) = (stat($img_big))[7];
		$img_big=~s/$pref//;
	    my $formatted_size = int($filesize / 1000);
    	$h{img_size}="<b>>> </b>".($lang?"Download Greater Photo":"Скачать большое фото ")."- ".($formatted_size == 0 ?"$filesize bytes" :$formatted_size." Kb");
		
		$h{img_big}= $img_big;	
		}

	$contents[$img-1]=~s/$pref//;
	$h{img_src}= $contents[$img-1];

	$h{img_id}= $img;
	if($img != scalar @contents ){$h{del_txt}=">><font color=maroon> Удалить x</font>";}
	if($edit && $img == scalar @contents ){$h{img_src}= "images/null.gif";$h{history_checked}="checked";}
	}
}
$template = new Template($SEARCH_TEMPLATE);

$html=$template->cast(\%h);


	}else{
	$html="<font color=\"Maroon\"><b>Ошибка</b></font>: Собака не найдена!<br>Повторите запрос";	
	}

print $html;

#foreach $env_var (keys %ENV){

#print "<I>$env_var=$ENV{$env_var}</I><BR>\n";

#}

exit 0;


sub get_pitom{

$sth2=$dbh->prepare("select p.id,p.name from pitom as p where id<>0 order by p.name") or print $dbh->errstr; 
$sth2->execute() or print $sth2->errstr;

while (($row = $sth2->fetchrow_arrayref))
{
$sel="";
if( $pitom eq $row->[0]){$sel="selected"};
	$h{pitom}.="<option value='$row->[0]' $sel>".$row->[1]."\n";
}

}


sub set_history{
#error($id);

if($history&&$history_text){
	my $sth1=$dbh->do("INSERT INTO history SET id=".($id||$dbh->{mysql_insertid}).", title='$history_text',date=NOW()")||error($dbh->errstr); 
	}
}