#!/usr/bin/perl 
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
#managed text by operator cms
#
#Example
#./src/scripts/mailTransportcms.pl 'shareedms-operator' 'send_alarm2hotline' '[user.c_id]' '[contenttxxxx.c_id]'
#./src/scripts/mailTransportcms.pl 'shareedms-operator' 'send_invoice_cms' '[user.c_id]' '[contenttxxxx.c_id]' '' '[cmstext_select]' '[with_pdf]'
#
#
#
use vars qw($syshost);

BEGIN {
  $syshost = $ARGV[0] || die 'syshost not defined';
}

use lib "/var/www/copri-bike/$syshost/src";

use strict;
use warnings;
use utf8;
use Encode;
use POSIX;
use DateTime;
use DateTime::Format::Pg;
use Scalar::Util qw(looks_like_number);
use Lib::Config;
use Mod::DBtank;
use Mod::MailTransport;
use Data::Dumper;
my $cf = new Config;
my %varenv = $cf->envonline();

my $dbt = new DBtank;
my $mailtrans = new MailTransport;
my $now_dt = strftime "%Y.%m.%d %H:%M:%S", localtime;

#one contentadr.c_id OR email on command
my $todo = $ARGV[1] || "";
my $adr_id = $ARGV[2] || "";
my $ct_id = $ARGV[3] || "";
my $temppw = $ARGV[4] || "";
my $cmstext_select = $ARGV[5] || "";
my $with_pdf = $ARGV[6] || "";
my $app_name = $ARGV[7] || "";

open(EMA, ">> $dbt->{copri_conf}->{logdir}/mailTransportcms.log");
print EMA "\n$now_dt, start mailTransportcms.pl syshost: $syshost, todo:$todo, adr_id:$adr_id, ct_id:$ct_id, temppw:$temppw, cmstext_select:$cmstext_select, with_pdf:$with_pdf\n";


#mailxcfg is shareeconf/mailx.cfg <block> selection!
#hash data to send
my $sendref = { 
	mailxcfg => "mailx_default",
	#mailxcfg => "mailx_admin",#just for tests
	syshost => "$syshost",
	mail_from  => "",
	mail_to  => "",
	mail_bcc  => "",
	c_id => 0,
	subject => "",
	message => "",
	signature => "",
	attachment => "",
};

my $oprefix = $dbt->{operator}->{$varenv{dbname}}->{oprefix} || "";
my $sendmail = {};

#user-account must be exist to send user message
my $ctadr = { c_id => 0 };
if(looks_like_number($adr_id)){
  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");
  my $pref_adr = {
     table => "contentadr",
     fetch => "one",
     c_id => "$adr_id",
  };
  $ctadr = $dbt->fetch_tablerecord($dbh_primary,$pref_adr);

 #send_invoice
 if($todo eq "send_invoice" && looks_like_number($ct_id)){
  $sendref->{mailxcfg} = "mailx_invoice";
  $sendmail = send_invoice($todo,$sendref,$ctadr,$ct_id,"email-invoice",$with_pdf);
 }

 #send_invoice_cms
 if($todo eq "send_invoice_cms" && looks_like_number($ct_id) && $cmstext_select){
  $sendref->{mailxcfg} = "mailx_invoice_bcc";#with BCC
  $sendmail = send_invoice($todo,$sendref,$ctadr,$ct_id,$cmstext_select,$with_pdf);
 }

 #send_payonelink
 if($todo eq "send_payonelink"){
  $sendmail = send_payonelink($todo,$sendref,$ctadr,$ct_id,$cmstext_select,$app_name);
 }

 #send_emailack
 if($todo eq "send_emailack"){
  $sendmail = send_emailack($todo,$sendref,$ctadr);
 }

 #send_password
 if($todo eq "send_password"){
  $sendmail = send_password($todo,$sendref,$ctadr,$temppw);
 }

 #send_cpdate_message, done by cronjob cpdate_check.pl
 if(($todo eq "send_cpupdate_message" || $todo eq "send_proactive_cpupdate_message")){
  $sendmail = send_cpupdate_message($todo,$sendref,$ctadr);
 }

}#end user-account message

#send_alarm2hotline, done by Ilockit_cloud.pl
if($todo eq "send_alarm2hotline" && looks_like_number($ct_id)){
  $sendmail = send_alarm2hotline($sendref,$ct_id);
}

#send_occupied2hotline 78h, done by cronjob
if($todo eq "send_occupied2hotline"){
  $sendmail = send_occupied2hotline($sendref);
}

