#!/usr/bin/perl 
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
#Generates CSV for amount channels and start-station/end-station and Nuter Registrierung 
#
#csv/Statistik-Allnewuser_amount_*
#csv/Statistik-channel_amount_*
#csv/Statistik-start_end_station_*
#csv/Statistik-Bonusnewuser_amount_*
#
#
#Examples
#./src/scripts/statistik_amountCSV_files.pl shareedms-operator '' '' '300103'"
#
#with start_time and end_time
#./src/scripts/statistik_amountCSV_files.pl shareedms-operator '2022-01-01' '2022-02-01' '300101'"
#./src/scripts/statistik_amountCSV_files.pl shareedms-operator '2022-01-01' '2022-02-01' '300103'"
#
use vars qw($syshost);

BEGIN {
  $syshost = $ARGV[0] || exit 1;
}

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

my $start_itime = $ARGV[1] || "";
my $end_itime = $ARGV[2] || "";

#2022-08-03 changed $bikesys int12 select to $bike_type_id int29
my $bike_type_id = $ARGV[3] || "";
my $flotte_type = "";
if($bike_type_id == 300101){
  $flotte_type = "Lastenrad";
}elsif($bike_type_id == 300103){
  $flotte_type = "Stadtrad";
}else{
  print "Failure, bike_type_id must be nodes.type_id number of Flot\n\n";
  exit 1;
}


use strict;
use warnings;
use utf8;
use POSIX;
use CGI ':standard';
use Lib::Config;
use Mod::DBtank;
use Scalar::Util qw(looks_like_number);
use DateTime;
use DateTime::Format::Pg;
use Text::CSV_XS;
use Sys::Hostname;
my $hostname = hostname;

use Mod::Libenz;
use Mod::Pricing;
use Mod::APIfunc;

use Data::Dumper;

my $q = new CGI;
my $cf = new Config;
my %varenv = $cf->envonline();
#print "host: $varenv{wwwhost}\n";
my $dbt = new DBtank;
my $lb = new Libenz;
my $pri = new Pricing;
my $apif = new APIfunc;

my $dbh = $dbt->dbconnect();

my $dt1 = DateTime->now(time_zone  => 'Europe/Berlin');
if(!$end_itime){
  $end_itime = $dt1;
}

if(!$start_itime){
  $start_itime = $dt1->clone->add(months => -1, end_of_month => 'preserve');
}

my $month = $1 if($start_itime =~ /\d{4}-(\d{2})-\d{2}/);
$month = sprintf('%.2d',$month);
my $year = $1 if($start_itime =~ /(\d{4})-\d{2}-\d{2}/);


my $channel_map = $dbt->channel_map();
my $channel = "ALL";

my $new_reg=0;
my $swk_reg=0;
my $swk_i=0;

#collect new users in time-range
my $adr_search = {
                table           => "contentadr",
		fetch           => "all",
        	keyfield        => "c_id",
		int09		=> "is::null", #not Service App staff
                start_itime     => ">=::$start_itime",
                end_itime       => "<::$end_itime",
        };
my $adr = $dbt->fetch_tablerecord($dbh,$adr_search);


foreach my $id (sort { $adr->{$a}->{itime} cmp $adr->{$b}->{itime} }keys (%$adr)){
	#mailAck && smsAck 
	if($adr->{$id}->{int04} && $adr->{$id}->{int04} == 1 && $adr->{$id}->{int13} && $adr->{$id}->{int13} == 1){

 	$new_reg++;

	 #New SWK Bonus registrations
	 if($adr->{$id}->{txt15} && $adr->{$id}->{txt15} =~ /\d+/){
	   $swk_reg++;
	 }
	}
}

 #fetch all stations
 my $pref = {
        table           => "content",
        fetch           => "all",
        keyfield        => "int04",
        main_id         => "=::300016",
	template_id     => "225",
	int04		=> "!=::99",#virtual station
        int10           => "1", #available
        int09           => "is::null", #not Contributor-Archive
        };
 my $station_rec = $dbt->fetch_record($dbh,$pref);


#Statistik-start_end_station
my $csv_start_station = Text::CSV_XS->new ({ binary => 1, sep_char => ";", eol => "\r\n" });
my $filename_start_station = "Statistik-start_end_station_$year-$month-$flotte_type.csv";
open my $sstation, ">", "$varenv{csv}/$filename_start_station" or die "$filename_start_station: $!\n";
my @start_station = ("$year-$month Station","Menge Anmietungen/Rueckgaben");
$csv_start_station->print($sstation, \@start_station);#$start_station CSV header

#Statistik-channel_amount
my $csv_amount = Text::CSV_XS->new ({ binary => 1, sep_char => ";", eol => "\r\n" });
my $filename_amount = "Statistik-channel_amount_$year-$month-$flotte_type.csv";
open my $aamount, ">", "$varenv{csv}/$filename_amount" or die "$filename_amount: $!\n";
my @amount = ("$year-$month $flotte_type","Menge");
$csv_amount->print($aamount, \@amount);#$amount CSV header:

#Statistik-Allnewuser_amount
my $csv_allamount = Text::CSV_XS->new ({ binary => 1, sep_char => ";", eol => "\r\n" });
my $filename_allamount = "Statistik-Allnewuser_amount_$year-$month.csv";
open my $allaamount, ">", "$varenv{csv}/$filename_allamount" or die "$filename_allamount: $!\n";
my @allamount = ("$year-$month Gesamtanzahl Neuregistrierungen","Menge");
$csv_allamount->print($allaamount, \@allamount);#$allamount CSV header:
$csv_allamount->print($allaamount, ["neue NutzerInnen","$new_reg"]);
print "Neue NutzerInnen: $new_reg\n";

