#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

# DESC: Export Transfer Table.

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Records' => 'Records',
	   'Combine failed on input' => 'Combine failed on input',
	   'Download CSV File' => 'Download CSV File',
	   'CSV (Comma Separated Value) can be directly imported into Open Office' =>
	     'CSV (Comma Separated Value) can be directly imported into Open Office',
	   'Note' => 'Note',
	   'Enrollments' => 'Enrollments',
	   'Withdrawals' => 'Withdrawals',
	   'Export Transfer Table' => 'Export Transfer Table',
	   'Error' => 'Error',

	   );

use DBI;
use CGI;
use Text::CSV_XS;

eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

my $q = CGI->new;
print $q->header( -charset, $charset );

my $csv = Text::CSV_XS->new( {binary => 1} );

# Open output file
my $fileName = "transfer$$.csv";
open (EX,">$fileName") || die "Can't open Export file $fileName";

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


# Add Field names.
my @fieldnames;
my $sth = $dbh->prepare("show columns from transfer");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while ( my @cols = $sth->fetchrow ) {
    push @fieldnames, $cols[0];
}


my $sth = $dbh->prepare("select * from transfer order by date desc");

$sth->execute;
my $rows = $sth->rows;

my $title = $lex{'Export Transfer Table'}

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" type="text/css" href="$css">
$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$exppage">$lex{Export}</a> ]\n};

print qq{<h1>$title - {Enrollments} / $lex{Withdrawals}</h1>\n};

print qq{<p>$lex{Records}: $rows</p>\n};

if ($csv->combine(@fieldnames)) {
    my $record = $csv->string;
    print EX $record, "\r\n";
} else {
    my $err = $csv->error_input;
    print $lex{'Combine failed on input'}. ":$err\n\n";
}


for ($i=1; $i <= $rows; ++$i) {
    my @arr = $sth->fetchrow;

    foreach my $element ( @arr ) {  # strip CR/LF
	$element =~ s/\n/ /g;
	$element =~ s/\r/ /g;
    }

    if ($csv->combine(@arr)) {
	my $record = $csv->string;
	print EX $record, "\r\n";
    } else {
	my $err = $csv->error_input;
	print $lex{'Combine failed on input'}. ":$err\n\n";
    }
}

close EX;
system("mv $fileName $downloaddir");

print qq{<h3><a href="$webdownloaddir/$fileName">$lex{'Download CSV File'}</a></h3>\n};
print qq{</body></html>\n};
