#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'ajax/user/getUserAccount.tmpl',
        }
);



my $sid = $input->{'sid'};
my $username=$input->{'userName'};
my $sth=$dbh->prepare("update opl_user set username=null where uid=?");
    my $userInfo = {};
    if($sid ne ''){
        $userInfo = getUserInfoBySid($dbh,$sid);
        $userInfo->{'acctRegistered'}=1;

        if($userInfo->{'password'} eq ''){
            $userInfo->{'acctRegistered'}=0;   
            $sth->execute($userInfo->{'uid'});
        }
    }
    elsif($username ne''){
       $userInfo = getUserInfoByUsername($dbh,$username);

    }
    foreach my $f(keys %$userInfo){
       $template->param( $f => $userInfo->{$f});
    }

$template->param(
    sid   => $input->{'sid'},
);

#Tue, Jan 12, 2010 @ 10:31:41 EST
my $msgValMap ={};
my $stdMsgMap  =loc_getMsgFile('user/userInfo.msg');
loc_write($template,$stdMsgMap);


tmpl_write($dbh, $cgi, $cookie, $template);


#==============================================
#
sub getUserInfoByUsername{
     my ($dbh, $username) = @_;
     my $userInfo={}; 
     my $sth = $dbh->prepare(<<_STH_);
select  uid,firstname,lastname,username,password,email,status,teacher,homeroom,grade 
from    opl_user
where    username = ?
_STH_
        $sth->execute($username);
        if($userInfo = $sth->fetchrow_hashref){
            if(!$userInfo->{'password'} || $userInfo->{'password'} eq ''){
                $userInfo={};
                $dbh->do("update opl_user set username='' where username='$username'");
            }
        }

       
  return   $userInfo;
}

#==============================================
#
sub getUserInfoBySid{
     my ($dbh, $sid) = @_;
     my $userInfo={}; 
     my $sth = $dbh->prepare(<<_STH_);
select  uid,firstname,lastname,username,password,email,status,teacher,homeroom,grade 
from    opl_user
where    sid = ? || userbarcode= ?
_STH_
        $sth->execute($sid,$sid);
        $userInfo = $sth->fetchrow_hashref;
  return   $userInfo;
}