#final send
if(ref($sendmail) eq "HASH" && $sendmail->{c_id}){
  sendmailjob($sendmail);
}else{
  print EMA "Error, can not sendmailjob without c_id\n";
}


#user messaging for all operators by one cronjob
if($todo eq "send_invoice_onwork" || $todo eq "email_longterm_occupied"){
 $sendref->{mailxcfg} = "mailx_invoice";
 #loop operators DB
 while (my ($key, $op_name) = each %{ $dbt->{operator} }) {
  if($op_name->{database}->{dbname}){
   my $rows = 0;
   my $sharee_operator = $op_name->{database}->{dbname};
   my $dbh = "";
   $dbh = $dbt->dbconnect_extern($sharee_operator,"iso-8859-1");
 
   $oprefix = $op_name->{oprefix} || "";
   $sendref->{syshost} = "$syshost";

   #send_invoice_onwork once a week as reminder [in Arbeit|eMail gesendet]
   if($todo eq "send_invoice_onwork"){
   	$sendmail = send_invoice_onwork($dbh,$oprefix,$sendref);
   }

   #email_longterm_occupied, done by cronjob (enhance/substitute sms_message 24h_occupied job)
   if($todo eq "email_longterm_occupied"){
  	$sendmail = email_longterm_occupied($dbh,$oprefix,$sendref);
   }

   #final send
   if(ref($sendmail) eq "HASH" && $sendmail->{c_id}){
      sendmailjob($sendmail);
   }
  }
 }
}#end user messaging for all operators by one cronjob

#send_invoice
sub send_invoice {
  my $todo = shift || "";
  my $sendref = shift || {};
  my $ctadr = shift || {};
  my $ct_id = shift || "";
  my $cms_message_key = shift || "email-invoice";
  my $with_pdf = shift || "";
  my $lang = $ctadr->{txt11} || $ctadr->{txt10};

  my $dbh = $dbt->dbconnect_extern($dbt->{operator}->{$varenv{dbname}}->{database}->{dbname},"iso-8859-1");
  my $project = $dbt->{operator}->{$varenv{dbname}}->{project} || "";
  $varenv{cms} = $dbt->fetch_cms($dbh,{ lang => $lang });

  if(!$varenv{cms}->{$cms_message_key}->{txt}){
    exit 1;
  }

  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "100002",
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh,$pref_ctu);

  my $fetchctt = {
     table => "contenttrans",
     fetch => "one",
     c_id => "=::$ct_id",
  };
  my $ctt = { c_id => 0 };
  $ctt = $dbt->fetch_tablerecord($dbh,$fetchctt);
  $ctt->{fibu_user} = "";
  if($ctt->{owner} > 1000){
      my $adref = {
          table           => "contentadr",
          fetch           => "one",
          template_id     => "202",
          c_id          => $ctt->{owner},
      };
      my $fibu_owner = $dbt->fetch_record($dbh,$adref);
      $ctt->{fibu_user} = "$fibu_owner->{txt01}" if($fibu_owner->{txt01});
  }

  my $ctadr_invoice = $ctt;#take adr from invoice for account-less mailing
  $sendref = $mailtrans->prepare_content(\%varenv,$sendref,$ctadr_invoice,$uadr,$ctt,$varenv{cms}->{$cms_message_key}->{txt},$with_pdf);

   my $updatectt = {
                table   =>      "contenttrans",
                c_id    =>      "$ct_id",
   };
   my $log_stamp = strftime "%d.%m.%Y %H:%M:%S", localtime;
   my $mailing_log = $ctt->{txt30} . "\n- $log_stamp mailing: $cms_message_key";
   $dbt->update_one($dbh,$updatectt,"txt30='$mailing_log'");

  return $sendref;
}#end send_invoice

#send_payonelink
sub send_payonelink {
  my $todo = shift;
  my $sendref = shift;
  my $ctadr = shift;
  my $ctpos_id = shift;
  my $cms_message_key = shift || "";
  my $app_name = shift || "";

  my $lang = $ctadr->{txt11} || $ctadr->{txt10};

  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");
  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh_primary,$pref_ctu);

  $varenv{cms} = $dbt->fetch_cms($dbh_primary,{ lang => $lang });

  my $pref_pos = {
        table   => "contenttranspos",
        fetch   => "one",
        ca_id   => "$ctadr->{c_id}",
        c_id => "$ctpos_id",
  };
  my $record_pos = { c_id => 0 };
  $record_pos = $dbt->fetch_tablerecord($dbh_primary,$pref_pos) if($ctpos_id);

  $sendref = $mailtrans->prepare_content(\%varenv,$sendref,$ctadr,$uadr,$record_pos,$varenv{cms}->{$cms_message_key}->{txt},'',$app_name);

  my $update_pos = {
                table   =>      "contenttranspos",
                c_id    =>      "$ctpos_id",
   };
   my $log_stamp = strftime "%d.%m.%Y %H:%M", localtime;
   my $mailing_log = $record_pos->{txt25} . "\n- $log_stamp mailing: $cms_message_key";
   $dbt->update_one($dbh_primary,$update_pos,"txt25='$mailing_log'");

  return $sendref;
}#end send_payonelink


