#!/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.

# Export Contact Name, rather than Student Name

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Export Student Table' => 'Export Student Table',
	   'Labels' => 'Labels',
	   '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',
	   'Cannot open' => 'Cannot open',
	   '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 = "mlabels$$.csv";
open (EX,">$fileName") || die $lex{'Cannot open'}. " Export file $fileName\n";

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 $rows = $sth->rows;

my $title = $lex{'Export Student 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</h1>\n};
print qq{<p>$lex{Records}: $rows</p>\n};

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

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

    $sth1 = $dbh->prepare("select sal, lastname from staff as s, staff_multi as sm
     where s.userid = sm.userid and field_name = 'homeroom' and field_value = ?");
    $sth1->execute( $arr[6] );
    my ($sal, $lastname) = $sth1->fetchrow;

    @labels[0] = "$arr[2] $arr[1]";  # Student Name
    @labels[1] = $arr[5];           # Grade
    @labels[2] =  "$sal $lastname";  # Teacher Name

    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};
    }
}

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

print qq{<p>[ <a href="$webdownloaddir/$fileName">$lex{'Download CSV File'}</a> ]</p>\n};

print qq{<p><strong>$lex{Note}:</strong> \n};
print qq{CSV (Comma Separated Value) can be directly imported into a spreadsheet</p>\n};

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

