#!/usr/bin/perl

use CGI;
use DBI;


my $self = 'updateMssid.pl';

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


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


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

# Select table to update mssid
my $table = 'student';

my $title = qq{Update MSSID};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body style="padding:1em;">\n};
print qq{<h1>$title</h1>\n};


my $sth2 = $dbh->prepare("update $table set mssid = ? where provnum = ?");

# Find mssid from provnum, if it exists
my $sth1 = $dbh->prepare("select mssid from mss_student where provnum = ?");


# get the records with missing mssid. Use studid rather than studnum to make sure
my $sth = $dbh->prepare("select studid,provnum,lastname,firstname, birthdate,studnum from $table 
			where mssid is NULL or mssid = '' or mssid = 0");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; }
while ( my ($studid,$provnum,$ln,$fn, $dob, $studnum) = $sth->fetchrow ) {
    if ( not $provnum) {
	print qq{<div style="color:red;">Missing Prov Num for $fn $ln ($studnum). Skipping</div>\n};
	next;
    } # can't match without provnum

    # Get MSSID from mss_student table using provnum
    $sth1->execute($provnum);
    if ( $DBI::errstr ) { print $DBI::errstr; }
    my $mssid = $sth1->fetchrow;
    if ( not $mssid ) {
	print qq{<div style="color:purple;">Missing in MSS: $fn $ln - $provnum ($studnum)</div>\n};
	next;
    }

    # Otherwise update the mssid value
    print qq{<div style="color:green;">PN:$provnum MSSID:$mssid - $fn $ln ($dob)</div>\n};
#    $sth2->execute($mssid,$provnum);
    if ( $DBI::errstr ) { print $DBI::errstr; }
}
    
print qq{</body></html>\n};


