#!/usr/home/italpro/local/bin/perl

use strict;
use warnings;
use encoding 'utf8';
use lib './modules';
use lib '/usr/home/dexter/perl/lib/perl5/site_perl/5.8.3';
use lib '/usr/home/dexter/perl/lib/perl5/5.8.3';
use CGI::Simple ();
use CGI::Carp qw(fatalsToBrowser); # serve gestire i messaggi di errore 
use DBI ();
use MIME::Lite ();
use Image::Info ();
use Petal::AlwaysUTF8 ();

$CGI::Simple::DISABLE_UPLOADS = 0;
$CGI::Simple::POST_MAX = 10_485_760;

my $q=new CGI::Simple;

#Inizializzazione di Petal
#Petal::BASE_DIR        =  "./t";
$Petal::DECODE_CHARSET  = 'UTF-8';
$Petal::OUTPUT          = 'XHTML';
$Petal::DISK_CACHE       = 0;   #per svuotare la memoria cache



#Apertura connessione con database

my $dbh = DBI->connect("DBI:mysql:italpro_alea:qs1213.pair.com", "italpro_8","kePHRZ78");
if (!$dbh) { die 'main-1 (can\'t connect to SQL server)'; }

$ENV {'PATH'} = '/bin';

if ($q->param('par')eq 'mod') { mod(); } 
    elsif ($q->param('par') eq 'agg') {agg();}
    elsif ($q->param('par') eq 'wr') {wr();}
    elsif ($q->param('par') eq 'del') {del();}
    else {list();}
     
$dbh->disconnect();



sub list {
print $q->header(
  -charset => 'utf-8'
);

my $flagtipo =$q->param('flagtipo');

my $t = new Petal::AlwaysUTF8 ( file => "./t/ed-privc$flagtipo.xhtml",); #chiamata di Petal


my $dati= "select 
          meo_opere_in_costruzione.id,
          meo_opere_in_costruzione.luogo
          from meo_opere_in_costruzione
          where meo_opere_in_costruzione.flagtipo = $flagtipo
          order by meo_opere_in_costruzione.priorita , meo_opere_in_costruzione.titolo  ";
my $sth = $dbh->prepare($dati);
if (!$sth) {die 'Forms-mm-2b ('.$dbh->errstr.')';}
$sth->execute or die 'Forms-mm-2b ('.$dbh->errstr.')';
my ($rows) = $sth->fetchall_arrayref({});
$sth->finish;

my $dati2= "select 
          meo_opere_in_costruzione.id,
          meo_opere_in_costruzione.titolo,
          meo_opere_in_costruzione.luogo,
          meo_opere_in_costruzione.descrizione
          from meo_opere_in_costruzione
          where meo_opere_in_costruzione.flaghome = 1
          limit 1";
my $sth2 = $dbh->prepare($dati2);
if (!$sth2) {die 'Forms-mm-2b ('.$dbh->errstr.')';}
$sth2->execute or die 'Forms-mm-2b ('.$dbh->errstr.')';
my $ultima = $sth2->fetchrow_hashref();
$sth2->finish;

opendir(DIR, "../dati/opere_in_costruzione/") or die "Opere-mm-1: $!";
    my @files = readdir(DIR);
    closedir DIR;

    foreach my $hrow(@$rows) {
        my $ifn = (grep /^$hrow->{'id'}_1\.(png|jpg)$/, @files)[0];
        if (defined $ifn) {
            $hrow->{"ifn1"} = $ifn;
            my $ii = Image::Info::image_info("../dati/opere_in_costruzione/$ifn");
            if ($ii->{error}) {
                die "Opera-mm-2: $ii->{error}\n";
            }
            ($hrow->{"isx1"}, $hrow->{"isy1"}) = Image::Info::dim($ii);
        }
    }
        my $ifn = (grep /^$ultima->{'id'}_3\.(png|jpg)$/, @files)[0];
        if (defined $ifn) {
            $ultima->{"ifn1"} = $ifn;
            my $ii = Image::Info::image_info("../dati/opere_in_costruzione/$ifn");
            if ($ii->{error}) {
                die "Opera-mm-2: $ii->{error}\n";
            }
            ($ultima->{"isx1"}, $ultima->{"isy1"}) = Image::Info::dim($ii);
        }
        
        my (@tmparr, @righe);
my $i=0;
foreach my $hrow (@$rows) {
push @tmparr,$hrow;
if ($i==4) {
    push @righe, {
         rows=>[@tmparr]
    };
            @tmparr = ();
            $i = 0;
        } else {
        $i++;
 }
}
    if (@tmparr > 0) {
        push @righe, {
            rows => [ @tmparr ]
        };
    }
        
    

print $t->process(
righe=>\@righe,
ultima=>$ultima);

sub tiposel {
    my $selected = shift;

    my @sn = ('edilizia privata', 'enti pubblici', 'settore immobiliare');

    my @lsn;
    for my $i(0..$#sn) {
        my $sel = undef; $i == $selected and $sel = 'selected';
        push @lsn, {
            isn      => $i,
            sn       => $sn[$i],
            selected => $sel,
        };
    }
    return \@lsn;
}






sub saveimg{
my ($id, $code) = @_;
my $name= $q->param("img$code");

my $fullname='';
if ($name ne '') {
    my ($ext) = lc(substr($name, -3,3));
    $ext =~ /^\w{3}$/ and $ext=$&;
    $fullname = "/var/www/htdocs/cooperativameolese.com/dati/opere_in_costruzione/${id}_${code}.$ext";
    
# Delete previous images
        foreach (glob("../dati/opere_in_costruzione/${id}_${code}.*")) {
            if ($_ =~ /^[\w\-\.\/]+$/) {
                unlink $&;
            }
        }


my $rv = $q->upload(
            $name,
            $fullname
        );
        if (!$rv) {
            die("saveimg-1 ($rv)");
        }
    }
    
    return $fullname;
}
sub savefile {
    my ($id, $icode) = @_;
    
    my $name = $q->param("file${icode}");
    if ($name ne '') {
        # Delete previous files
        foreach (glob("../dati/opere_in_costruzione/${id}_${icode}")) {
            if ($_ =~ /^[\w\-\.\/]+$/) {
                unlink $&;
            }
        }
        my $rv = $q->upload(
            $name,
            "../dati/opere_in_costruzione/${id}_${icode}.dlf"
        );
        if (!$rv) {
            die ("savefile-1 (can't open file)");
        }
    }
}

sub sqlstr {
  my ($str) = shift;
  $str =~ s/\\/\\\\/g;
  $str =~ s/\'/\\\'/g;
  return $str;
}}
