#!/usr/bin/perl
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
# velofaktur per REST JSON Payload with Bearer Token
#
#Examples
# Abrufen einer Liste mit Stationen, Anzahl Slots + Name
# ./src/scripts/velofaktur_client.pl shareedms-operator get_velo
#
# bike ID Statusabfrage | Freigeben
# ./src/scripts/velofaktur_client.pl shareedms-operator post_velo 8 1 200008 Statusabfrage 
# will be sent by booking_update $lock_state eq "unlocked"
# ./src/scripts/velofaktur_client.pl shareedms-operator post_velo 8 1 200008 Freigeben "$record_pos->{c_id}" 
#
use vars qw($syshost);

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

use lib "/var/www/copri-bike/$syshost/src";
use strict;
use warnings;
use POSIX;
use CGI;
use JSON;
use LWP::UserAgent;
use DateTime;
use Time::Piece;
use Lib::Config;
use Mod::DBtank;
use Mod::Basework;
use Data::Dumper;

my $q = new CGI;
my $cf = new Config;
my $dbt = new DBtank;
my $bw = new Basework;
my $lang = "de";
my $now_dt = strftime "%Y-%m-%d %H:%M:%S", localtime;

my $api_file = "/var/www/copri4/shareeconf/apikeys.cfg";
my $aconf = Config::General->new($api_file);
my %apikeyconf = $aconf->getall;
#print $apikeyconf{velofaktur}->{bearer};

my $ua = LWP::UserAgent->new;
$ua->agent("sharee veloclient");
my $size = $ua->max_size;
my $bytes = 100000;
$ua->max_size( $bytes );
$ua->default_header( 'Authorization' => $apikeyconf{velofaktur}->{bearer} );

my $json = JSON->new->allow_nonref;
my %varenv = $cf->envonline($syshost);
my $response_in = {};
my $dbh = "";
my $owner = 182;

my $todo = $ARGV[1];
my $Station = $ARGV[2] || "";
my $Slot = $ARGV[3] || "";
my $velo_id = $ARGV[4] || "";
my $Befehl = $ARGV[5] || "";
my $posc_id = $ARGV[6] || "";

open(FILE,">>$varenv{logdir}/APIvelo.log");
print FILE "\n*** $now_dt 'sharee veloclient' \n";

&get_velo if($todo eq "get_velo");
sub get_velo {

 #my $endpoint = "https://shareeapp-primary.copri-bike.de/APIvelo";
 my $endpoint = "https://cockpit.velofactur.de/api/portal/station";

   my $rest_json = "";
   my $ret_json = getvelo_cloud("","$endpoint",$rest_json);
   eval {
     $response_in = decode_json($ret_json);
     print FILE "<--- velofactur response_in:\n" . Dumper($response_in);
   };
   if ($@){
     print FILE "<--- failure  get_velo raw response_in:\n" . Dumper($ret_json) . "\n";
     warn $@;
   }

}

#velofaktur http request
sub getvelo_cloud {
 my $self = shift;
 my $veloserver = shift || "";
 my $rest_json = shift || "";
 my $velo_request = "$veloserver";

 print FILE "===> GET2velo >> " . $velo_request . "\n" . $rest_json . "\n";

 my $req = HTTP::Request->new(GET => "$velo_request");
 $req->content_type('application/json');

 $req->content($rest_json);

 my $res = $ua->request($req);
 if ($res->is_success) {
  #print $res->content;
  return $res->content;
  print $res->status_line, "\n";
 }else {
  print $res->status_line, "\n";
 }
}
#end if($todo eq "get_velo"){

&post_velo($Station,$Slot,$velo_id,$Befehl,$posc_id) if($todo eq "post_velo");
sub post_velo {
  my $Station = shift;
  my $Slot = shift;
  my $velo_id = shift;
  my $Befehl = shift;

  #local TEST
  my $endpoint = "https://shareeapp-fr01.copri-bike.de/APIvelo";
  #LIVE
  #my $endpoint = "https://cockpit.velofactur.de/api/portal/befehl";


	my %json;
	$json{Station} = "$Station";
	$json{Slot} = "$Slot";
	$json{Id} = "$velo_id";
	$json{Befehl} = "$Befehl";
	my $rest_json = encode_json(\%json);

	print FILE "rest_json:\n" . Dumper($rest_json) . "\n";

   my $ret_json = post2velo_cloud("","$endpoint",$rest_json);
   #
   eval {
     $response_in = decode_json($ret_json);
     print FILE "<--- velofaktur response_in:\n" . Dumper($response_in);
     print $ret_json . "\n";

     my $record_cc = { c_id => 0 }; 
     if($velo_id && $velo_id > 0){
      my $pref_cc = {
        table           => "content",
        fetch           => "one",
        template_id     => "205",
        int27         => $velo_id,
        };

        $record_cc = $dbt->fetch_record($dbh,$pref_cc);
        my $update_cc = {
                table   =>      "content",
                mtime   =>      "now()",
                owner   =>      "$owner",
        };
        $dbt->update_record($dbh,$update_cc,$record_cc) if($record_cc->{c_id});
        $bw->log("update content velofactur response Status for bike $velo_id $record_cc->{barcode} $response_in->{status}",$update_cc,"");
     }

     my $record_pos = { c_id => 0 }; 
     if($posc_id && $posc_id > 0){
      my $pref_pos = {
        table           => "contenttranspos",
        fetch           => "one",
        c_id	        => $posc_id,
        };

        $record_pos = $dbt->fetch_record($dbh,$pref_pos);

        my $update_pos = {
                table   =>      "contenttranspos",
                mtime   =>      "now()",
                owner   =>      "$owner",
        };
        $update_pos->{int27} = $velo_id if($velo_id);
        $update_pos->{30} = $Station if($Station);
        $update_pos->{31} = $Slot if($Slot);
        $dbt->update_record($dbh,$update_pos,$record_pos) if($record_pos->{c_id});
        $bw->log("update contenttranspos velofactur response Status for bike $velo_id $record_pos->{barcode} $response_in->{status}",$update_pos,"");
     }


   };
   if ($@){
     print FILE "<--- failure post_velo raw response_in:\n" . Dumper($ret_json) . "\n";
     warn $@;
   }

}#end if($todo eq "post_velo"){


#velofaktur http POST request
sub post2velo_cloud {
 my $self = shift;
 my $veloserver = shift || "";
 my $rest_json = shift || "";
 my $velo_request = "$veloserver";

 print FILE "===> POST2velo >> " . $velo_request . "\n" . $rest_json . "\n";

 my $req = HTTP::Request->new(POST => "$velo_request");
 $req->content_type('application/json');

 $req->content($rest_json);

 my $res = $ua->request($req);
 if ($res->is_success) {
  #print $res->content;
  return $res->content;
  print $res->status_line, "\n";
 }else {
  print $res->status_line, "\n";
 }
}

close(FILE);

