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

#  This file is part of Open Admin for Schools.

# DESC: Export any table by selection.

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Custom Table Export' => 'Custom Table Export',
	   'Please select a table to export.' => 'Please select a table to export.',
	   'Table' => 'Table',
	   'Records' => 'Records',
	   'Cannot open Export file' => 'Cannot open Export file',
	   'Combine failed on input' => 'Combine failed on input',
	   'Download CSV File' => 'Download CSV File',
	   'Error' => 'Error',

	   );

my $self = 'expcustom.pl';

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

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

if (not $arr{table}) {
    showTables();
}

my $table = $arr{table};
print qq{<div style="font-size:120%;">$lex{Table} <b>$table</b></div>\n};

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

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


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

$sth = $dbh->prepare("select * from $table order by $fieldnames[0]");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
my $rows = $sth->rows;

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 qq{$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;
	$element =~ s/\x92/\x27/g; # chg close single quote.
    }

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

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

print qq{<div style="font-size:120%;font-weight:bold;">[ <a href="$webdownloaddir/$fileName">\n};
print qq{$lex{'Download CSV File'}</a> ]</div>\n};
print qq{</body></html>\n};


#-------------
sub showTables {
#-------------

    my $sth = $dbh->prepare("show tables");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print qq{<form action="$self" method="post">\n};

    print qq{<p>$lex{'Please select a table to export.'}</p>\n};
    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
    print qq{<tr><td colspan="2" class="cn">};
    print qq{<input type="submit" value="$lex{'Export'}"></td></tr>\n};

    while ( my $tbl = $sth->fetchrow ) {
	print qq{<tr><td>$tbl</td><td><input type="radio" name="table" value="$tbl"></td></tr>\n};
    }
    
    print qq{<tr><td colspan="2" class="cn">};
    print qq{<input type="submit" value="$lex{'Export'}"></td></tr>\n};
    print qq{</table></form></body></html>\n};
    
    exit;

}