#Statistik-Bonusnewuser_amount
my $csv_swkamount = Text::CSV_XS->new ({ binary => 1, sep_char => ";", eol => "\r\n" });
my $filename_swkamount = "Statistik-Bonusnewuser_amount_$year-$month.csv";
open my $swkaamount, ">", "$varenv{csv}/$filename_swkamount" or die "$filename_swkamount: $!\n";
my @swkamount = ("$year-$month Gesamtanzahl Neuregistrierungen Bonusnummer","Menge");
$csv_swkamount->print($swkaamount, \@swkamount);#$swkamount CSV header:
$csv_swkamount->print($swkaamount, ["neue NutzerInnen mit Bonus Tarif","$swk_reg"]);
print "Neue NutzerInnen mit Bonus Tarif: $swk_reg\n";

  my $sum_minutes=0;
  my $sum_hours=0;
  my $pricing = {};
  my $counting = {};
  my $diff_station = 0;

  #station hash init
  my $start_station = {};
  my $end_station = {};
  foreach my $int04_id (sort { $station_rec->{$a}->{int04} <=> $station_rec->{$b}->{int04} } keys (%$station_rec)){
  	$start_station->{$int04_id} = 0;
  	$end_station->{$int04_id} = 0;
  }

  my $pos_search = {
                table           => "contenttranspos",
		fetch           => "all",
        	keyfield        => "c_id",
		int05		=> "is::null",#not if sub workflow doc
		int06           => "!=::99",#virtual start-station
		int29		=> "$bike_type_id",#nodes.type_id 
		int34		=> "is::null",#not if staff 
                start_itime     => ">=::$start_itime",
                end_itime       => "<::$end_itime",
        };
  my $pos = $dbt->fetch_tablerecord($dbh,$pos_search);

  #Loop rental positions alias Mietjournal
  foreach my $id (sort { $pos->{$a}->{mtime} cmp $pos->{$b}->{mtime} }keys (%$pos)){

      ($pricing->{$id},my $counting) = $pri->counting_rental(\%varenv,$pos->{$id});

      #umsatz by tarif-nr in int09
      if($pos->{$id}->{template_id} && $pos->{$id}->{template_id} == 205 && $pos->{$id}->{int09} && $pos->{$id}->{int35} && $pos->{$id}->{int10} == 1 && $pricing->{$id}->{rentalog}->{rental_minute_all} && $pricing->{$id}->{rentalog}->{rental_minute_all} > 0){

	 #if sharing type public-bonus = 5
	 if($pos->{$id}->{int18} && $pos->{$id}->{int18} == 5){
	 	$swk_i++;
	 }

	 $start_station->{$pos->{$id}->{int06}} += 1 if($pos->{$id}->{int06} && exists($start_station->{$pos->{$id}->{int06}}));
	 $end_station->{$pos->{$id}->{int04}} += 1 if($pos->{$id}->{int04} && exists($start_station->{$pos->{$id}->{int04}}));
	 $diff_station += 1 if($pos->{$id}->{int06} && $pos->{$id}->{int04} && $pos->{$id}->{int06} != $pos->{$id}->{int04});

         $sum_minutes += $pricing->{$id}->{rentalog}->{rental_minute_all};
      }
  }#end Loop rental

  #Service pos
  my $pos_partref = {
                table           => "contenttranspos",
		fetch           => "all",
        	keyfield        => "c_id",
		int05		=> "is::null",#not if sub workflow doc
		start_itime	=> ">=::$start_itime",
		end_itime	=> "<::$end_itime",
        };
  my $pos_part = $dbt->fetch_tablerecord($dbh,$pos_partref);

  $sum_hours = $sum_minutes / 60 if($sum_minutes > 0);
  $sum_hours = sprintf('%.2f',$sum_hours);
  $sum_hours =~ s/\./,/;
  $csv_amount->print($aamount, ["Gesamtnutzungsstunden im Gesamtsystem","$sum_hours"]);
  print "Gesamtnutzungsstunden im Gesamtsystem: $sum_hours\n";

  my $count_start = 0;
  foreach my $stid (sort { $a <=> $b } (keys (%$start_station))){
	$count_start += $start_station->{$stid};
        my @start_station_line = ("start-Station $stid","$start_station->{$stid}");
        $csv_start_station->print($sstation, \@start_station_line);#foreach line
  }
  print "Count start_station: $count_start\n";

  my $count_end = 0;
  foreach my $stid (sort { $a <=> $b } (keys (%$end_station))){
	$count_end += $end_station->{$stid};
        my @end_station_line = ("end-Station $stid","$end_station->{$stid}");
        $csv_start_station->print($sstation, \@end_station_line);#foreach line
  }
  print "Count end_station: $count_end\n";

  $csv_amount->print($aamount, ["APP Anmietungen","$count_start"]);
  print "APP Anmietungen: $count_start\n";

  $csv_amount->print($aamount, ["Gesamtanzahl Anmietungen im Gesamtsystem","$count_start"]);
  print "Gesamtanzahl Anmietungen im Gesamtsystem: $count_start\n";


  $csv_amount->print($aamount, ["One-Way-Fahrten","$diff_station"]);
  print "\nAnteil One-Way-Fahrten: $diff_station\n";

  if($swk_i){
    $csv_amount->print($aamount, ["Anmietungen mit Bonusnummer","$swk_i"]);
    print "Anmietungen mit Bonusnummer: $swk_i\n";
  }


