package RentalData;
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
use strict;
use warnings;
use POSIX;
use CGI ':standard';
use Mod::Basework;
use Mod::Libenz;
use Mod::DBtank;
use Mod::APIfunc;
use Mod::Pricing;
use Mod::Payment;
use Tpl::AccountSubmenu;
use Data::Dumper;

sub new {
 my $class = shift;
 my $self = {};
 bless($self,$class);
 return $self;
}

sub tpl {
 my $node_meta = shift;
 my $users_dms = shift || "";
 my $varenv = shift;
 my $ctadr = shift || "";
 my $feedb = shift || "";

 my $q = new CGI;
 my $bw = new Basework;
 my $lb = new Libenz;
 my $dbt = new DBtank;
 my $apif = new APIfunc;
 my $pri = new Pricing;
 my $pay = new Payment;
 my $submenu = new AccountSubmenu;
 my $path = $q->path_info();
 my $dbh = "";
 my $red = "#c83434";

 my $coo = $q->cookie(-name=>'domcookie') || $R::sessionid;
 my $session="";
 my $session_and="";
 if($R::sessionid && length($R::sessionid) > 20 && !$q->cookie(-name=>'domcookie')){
        $session = "?sessionid=$R::sessionid";
        $session_and = "&sessionid=$R::sessionid";
 }
 my $bgcolor1 = "009899";#sharee
 $bgcolor1 = $dbt->{website}->{$varenv->{syshost}}->{bgcolor1} if($dbt->{website}->{$varenv->{syshost}}->{bgcolor1});
 $bgcolor1 = $dbt->{merchant_ids}->{$varenv->{merchant_id}}->{bgcolor1} if($dbt->{merchant_ids}->{$varenv->{merchant_id}}->{bgcolor1});

 my $tpl_id = $node_meta->{tpl_id};
 my $tpl = $dbt->get_tpl($dbh,$tpl_id);
 my @tpl_order = split /,/,$tpl->{tpl_order};

 my ($cttpos,$operator_hash) = $apif->user_rentals_history($q,$ctadr);
 my $cttpos_count=0;
 foreach my $id (keys(%$cttpos)){
        $cttpos_count++;
 }

 #loop operator hash to get invoices for each operator
 my $ctt_all = {};
 my $ctadrcoupon = {};
 foreach my $sharee_operator (keys (%$operator_hash)){
   my $dbh_operator = $dbt->dbconnect_extern("$sharee_operator");
   my $pref = {
        table    => "contenttrans",
        fetch    => "all",
        int10    => "$ctadr->{c_id}",
        keyfield => "ct_name",
        ct_name  => "~::[1-9]",
        };


   if($ctadr->{c_id}){
     my $ctt = $dbt->fetch_tablerecord($dbh_operator,$pref);
     foreach my $id (keys(%$ctt)){
       $ctt->{$id}->{wwwhost} = "$operator_hash->{$sharee_operator}";
       $ctt->{$id}->{operator} = "$sharee_operator";
       $ctt->{$id}->{basedir} = "$dbt->{copri_conf}->{basedir}/$dbt->{operator}->{$sharee_operator}->{dir_app}";
     }
     $ctt_all = { %$ctt_all, %$ctt };

     my $prefcoupon = {
        table   => "contentadr",
        fetch   => "one",
        txt15   => "~::\\w",
        c_id    => "$ctadr->{c_id}",
        };

     $ctadrcoupon->{$sharee_operator} = $dbt->fetch_tablerecord($dbh_operator,$prefcoupon);
     $ctadrcoupon->{$sharee_operator}->{oprefix} = "$dbt->{operator}->{$sharee_operator}->{oprefix}";
   }
 }

 my $project = "Freiburg";#defaults to sharee
 $project = $dbt->{merchant_ids}->{$varenv->{merchant_id}}->{project} if($varenv->{merchant_id} && $dbt->{merchant_ids}->{$varenv->{merchant_id}}->{project});
 my $bonus_ak = "$varenv->{cms}->{'iframe-bonusnumber-accepted'}->{txt}";
 $bonus_ak = "$varenv->{cms}->{'iframe-activation-code-info'}->{txt}" if($project eq "Freiburg");

 print "<div id='Contentapp'>\n";

 #subMenue--------
 $submenu->tpl($node_meta,$users_dms,$varenv,$ctadr,$feedb);
 #-----------------
 
 my $debug=0;
 $debug=1 if($ctadr->{c_id} eq $dbt->{copri_conf}->{superu_id} || $dbt->{copri_conf}->{stage} eq "test");
 my $debug_message = "";
 my $catch_failure=0;
 if(($R::failure && $R::failure =~ /\w+/) || ($ctadr->{txt31} && $ctadr->{txt31} =~ /\w/)){
        $debug_message = "($R::failure || $ctadr->{txt31})" if($debug);
        $catch_failure=1;
        print $q->div({-class=>'content2', -style=>"clear:both;color:$red"}, "* $varenv->{cms}->{'iframe-one-error'}->{txt} $debug_message"),"\n"; 
        print $q->div({-class=>'content2'}, "$varenv->{cms}->{'iframe-complete-confirmation'}->{txt} $debug_message"),"\n";
 }

 #confirm code manage
 if((!$ctadr->{int04} || !$ctadr->{int13}) && ($tpl_id =~ /^2$|302004/) && ($path =~ /$varenv->{accounting_3}/)){

    print $q->start_form(-name=>'accountscreen', -action=>"/$varenv->{mandant}/Account/$varenv->{accounting_3}$session"),"\n";
    print $q->hidden(-name=>"sessionid",-override=>1,-value=>"$R::sessionid");
    my $required = "";
    $debug_message = "(!$ctadr->{int04} || !$ctadr->{int13}) && $tpl_id" if($debug);
    print $q->div({-class=>'content_title3',-style=>'clear:both;'}, "$varenv->{cms}->{'iframe-almost-done'}->{txt} $debug_message"),"\n";
    my $acktext = "$varenv->{cms}->{'iframe-confirmation-codes-sent'}->{txt}";
    $acktext = "$varenv->{cms}->{'iframe-sms-confirmation-code-sent'}->{txt}" if($ctadr->{int04} && !$ctadr->{int13});
    $acktext = "$varenv->{cms}->{'iframe-email-confirmation-code-sent'}->{txt}" if(!$ctadr->{int04} && $ctadr->{int13});
    print $q->div({-class=>'content2'}, "$acktext $varenv->{cms}->{'iframe-successful-confirmation'}->{txt}"),"\n";
    if(!$ctadr->{int04}){
      my $des = "$varenv->{cms}->{'iframe-email-code'}->{txt}";
      my $key = "confirm_code";
      my $label_des="* $des";
      $varenv->{cms}->{'iframe-correct-input'}->{txt} =~ s/::input::/$des/;
      $label_des = "<span style=color:$red>$varenv->{cms}->{'iframe-correct-input'}->{txt}</span>" if($R::failure);
      print $q->label({-for=>"$key", -style=>'padding-top:1em;'},"$label_des"),"\n";
      print "<input id='$key' type='text' class='form-control' name='$key' value='' $required autofocus/>\n";
      print $q->div({-class=>'content2'}, " $varenv->{cms}->{'iframe-if-email-code-not-received'}->{txt}",$q->a({-style=>"color:#$bgcolor1;",-href=>"$varenv->{wwwhost}?sharee_edit=send_email$session_and"},"$varenv->{cms}->{'iframe-request-email-code'}->{txt}")),"\n";
    }else{
      print $q->div({-class=>'content2', -style=>'color:gray;'}, "* $varenv->{cms}->{'iframe-email-code-already-entered'}->{txt}"),"\n";
    }
    if(!$ctadr->{int13}){
      my $des = "$varenv->{cms}->{'iframe-sms-code'}->{txt}";
      my $key = "confirm_smscode";
      my $label_des="* $des";
      $varenv->{cms}->{'iframe-correct-input'}->{txt} =~ s/::input::/$des/;
      $label_des = "<span style=color:$red>$varenv->{cms}->{'iframe-correct-input'}->{txt}</span>" if($R::failure);
      print $q->label({-for=>"$key", -style=>'padding-top:1em;'},"$label_des"),"\n";
      print "<input id='$key' type='text' class='form-control' name='$key' value='' $required autofocus />\n";
      #print $q->div({-class=>'content2'}, "$varenv->{cms}->{'iframe-if-sms-code-not-received'}->{txt} ",$q->a({-style=>"color:#$bgcolor1;",-href=>"$varenv->{wwwhost}?sharee_edit=send_sms$session_and"},"$varenv->{cms}->{'iframe-request-sms-code'}->{txt}")),"\n";    
    }else{
      print $q->div({-class=>'content2', -style=>'color:gray;'}, "* $varenv->{cms}->{'iframe-sms-code-already-entered'}->{txt}"),"\n";
    }

    my $button_name = "$varenv->{cms}->{'iframe-next'}->{txt}";
    print $q->div({-style=>'margin-top:2em;text-align:center;'},"<button type='submit' name='confirm_userid' value='$ctadr->{c_id}' class='btn btn-primary btn-lg btn-block' style='border:1px solid #$bgcolor1;background-color:#$bgcolor1;'>$button_name</button>"),"\n";
    print $q->end_form,"\n";

 }#end confirm code manage
 else{

  my $payable_check=0;
  $payable_check = $bw->isuser_rentable($ctadr,$varenv);
  if($payable_check < 1){
     print $q->div({-class=>'content2',-style=>"color:$red"}, "$varenv->{cms}->{'iframe-payAck-failure'}->{txt}"),"\n";
  }

  print $q->start_form(-name=>'accountscreen', -action=>"/$varenv->{mandant}/Account/$varenv->{accounting_3}$session"),"\n";
  print $q->hidden(-name=>"sessionid",-override=>1,-value=>"$R::sessionid");

  if($R::confirm_success){
    print $q->div({-class=>'content_title3'},"$varenv->{cms}->{'iframe-registration-confirmed'}->{txt}"),"\n";
  }else{
    print $q->div({-class=>'content_title3'},"$varenv->{cms}->{$tpl->{tpl_name}}->{txt}"),"\n";
  }

    my $scol = "itime";
    foreach (@tpl_order){
      my ($key,$des,$size) = split /=/,$_;
      $ctadr->{$key} = $q->unescapeHTML("$ctadr->{$key}");
      $ctadr->{$key} = $lb->newline($ctadr->{$key},"","1");

      #$des = "$tpl_id.$key" if($debug);
      $des = $varenv->{cms}->{"iframe-form-$tpl_id.$key"}->{txt} if($varenv->{cms}->{"iframe-form-$tpl_id.$key"}->{txt});
     
	if($key =~ /ct_name/){
	 if($ctadr->{int12}){
	   print $q->div({-class=>'content2', -style=>'color:#c83434;'}, "$varenv->{cms}->{'iframe-block-rental-access'}->{txt}"),"\n";
	 }elsif($R::confirm_success){
	   print $q->div({-class=>'content2'}, "$varenv->{cms}->{'iframe-success-welcome'}->{txt}"),"\n";
	 }else{
	   #print $q->div({-class=>'content2'}, ""),"\n";
   	 }
	 if($ctadr->{int03} == 3){
	   my $prepaidhash = { prepaid_total => 0 };
 	   $prepaidhash = $pay->collect_prepaid($dbh,$ctadr);
     	   $prepaidhash->{prepaid_total} = sprintf('%.2f',$prepaidhash->{prepaid_total});
     	   $prepaidhash->{prepaid_total} =~ s/\./,/;
     	   $varenv->{cms}->{'iframe-prepaid-sum'}->{txt} =~ s/\n/<br \/>/g;
     	   $varenv->{cms}->{'iframe-prepaid-sum'}->{txt} =~ s/::prepaid_total::/<b>$prepaidhash->{prepaid_total}<\/b>/g;
	   print $q->div({-class=>'content2'}, "$varenv->{cms}->{'iframe-prepaid-sum'}->{txt}"),"\n";
	 }
	 print $q->div({-class=>'content2'}, "$varenv->{cms}->{'iframe-invoice-note'}->{txt}"),"\n";
	 print $q->div({-class=>'content2'}, "$bonus_ak"),"\n" if($R::success && $R::success eq "txt15");

     	}elsif($key =~ /barcode/){

	 if($cttpos_count){
    	  print $q->div({-style=>'padding-top:1.5em;font-weight:bold;'},"$varenv->{cms}->{'iframe-items-for-debit'}->{txt}"),"\n"; 

	  my @tpl_posorder = ("txt01=$varenv->{cms}->{'iframe-description'}->{txt}","int04=$varenv->{cms}->{'iframe-station'}->{txt}","ct_name=$varenv->{cms}->{'iframe-bike-nr'}->{txt}","int26=CO2","int02=$varenv->{cms}->{'iframe-amount'}->{txt}");

	  my $j=0;
	  my $nx=0;
	  my $sum = 0;
	  print "<div style='clear:both;'>\n";
  	  print $q->start_table({-style=>'margin:15px 0;', -border=>'0', -width=>'auto',-align=>'left', -cellpadding=>'3', -cellspacing=>'0'}),"\n";
	  print $q->Tr(),"\n";

  	  foreach my $id (sort { lc($cttpos->{$b}->{$scol}) cmp lc($cttpos->{$a}->{$scol}) } keys(%$cttpos)){
	   $j++;
	   $nx++;

  	   my $pricing = {};
   	   my $counting = {};
   	   if($cttpos->{$id}->{int35} && $cttpos->{$id}->{start_time} && $cttpos->{$id}->{end_time}){
    		($pricing,$counting) = $pri->counting_rental($varenv,$cttpos->{$id});
   	   }

	  print $q->Tr(),"\n";
          foreach (@tpl_posorder){
           my ($key,$val) = split /=/,$_;

	    my $occupied_style = "background-color:#fcfdfb;";
	    $occupied_style = "background-color:#f4f1ee;" if($nx %= 2);
	    #$occupied_style = "color:#ff1493;" if($cttpos->{$id}->{txt10} =~ /occupied|requested/);
   	    $occupied_style = "color:#ff1493;" if($cttpos->{$id}->{int10} == 2 || $cttpos->{$id}->{int10} == 3);

	   if($key eq "txt01"){
	    #print $q->td({-class=>'tdtxt', -style=>"$occupied_style"},"$cttpos->{$id}->{$key}");
	    print "<td class='tdtxt' style='$occupied_style'>\n";
	    if($cttpos->{$id}->{txt01}){
            	$cttpos->{$id}->{$key} =~ s/\<br \/\>/; &nbsp; /g;
            	print "$cttpos->{$id}->{$key}<br />\n";
	    }
	    if($pricing->{start_time} && $pricing->{end_time}){
	      $pricing->{start_time} = $lb->time4de($pricing->{start_time},"1");
	      $pricing->{end_time} = $lb->time4de($pricing->{end_time},"1");
	      my $rental_time = "";
	      $rental_time = "";#"(rental debug: $pricing->{real_clock} $pricing->{freed_time})";
	      print $q->span("&rarr; $pricing->{start_time}<br />&larr; $pricing->{end_time} $rental_time");
	    }
	    print "</td>\n";
	   }elsif($key =~ /int04/){
            if($cttpos->{$id}->{int09}){#if Tarifnr then bike
		#print $q->td({-class=>'tdint', -style=>"$occupied_style"},"Station $cttpos->{$id}->{$key}");
		print "<td class='tdtxt' style='$occupied_style'>\n";
		my $return_station = "";
		$return_station = "&larr; $cttpos->{$id}->{txt13}$cttpos->{$id}->{int04}" if($cttpos->{$id}->{txt13} && $cttpos->{$id}->{int04});
		print $q->span("$varenv->{cms}->{'iframe-station'}->{txt}<br />&rarr; $cttpos->{$id}->{txt12}$cttpos->{$id}->{int06}<br />$return_station");
		print "</td>\n";
	    }else{
	    	print $q->td({-class=>'tdint', -style=>"$occupied_style"},"$cttpos->{$id}->{$key}");
	    }
	   }elsif($key =~ /ct_name/){
            if($cttpos->{$id}->{int09}){#if Tarifnr then bike
	    	print $q->td({-class=>'tdint', -style=>"$occupied_style"},"$varenv->{cms}->{'iframe-bike'}->{txt}<br />$cttpos->{$id}->{$key}"),"\n";
	    }else{
	    	print $q->td({-class=>'tdint', -style=>"$occupied_style"},"$cttpos->{$id}->{$key}"),"\n";
	    }
	   }elsif($key eq "int26"){
	    my $co2saving = "";
	    if($cttpos->{$id}->{int26}){
	      $co2saving = "$varenv->{cms}->{'iframe-saving'}->{txt}</br>";
	      my $co2diff = $pri->co2calc($cttpos->{$id});
	      #my $sprit_price = $pri->sprit2calc($cttpos->{$id});
	      $co2saving .= "$co2diff kg CO&sup2;<br />";
	      #$co2saving .= "$sprit_price EUR<br />" if($sprit_price !~ /-/);
	      $cttpos->{$id}->{int26} =~ s/\./,/;
	      $co2saving .= "bei $cttpos->{$id}->{int26} KM";
	    }
	    print $q->td({-class=>'tdint', -style=>"$occupied_style", -nowrap=>1},"$co2saving"),"\n";
	   }elsif($key eq "int02"){
            if($cttpos->{$id}->{int35} && $cttpos->{$id}->{start_time} && $cttpos->{$id}->{end_time}){
	      my $gesamt = 0;
	      $sum += $pricing->{total_price};
	      $gesamt = $lb->round($pricing->{total_price});
	      $gesamt = sprintf('%.2f', $gesamt);
	      $gesamt =~ s/\./,/;
	      my $rabatt = "";
	      $rabatt = "$pricing->{discount}" if($pricing->{discount});
              print $q->td({-class=>'tdint', -style=>"$occupied_style", -nowrap=>1},"$rabatt $gesamt €"),"\n";
            }else{
              my $gesamt = 0;
              my $rabatt = "";
              ($gesamt,$rabatt) = $pri->price2calc($cttpos->{$id});
	      $gesamt *= -1 if($cttpos->{$id}->{template_id} && $cttpos->{$id}->{template_id} == 219);#prepaid
              $sum += $gesamt;
              $gesamt = $lb->round($gesamt);
	      $gesamt = sprintf('%.2f',$gesamt);
	      $gesamt =~ s/\./,/;
	      print $q->td({-class=>'tdint', -style=>"$occupied_style", -nowrap=>1},"$rabatt $gesamt €"),"\n";
    	    }
	   }
	  }
	  }
    	  if($j==0){
	    print $q->Tr(),"\n";
	    print $q->td({-class=>'tdint'},"$varenv->{cms}->{'iframe-no-data'}->{txt}"),"\n";
	  }else{
	    $sum = $lb->round($sum);
	    $sum = sprintf('%.2f',$sum);
	    print $q->Tr(),"\n";
	    print $q->td({-class=>'tdint', -colspan=>3},""),"\n";
	    print $q->td({-class=>'tdint'},"$varenv->{cms}->{'iframe-total'}->{txt}"),"\n";
	    print $q->td({-class=>'tdint'},$q->b("$sum €")),"\n";
	  }
	  print $q->end_table;
	  print "</div>\n";
	 }else{
	  print $q->div({-class=>'content2',-style=>'padding:0.5em 0;'}, "$varenv->{cms}->{'iframe-no-bookings'}->{txt}"),"\n";
	 }#end if $cttpos_count

	  my $i=0;
          my $dtext = "";
	  print "<div style='clear:both;'>\n";
	  foreach my $id (sort { $ctt_all->{$b}->{ct_name} cmp $ctt_all->{$a}->{ct_name} } keys(%$ctt_all)){

	  if( -f "$ctt_all->{$id}->{basedir}/pdfinvoice/Rechnung-$ctt_all->{$id}->{operator}-$ctt_all->{$id}->{ct_name}.pdf" && $ctt_all->{$id}->{ct_name} =~ /\d/ && $coo){
	     #print "$ctt_all->{$id}->{basedir}/pdfinvoice/Rechnung-$ctt_all->{$id}->{operator}-$ctt_all->{$id}->{ct_name}.pdf && $ctt_all->{$id}->{ct_name} =~ /\d/ && $coo<br />";
	     $i++;
	     my $invoice_time = $ctt_all->{$id}->{invoice_time} || $ctt_all->{$id}->{mtime};
	     $invoice_time = $lb->time4de($invoice_time,0);
             #$varenv->{operator} only defined in sharee
             my $webtarget = "_blank";
	     my $dtext = "";
             if($varenv->{syshost} =~ /app/){
               $webtarget = "_self";
               $dtext = "$varenv->{cms}->{'iframe-pdf-download-info'}->{txt}";
             }

	     if($i==1){
               print $q->div({-id=>'Rechnungen',-style=>'font-weight:bold;'},"$varenv->{cms}->{'iframe-your-invoice'}->{txt}"),"\n";
               print $q->div({-style=>'padding:0.5em 0;'},"$dtext"),"\n";
	     }
             print $q->div({-style=>'padding:0.7em 0;border:0px solid #cccccc;'},$q->a({-href=>"$ctt_all->{$id}->{wwwhost}/FileOut?file=Rechnung-$ctt_all->{$id}->{operator}-$ctt_all->{$id}->{ct_name}.pdf&sessionid=$coo", -target=>"$webtarget" , -type=>'application/octet-stream', -style=>'text-decoration:underline;'}, $q->span({-class=>"bi bi-file-earmark-pdf"}), "$varenv->{cms}->{'iframe-invoice'}->{txt} $ctt_all->{$id}->{ct_name}.pdf"), "&nbsp;&nbsp; ($invoice_time)"),"\n";
	   }

	  }
	  print "</div>\n";
       }
        #Gutschein 
        elsif($key =~  /txt16/ && $ctadr->{c_id}){
	 my $autofocus = "";
	 my $label_des="$des";
         if($R::failure =~ /^txt16/){
            $autofocus = "autofocus";
            $label_des = "<span style=color:$red>$varenv->{cms}->{'iframe-voucher-not-available'}->{txt}</span>";
         }
         elsif($R::failure =~ /conflict_txt16/){
            $autofocus = "autofocus";
            $label_des = "<span style=color:$red>$varenv->{cms}->{'iframe-voucher-deposit'}->{txt}</span>";
         }else{
            $label_des = "<span style='font-weight:normal;'>$des</span>";
         }
         print $q->label({-for=>"$key", -style=>'padding-top:1.5em;'},"$label_des"),"\n";
         print "<input id='$key' type='text' class='form-control' name='$key' value='$ctadr->{$key}' override $autofocus />\n";
        }
   }	
   print $q->div({-style=>'margin-top:1em;text-align:center;'},"<button type='submit' name='sharee_edit' value='save_account' class='btn btn-primary btn-lg btn-block' style='border:1px solid #$bgcolor1;background-color:#$bgcolor1;'>$varenv->{cms}->{'iframe-save'}->{txt}</button>"),"\n";

  print $q->div({-class=>'content2', -style=>'margin-top:2em;'}, "$varenv->{cms}->{'iframe-registration-contact-hotline'}->{txt}"),"\n";

  print "</div>\n";
  print $q->end_form,"\n";
 }

 print $q->div({-style=>'position:fixed;bottom:2%;right:2%;z-index:10;font-size:13px;'},"--> $varenv->{syshost} | $varenv->{merchant_id} | $bgcolor1 | template -> $node_meta->{tpl_name},$tpl_id"),"\n" if($ctadr->{c_id} eq $dbt->{copri_conf}->{superu_id} || $dbt->{copri_conf}->{stage} eq "test");

  print "</div>";
}
1;
