#!/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 any table by selection.

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'User/Password Export' => 'User/Password Export',
	   'Cannot open Export file' => 'Cannot open Export file',
	   'Download CSV File' => 'Download CSV File',
	   'Error' => 'Error',
	   'Students' => 'Students',

	   );

my $self = 'expuserpwd.pl';

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

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

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

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

my $title = $lex{'User/Password Export'};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<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>$schoolname $lex{'User/Password Export'}</h1>\n};

#foreach my $key (keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }

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

# Open output file
my $filename = "userpwdexp$$.csv";
open (EX,">$filename") || die $lex{'Cannot open Export file'}. " $fileName";

# Get lastname, firstname, student number (studnum) and password.
$sth = $dbh->prepare("select lastname, firstname, studnum, password
 from student order by lastname, firstname");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
my $rows = $sth->rows;

print qq{<p>". $lex{Students}. ": $rows</p>\n};

while ( my ($lastname, $firstname, $studnum, $password ) = $sth->fetchrow ) {

    my $userid = 's'. $studnum;
    my @rec = ( $userid, $password );

    if ( $csv->combine( @rec ) ) {
	my $record = $csv->string;
	print EX $record, "\r\n";
    } else {
	my $err = $csv->error_input;
	print qq{Combine failed on input for $firstname $lastname ($studnum)};
	print qq{ Password: $password - $err\n\n};
    }
}

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

print qq{<h1>[ <a href="$webdownloaddir/$filename">\n};
print qq{$lex{'Download CSV File'}</a> ]</h1>\n};
print qq{</body></html>\n};
