#!/usr/bin/perl
#  Copyright 2001-2009 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.

# Export Contact Name, rather than Student Name

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Address' => 'Address',
	   'Combine failed on input' => 'Combine failed on input',
	   'Error' => 'Error',
	   'Download' => 'Download',
	   );


use DBI;
use CGI;
# use Text::CSV_XS;
use Text::CSV::Encoded;

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::Encoded->new ({ encoding  => undef }); # accepts UTF8 marked strings
# my $csv = Text::CSV_XS->new( {binary => 1} );


# Open output file
$filename = "address$$.csv";
open (EX,">:encoding(UTF-8)", $filename) || die "$lex{Error}: Can't open file $filename";

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


my $sth = $dbh->prepare("select * from student 
  order by grade, homeroom, lastname,firstname");
$sth->execute;


my $title = "$lex{Export} $lex{'Address'}";

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{<center><h1>$title</h1>\n};


while ( my @arr = $sth->fetchrow ) {

    foreach $element (@arr) {  # strip CR/LF
	$element =~ s/\n/ /g;
	$element =~ s/\r/ /g;
    }  
    
    @labels[0] = "$arr[2] $arr[1]";  # Student Name
    @labels[1] = $arr[34];           # Address
    @labels[2] = $arr[35];           # City
    @labels[3] = $arr[36];           # P Code
    @labels[4] = $arr[16];           # Fees Owing
  
    if ($csv->combine(@labels)) {
	my $record = $csv->string;
	print EX $record, "\r\n";
    } else {
	my $err = $csv->error_input;
	print qq{$lex{'Combine failed on input'}: $err\n\n";
    }
}

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

print qq{<h1><a href="$webdownloaddir/$filename">$lex{Download} $lex{Address}</a></h1>\n};

print qq{</body></html>\n};
