#!/usr/bin/perl

use warnings;
use strict;
use diagnostics;

use DBI;

sub Print_SQL_Insert {
    my $dbh = shift;
    my $qry = shift;
    my $account = shift;
    my @columns = @_;

    my $sth = $dbh->prepare( $qry ) or die "Unable to prepare statement: $dbh->errstr\n";
    $sth->execute() or die "Unable to execute statement: $sth->errstr\n";

    my $v;
    my $values;
    $values = join(
        ",\n",
        map {
            $v = $_;
            "    (" . join(
                ",\t",
                map { defined $_ ? "'$_'" : 'NULL' } map { $v->{$_} } @columns
            ) . ')'
        } @{ $sth->fetchall_arrayref({}) }
    );
    if ($values) {
        print qq|INSERT INTO $account (| . join(', ', @columns) . qq|) VALUES\n$values;\n|;
    }
}

# use environment variables for authentication
my $dbh = DBI->connect('dbi:Pg:', undef, undef)
    or die "Unable to connect: $DBI::errstr\n";

print '
-- Create the entire COA in 1 transaction

BEGIN;

';

print "-- HEADINGS DEFINITION\n";
my $query = qq|
    select h.id, h.accno, h.parent_id, h.description
        from account_heading_tree t
    join account_heading h on t.id = h.id
        order by level asc, t.accno asc
|;
Print_SQL_Insert( $dbh, $query, 'account_heading', qw|id parent_id accno description| );


print "\n\n\n-- GIFI DEFINITION (need gifi before account creation)\n";
$query = qq|
    select * from account
|;
Print_SQL_Insert( $dbh, $query, 'gifi', qw|accno description| );


print "\n\n\n-- ACCOUNTS DEFINITION\n";
$query = qq|
    select * from account
|;
Print_SQL_Insert( $dbh, $query, 'account', qw|id accno is_temp category gifi_accno heading contra tax obsolete description| );


print "\n\n\n-- CUSTOM ACCOUNT LINK DEFINITION\n";
$query = qq|
    select * from account_link_description where custom
|;
Print_SQL_Insert( $dbh, $query, 'account_link_description', qw|description summary custom| );


print "\n\n\n-- ACCOUNT LINKS\n";
$query = qq|
    select * from account_link
|;
Print_SQL_Insert( $dbh, $query, 'account_link', qw|account_id description| );


print "\n\n\n-- TAX DEFINITION\n";
$query = qq|
    select * from tax
|;
Print_SQL_Insert( $dbh, $query, 'tax', qw|chart_id rate minvalue maxvalue taxnumber validto pass taxmodule| );


print "\n\n\n-- SET UP DEFAULTS\n";
$query = qq|
    select * from defaults
        where setting_key in ('inventory_accno_id',
                       'income_accno_id',
                       'expense_accno_id',
                       'fxgain_accno_id',
                       'fxloss_accno_id',
                       'earn_id',
                       'curr',
                       'weightunit',
                       'default_language',
                       'separate_duties',
                       'lock_description',
                       'gapless_ar',
                       'check_prefix',
                       'vclimit',
                       'decimal_places',
                       'show_creditlimit',
                       'session_timeout',
                       'password_duration',
                       'format',
                       'default_country'
                       );
|;
( my $delete_query = $query ) =~ s/select \*/delete/;
print "-- FIRST Delete the Keys we intend to set\n";
print "$delete_query\n";
print "-- NOW ACTUALLY SET the KEYS\n";
Print_SQL_Insert( $dbh, $query, 'defaults', qw|value setting_key| );

print "\n\n\n-- SET UP DEFAULTS that require Lookups\n";
print "-- FIRST Delete the Keys we intend to set\n\n";
my $delete_query = qq|delete from defaults where setting_key in ('default_country');|;
print "$delete_query\n";
print "-- NOW ACTUALLY SET the KEYS\n";
$query = qq|
    select C.short_name FROM defaults D
        INNER JOIN country C on D.value = C.id::text
        WHERE setting_key = 'default_country';
|;
my $sth = $dbh->prepare( $query ) or die "Unable to prepare statement: $dbh->errstr\n";
$sth->execute() or die "Unable to execute statement: $sth->errstr\n";

my $default_country = $sth->fetchrow_array;

print "INSERT INTO defaults (value, setting_key ) SELECT id::text, 'default_country' from country WHERE short_name = '$default_country';";

print '

-- END of transaction
COMMIT;

';

