#!/usr/bin/perl 
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
#./src/scripts/statistik_dailystation.pl shareedms-operator"
#
#
use vars qw($syshost);

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

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

use strict;
use warnings;
use POSIX;
use CGI ':standard';
use Lib::Config;
use Scalar::Util qw(looks_like_number);
use DateTime;
use DateTime::Format::Pg;
use Mod::DBtank;
use Data::Dumper;

my $q = new CGI;
my $cf = new Config;
my $dbt = new DBtank;

my $dbh = "";
my $now_dt = strftime "%Y-%m-%d", localtime;

   my $pref_st = {
        table           => "content",
        fetch           => "all",
        keyfield        => "int04",
        template_id     => "225",
   };
   my $ct4rel_st = $dbt->fetch_record($dbh,$pref_st);

   my $pref_bi = {
        table           => "content",
        fetch           => "all",
        keyfield        => "barcode",
        template_id     => "205",
   };
   my $ct4rel = $dbt->fetch_record($dbh,$pref_bi);

my $station_bikes = {};

#foreach station
foreach my $st (sort { $ct4rel_st->{$a}->{int04} <=> $ct4rel_st->{$b}->{int04} } keys (%$ct4rel_st)){
    $station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes} = "";
    $station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes} = "";

    #foreach bike
    foreach my $cpid (sort { $ct4rel->{$a}->{barcode} <=> $ct4rel->{$b}->{barcode} } keys (%$ct4rel)){
      if(($ct4rel->{$cpid}->{barcode} && $ct4rel->{$cpid}->{barcode} > 0) && ($ct4rel->{$cpid}->{int04} && $ct4rel_st->{$st}->{int04} == $ct4rel->{$cpid}->{int04})){

	if($ct4rel->{$cpid}->{int10} && $ct4rel->{$cpid}->{int10} =~ /1|2|3/){
	  $station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes} .= "$ct4rel->{$cpid}->{barcode},";
	}elsif($ct4rel->{$cpid}->{int10} && $ct4rel->{$cpid}->{int10} =~ /4|5/){
	  $station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes} .= "$ct4rel->{$cpid}->{barcode},";
	}

      }
    }
    $station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes} =~ s/,$// if($station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes});
    $station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes} =~ s/,$// if($station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes});

	print "Registered on station: $ct4rel_st->{$st}->{int04} --> bikes_on: $station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes} --> bikes_off: $station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes}\n";
	my $sethash = {
			station => $ct4rel_st->{$st}->{int04},
			bikes_on => "$station_bikes->{$ct4rel_st->{$st}->{int04}}->{on}->{bikes}",
			bikes_off => "$station_bikes->{$ct4rel_st->{$st}->{int04}}->{off}->{bikes}",
			};
	$dbt->insert_contenthash($dbh,"statistik",$sethash);
}