#send_emailack
sub send_emailack {
  my $todo = shift;
  my $sendref = shift;
  my $ctadr = shift;
  my $lang = $ctadr->{txt11} || $ctadr->{txt10};

  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");
  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh_primary,$pref_ctu);

  $varenv{cms} = $dbt->fetch_cms($dbh_primary,{ lang => $lang });
  my $cms_message_key = "email-emailack";

  #Ack digest
  if($ctadr->{txt34} =~ /^(.{5})/){
    $ctadr->{txt34} = $1;
  }else{
    $ctadr->{txt34} = "";
  }

  $sendref = $mailtrans->prepare_content(\%varenv,$sendref,$ctadr,$uadr,"",$varenv{cms}->{$cms_message_key}->{txt});

  return $sendref;
}#end send_emailack

#send_password
sub send_password {
  my $todo = shift;
  my $sendref = shift;
  my $ctadr = shift;
  my $temppw = shift;
  my $lang = $ctadr->{txt11} || $ctadr->{txt10};

  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");
  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh_primary,$pref_ctu);

  $varenv{cms} = $dbt->fetch_cms($dbh_primary,{ lang => $lang });
  my $cms_message_key = "email-temppassword";

  #temp pw 
  if($temppw){
    $ctadr->{txt04} = $temppw;
  }else{
    $ctadr->{txt04} = "";
  }

  $sendref = $mailtrans->prepare_content(\%varenv,$sendref,$ctadr,$uadr,"",$varenv{cms}->{$cms_message_key}->{txt});

  return $sendref;
}#end send_password

#send_cpupdate_message
sub send_cpupdate_message {
  my $todo = shift;
  my $sendref = shift;
  my $ctadr = shift || {};
  my $lang = $ctadr->{txt11} || $ctadr->{txt10};

  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");

  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh_primary,$pref_ctu);

  $varenv{cms} = $dbt->fetch_cms($dbh_primary,{ lang => $lang });
  my $cms_message_key = "email-cpupdate-message";
  $cms_message_key = "email-proactive-cpupdate-message" if($todo eq "send_proactive_cpupdate_message");
  $sendref = $mailtrans->prepare_content(\%varenv,$sendref,$ctadr,$uadr,"",$varenv{cms}->{$cms_message_key}->{txt});

  return $sendref;
}#end send_cpupdate_message



#send_alarm2hotline
sub send_alarm2hotline {
  my $sendref = shift;
  my $ct_id = shift || "";

  my $dbh = $dbt->dbconnect_extern($dbt->{operator}->{$varenv{dbname}}->{database}->{dbname},"iso-8859-1");
  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh,$pref_ctu);
  $sendref->{mail_to} = $uadr->{txt08};
  
  #without cms
  my $cms_prim = { c_id => 0, txt01 => 'Folgendes Mietrad hat einen Diebstahlalarm ausgelöst' };

  my $pref_ct = {
     table => "contenttheftpos",
     fetch => "one",
     c_id => $ct_id,
  };

  my $ct = { c_id => 0 };
  $ct = $dbt->fetch_tablerecord($dbh,$pref_ct);

  $sendref->{c_id} = $ct->{c_id};
  $sendref->{subject} = "Diebstahlalarm $oprefix$ct->{barcode}";

$sendref->{message} = <<EOF
  $cms_prim->{txt01} 

  Bike: $oprefix$ct->{barcode} 
  Speed: $ct->{int07} 
  Meter: $ct->{int08} 
  GPS: $ct->{txt06} 
  Timestamp: $ct->{start_time}
 
  Öffne das Alarmjournal für weitere Informationen:
  <a href='$dbt->{operator}->{$varenv{dbname}}->{operatorDMS}/DMS/Alarmjournal'>$dbt->{operator}->{$varenv{dbname}}->{operatorDMS}/DMS/Alarmjournal</a>

  Freundliche Grüße,
  -- 
  $uadr->{txt01}
  $uadr->{txt03}
  $uadr->{txt06}

  $uadr->{txt84}

