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

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Staff' => 'Staff',
	   'Combine failed on input' => 'Combine failed on input',
	   'CSV File' => 'CSV File',
	   '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_XS->new( {binary => 1} );
my $csv = Text::CSV::Encoded->new ({ encoding  => undef });

Text::CSV::Encoded->error_diag unless $csv; # report error message

# Open output file
my $filename = "teacher$$.csv";

open (EX, ">",$filename) || die "$lex{Error}: Can't open Export file $filename\n";

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


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

my $title = "$lex{Export} $lex{Staff}";

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

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

    my $userid = $arr[5];

    # Get the Grade (if any)
    my $sth1 = $dbh->prepare("select field_value from staff_multi as sm, staff as s
      where s.userid = sm.userid and field_name = 'grade' and s.userid = ?");
    $sth1->execute( $userid );
    my $grade;
    while ( my $gr = $sth1->fetchrow ) {
	$grade .= $gr. ' ';
    }

    # Get the Homeroom (if any)
    $sth1 = $dbh->prepare("select field_value from staff_multi as sm, staff as s
      where s.userid = sm.userid and field_name = 'homeroom' and s.userid = ?");
    $sth1->execute( $userid );
    my $homeroom;
    while ( my $hr = $sth1->fetchrow ) {
	$homeroom .= $hr. ' ';
    }

    push @arr, $grade;
    push @arr, $homeroom;

    shift @arr; # remove first element - teachid, not useful.
    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{<h1><a href="$webdownloaddir/$filename">\n};
print qq{$lex{Download} $lex{'CSV File'}</a></h1>\n};

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