#!/usr/bin/perl -w

use strict;
use DBI;
use Data::Dump qw/dump/;
use Algorithm::CheckDigits;
use Text::Unaccent;

use lib 'lib';
use FERWeb;

my $f = FERWeb->new;
my $c = DBI->connect("dbi:CSV:","","", { RaiseError => 1, f_ext => '.csv', f_encoding => 'utf-8' }) || die $dbi::errstr;
my $k = DBI->connect("dbi:mysql:database=koha_fer","","", { RaiseError => 1, AutoCommit => 0, mysql_enable_utf8 => 1 }) || die $DBI::errstr;

my $s = $c->prepare(qq{
select * from brucosi_2011_ISVU
});
$s->execute;

my $user_exists = $k->prepare(qq{
select * from borrowers where cardnumber = ?
});

my $insert_user = $k->prepare(qq{
insert into borrowers 
(cardnumber, categorycode, userid, firstname, surname, branchcode, email, dateexpiry)
values
(?,'S',?,?,?,'SRE',?,'2021-12-13')
});

while( my $row = $s->fetchrow_hashref ) {

	warn "# row = ",dump($row),$/;

	my $user = $f->getinfobycode( $row->{jmbag} );

	warn "# user = ", dump($user), $/;

	$user_exists->execute( 'S' . $row->{jmbag} );

	if ( $user_exists->rows ) {
		warn "EXISTS: ",dump($row);
		print "#";
	} else {
		$insert_user->execute( 'S' . $row->{jmbag}, $user->{nick}, $user->{first_name}, $user->{last_name}, $user->{email} );
	}

	print join(" "
		, $row->{jmbag}
		, $user->{nick}
		, $user->{email}
	),$/;

}

$k->commit;