EOF
;

  $sendref->{message}  =~ s/\n/\<br \/\>/g;
  return $sendref;
}#end send_alarm2hotline

#send_occupied2hotline
sub send_occupied2hotline {
  my $sendref = shift;
  my $ct_id = shift || "";

  my $dbh = "";
  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh,$pref_ctu);
  $sendref->{mail_to} = $uadr->{txt08};
  
  my $search = {
        table_pos  => "contenttranspos",
        int10  => 3,
	#int33  => 3,#marker for sending 3. SMS
	int34  => "null",#not staff
        start_time_interval => "(now() - interval '78 hour')",
  };

  my $cttpos = { c_id => 0 };
  $cttpos = $dbt->collect_transpos($dbh,$search,0);

  my $bike = "";
  foreach my $pid (sort { $cttpos->{$b}->{end_time} cmp $cttpos->{$a}->{end_time} } keys(%$cttpos)){

	$bike .= $oprefix . $cttpos->{$pid}->{barcode} . "\n";
	$sendref->{c_id} = $cttpos->{$pid}->{cc_id};#just one
	print "$bike $sendref->{c_id}";

  }

  if($bike){
    $bike =~ s/,$//;
    $sendref->{subject} = "konrad über 78 Stunden occupied";

$sendref->{message} = <<EOF
   Hallo,

   folgende konräder sind seit über 3 Tagen gemietet:

   $bike
   Bitte MieterInnen kontaktieren und den verbleib klären.

   Grüße vom cron

EOF
;

    $sendref->{message}  =~ s/\n/\<br \/\>/g;
    return $sendref;
  }
 return;
}


#send_invoice_onwork, done by operaor loop
sub send_invoice_onwork {
  my $dbh = shift;
  my $oprefix = shift || ""; 
  my $sendref = shift;

  my $dbh_primary = $dbt->dbconnect_extern($dbt->{primary}->{sharee_primary}->{database}->{dbname},"iso-8859-1");

  my $pref_ctu = {
     table => "contentuser",
     fetch => "one",
     c_id => "1",#primary hotline
  };
  my $uadr = { c_id => 0 };
  $uadr = $dbt->fetch_tablerecord($dbh_primary,$pref_ctu);
  #$sendref->{mail_to} = $uadr->{txt08};
  $sendref->{mail_to} = $sendref->{mail_from};#yes, delivering to $sendref->{mailxcfg} = "mailx_invoice";
  
  my $pref = {
        table  => "contenttrans",
        fetch  => "all",
        keyfield => "c_id",
        txt22  => "IN::('in Arbeit','eMail gesendet')",
	state  => "is::null",
  };

  my $ctt = $dbt->fetch_tablerecord($dbh,$pref);

  my $ct_onwork = "";
  foreach my $id (sort { $ctt->{$b}->{c_id} <=> $ctt->{$a}->{c_id} } keys(%$ctt)){

	$ct_onwork .= $oprefix . " Faktura ID:$ctt->{$id}->{c_id}, " . " Nummer: " . $ctt->{$id}->{ct_name} . "\n";
	$sendref->{c_id} = $ctt->{$id}->{c_id};#just one
	print "$ctt->{$id}->{c_id}: $ct_onwork $sendref->{c_id}";

  }

  if($ct_onwork){
    $ct_onwork =~ s/,$//;
    $sendref->{subject} = "$oprefix wöchentliche Faktura in Arbeit Übersicht";

$sendref->{message} = <<EOF
   Hallo,

   folgende ungebuchte Rechnungen haben den Status "in Arbeit" oder "eMail gesendet":

   $ct_onwork
   Nicht aus dem Blick verlieren.

   Grüße vom cron

EOF
;

    $sendref->{message}  =~ s/\n/\<br \/\>/g;
    return $sendref;
  }
 return;
}#end send_invoice_onwork


#sending mail job
sub sendmailjob {
 my $sendref = shift || "";
 my $dbh = "";

 #at first connect mailxchanger by mailx.cfg config
 my ($smtp,$mailxconf) = $mailtrans->mail_connect($sendref);

 #one mailing with mail address on command
 if($sendref->{mail_to} =~ /\w\@\w/ && $sendref->{subject} && $sendref->{message}){
  my $ret = "";
  $ret = $mailtrans->mail_transport($smtp,$mailxconf,$sendref);

  print EMA "done mailing with state to $sendref->{mail_to}: $ret\n";
  print EMA Dumper($sendref);
 }else{
  print EMA "Error, no or false email:\n$sendref->{mail_to}\n$sendref->{subject}\n$sendref->{message}, exit\n";
 }
}

print EMA "\n\n";
close EMA;

