#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }

use CGI::Carp qw(fatalsToBrowser);
use strict;
use CGI;
use DBI;
use CGI::Session;
use CGI::Cookie;
use Crypt::PasswdMD5;

#----------------------------------------------------------------------------------------------------------------------

my $q = CGI->new;
my $username = $q->param("username");
my $password = $q->param("password");

my $salt = '1Tv4dM1n' ;
my $crypted_password = apache_md5_crypt($password,$salt) ;

#----------------------------------------------------------------------------------------------------------------------

my ($url1,$url2,$url3,$url4) = split(/\./,$ENV{SERVER_NAME}) ; # www.itvadmin.co.za or itvadmin.co.za

unless ($url1 eq 'itvadmin' || $url2 eq 'itvadmin') { return ; }

#----------------------------------------------------------------------------------------------------------------------

our ($dbh,$now_ccyy_mm_dd,$now_hour,$now_min,$now_sec);
our %i ;

my $session;
my $userID;
my $error;

use today ;
use db ;

&db_open_upd ;

	# $CGI::Session::MySQL::TABLE_NAME = 'my_sessions'; # This is only used if the sessions table in the database does not have the default name of "sessions"
	my $session = new CGI::Session("driver:MySQL", undef, {Handle=>$dbh});
	my $cgisessid = $session->id();

	my $cookie = new CGI::Cookie(-name=>'CGISESSID', -value=>$cgisessid);

&db_close_conn;

#----------------------------------------------------------------------------------------------------------------------

# check the username and password in the database
my $statement = qq{SELECT id,block,user_type,organisation_ids,region_ids,email,customer_ids FROM users WHERE username=? and password=?};
my $sth = $dbh->prepare($statement) or die $dbh->errstr;
$sth->execute($username,$crypted_password) or die $sth->errstr;
my ($userID,$blocked,$usertype,$organisationIds,$regionIds,$email,$customerIds) = $sth->fetchrow_array;

if ($blocked){ $error = qq(unauthorised) ; } else { $error = qq(username or password is wrong) ; }

my $json = '' ;

if ($userID && $blocked ne '1') { # username and password has been found in the database and the user is not blocked
    $session->param(-name=>'id', -value=>$userID);
    $session->param(-name=>'uemail', -value=>$email);
    $session->param(-name=>'uname', -value=>$username);
    $session->param(-name=>'utype', -value=>$usertype);
    $session->param(-name=>'oids', -value=>$organisationIds);
    $session->param(-name=>'rids', -value=>$regionIds);
    $session->param(-name=>'cids', -value=>$customerIds);
    $session->param(-name=>'_IS_LOGGED_IN', -value=>$userID);
    &today;
    $session->param(-name=>'timestamp', -value=>"$now_ccyy_mm_dd $now_hour:$now_min:$now_sec");
    $json = qq{{"success" : "login is successful", "userid" : "$userID"}} ;
    # $i{lastvisitdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
    # &db_min_upd('users',"id='$userID'") ;
	
	$session->expire('+12h');  # session expire hours  # $session->expire(3600); # expire seconds # $session->expire('+2m'); # expire minutes # $session->expire('+1M'); # expire months
	
	my $lastvisitdate = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
    my $sql = qq(UPDATE `users` SET `lastvisitDate`="$lastvisitdate" WHERE `id`='$userID') ;
	$sth = $dbh -> do ($sql) or die "could not execute :<BR>$sql<BR>$!" ;
    }
else
    {
    $json = qq{{"error" : "$error"}};
    $session->delete();
    $session->flush(); # Recommended practice says use flush() after delete().
    };
    
# return JSON string
print $q->header(-type => "application/json", -charset => "utf-8", -cookie => $cookie);
print $json;

use common ;

1;