<?php

session_start();
ob_start();

// get the config file
include_once("../public/config.php");

//	//here the db files that include in the file
include("../public/include_dao.php");

//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//Newdbname
require_once('../models/dao/NewdbnameDAO.class.php');
require_once('../models/dto/Newdbname.class.php');
require_once('../models/mysql/NewdbnameMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbnameMySqlExtDAO.class.php');


//Properties
require_once('../models/dao/PropertiesDAO.class.php');
require_once('../models/dto/Propertie.class.php');
require_once('../models/mysql/PropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/PropertiesMySqlExtDAO.class.php');

//Relusergrouppropertie
require_once('../models/dao/RelusergrouppropertiesDAO.class.php');
require_once('../models/dto/Relusergrouppropertie.class.php');
require_once('../models/mysql/RelusergrouppropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/RelusergrouppropertiesMySqlExtDAO.class.php');

//get the do the action
$do = filter_input(INPUT_GET, "do"); //$_GET['do'];



/* ======================

  Controller Name :- login

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */


//here goes the instances and general variables
//User
$user = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroup = new Usergroup();
//Newdbname
$newDbName = new Newdbname();
$newDbNameDAO = new NewdbnameMySqlDAO();
$newDbNameExt = new NewdbnameMySqlExtDAO();


//Properties
$myPropertiesRecord = new PropertiesMySqlDAO();

//Relusergrouppropertie
$myRelusergrouppropertie = new Relusergrouppropertie();
$myRelusergrouppropertieRecord = new RelusergrouppropertiesMySqlDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//check if there is a usergroup with id = 1


$do = filter_input(INPUT_GET, "do");


// Read in entire file
$databsesNames = file_get_contents("../views/default/archiveview/dbNames.txt");
$databsesNames = trim($databsesNames);



//print($databsesNames);
$databases = array_reverse(explode(",", $databsesNames));
$smarty->assign("databases", $databases);


if (!isset($do)) {

    $sessionUserId = $_SESSION['userid'];
    $sessionUsergroupId = $_SESSION['usergroupid'];
    // the that will do the check
    if (!empty($sessionUserId)) {
        //get start page from usergroup by $_SESSION['usergroupid']
        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;

        //send the user to the start page
        header("location:" . $startPage . "");
    } else {
        $smarty->display("login.html");
    }
} elseif ($do == "en") {
    $sessionUserId = $_SESSION['userid'];
    $sessionUsergroupId = $_SESSION['usergroupid'];
    // the that will do the check
    if (!empty($sessionUserId)) {
        //get start page from usergroup by $_SESSION['usergroupid']
        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;
        //send the user to the start page
        header("location:" . $startPage . "");
    } else {
        //variables the get the values of input from login from
        $username = filter_input(INPUT_POST, "username"); //$_POST['username'];
        $password = filter_input(INPUT_POST, "password"); //$_POST['password'];
        $db = filter_input(INPUT_POST, "db"); //$_POST['db'];
        $_SESSION['dbname'] = $db;
        //checkAllowedLimits();
        //checkSoftwareActivation();
        insertProperities();

        $userGroupData = $myUserGroupRecord->queryAll(); //$myUserGroupRecord->load(1);
        if (count($userGroupData) <= 0) {
            try {
                insertUserGroup();
            } catch (Exception $e) {

            }
        }

        //check if there is a user with id = 1
        $userData = $myUserRecord->queryAll(); //$myUserRecord->load(1);
        if (count($userData) <= 0) {
            try {
                insertUser();
            } catch (Exception $e) {

            }
        }

        //check on there values
        if (empty($username) & empty($password)) {
            // the login form is empty
            $smarty->display("login.html");
        } else {
            /*             * * check from database for the user name  ** */
            $validationResult = $myUserEx->validationUser($username, $password);

            //if there no result in the arry send it to the login form
            if (count($validationResult) <= 0) {
                $_SESSION['attempt'] = $_SESSION['attempt'] + 1;
                if (empty($_SESSION['attempt']) || $_SESSION['attempt'] == NULL || $_SESSION['attempt'] < 3) {
                    // the login form is empty
                    $smarty->display("login.html");
                } else {
                    $testUser = $myUserRecord->queryByUsername($username);
                    $smarty->assign("userQuestion", $testUser[0]->question);
                    $smarty->assign("username", $username);
                    $smarty->display("secretquestion.html");
                }
            } else {
                $_SESSION['attempt'] = 0;
                $_SESSION['userid'] = $validationResult->userid;
                $_SESSION['usergroupid'] = $validationResult->usergroupid;
                $_SESSION['username'] = $validationResult->username;
                $_SESSION['usergroupname'] = $validationResult->usergroupname;
                $_SESSION['saveid'] = $validationResult->saveid;
                $_SESSION['employeename'] = $validationResult->employeename;
                $_SESSION['searchinonesave'] = $validationResult->searchinonesave;
                $_SESSION['branchId'] = $validationResult->branchId;

                $_SESSION['dbname'] = $db;
                //get start page from usergroup by $_SESSION['usergroupid']
                $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);

                $startPage = $userGroupData->startpage;
                //send the user to the start page
                header("location:" . $startPage . "");
            }
        }
    }
} elseif ($do == "enq") {
    $username = filter_input(INPUT_POST, "username"); //$_POST['username'];
    $answer = filter_input(INPUT_POST, "answer"); //$_POST['answer'];

    $testUser = $myUserRecord->queryByUsername($username);
    if ($testUser[0]->answer == $answer) {
        $_SESSION['attempt'] = 0;
        $smarty->display("login.html");
    } else {
        $smarty->assign("userQuestion", $testUser[0]->question);
        $smarty->assign("username", $username);
        $smarty->display("secretquestion.html");
    }
} elseif ($do == "finished") {
    //here the smarty templates
    $smarty->display("finished.html");
} elseif ($do == "activate") {
    //here the smarty templates
    $id = filter_input(INPUT_POST, "serial");
    if (!empty($id)) {
        activate();
    }
    $serialCal = serialcheck();
    if ($id == $serialCal) {
        header("location:?");
    } else {
        exec('wmic csproduct get "UUID"', $macaddress, $isExecuted);
        $macaddress = $macaddress[1];
        $mac = str_replace(array('-'), '', $macaddress);
        $smarty->assign("mac", $mac);
        $smarty->display("activate.html");
    }
}

function insertUserGroup() {
    global $myUserGroup;
    global $myUserGroupRecord;

    $myUserGroup->conditions = 0;
    $myUserGroup->currentdate = date("Y-m-d");
    $myUserGroup->level = 1;
    $myUserGroup->startpage = "index.php";
    $myUserGroup->usergroupdescription = "admin";
    $myUserGroup->usergroupname = "admin";
    //
    $myUserGroup->savedailydate = date("Y-m-d");
    $myUserGroup->hidemenu = 0;
    $myUserGroup->hidecat = 0;
    $myUserGroup->clientnegative = 1;
    $myUserGroup->suplliernegative = 1;
    $myUserGroup->storenegative = 1;
    $myUserGroup->directDiscount = 0;
    $myUserGroup->percentageDiscount = 0;
    $myUserGroup->priceupdate = 0;

    $usergroupId = $myUserGroupRecord->insert($myUserGroup);
    addReluesUsergroup($usergroupId);
}

function insertUser() {
    global $user;
    global $myUserRecord;

    $user->conditions = 0;
    $user->currentdate = date("Y-m-d");
    $user->employeename = "admin";
    $user->password = "123";
    $user->saveid = 1;
    $user->usergroupid = 1;
    $user->username = "admin";

    $user->userstoreid = 0;
    $user->awardrate = 0;
    $user->branchId = 0;
    $user->question = "what is my question";
    $user->answer = "how";
    $user->searchinonesave = 0;

    $myUserRecord->insert($user);
}

// add data in relues tbl
function addReluesUsergroup($usergroupId) {

    //to use the variable out side the funcion
    global $myPropertiesRecord;

    global $myRelusergrouppropertie;
    global $myRelusergrouppropertieRecord;

    $propertiesData = $myPropertiesRecord->queryAll();
    if ($usergroupId == 1) {
        foreach ($propertiesData as $properties) {
            $propertyId = $properties->propertyid;

            $myRelusergrouppropertie->propertyid = $propertyId;
            $myRelusergrouppropertie->propertyvalue = 0;
            $myRelusergrouppropertie->usergroupid = $usergroupId;

            $myRelusergrouppropertieRecord->insert($myRelusergrouppropertie);
        }
    }
}

function insertProperities() {
    global $myPropertiesRecord;

    $propertiesData = $myPropertiesRecord->queryAll();
    if (count($propertiesData) <= 0) {
        run_sql_file("pro.sql");
    }
}

function run_sql_file($location) {
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $database = $_SESSION['dbname'];
    } else {
        $database = "storesdb";
    }


    $con = mysql_connect("localhost", "root", "123456");
    mysql_select_db($database, $con);
    $charset = mysql_client_encoding($con);
    mysql_query("SET NAMES 'utf8'");
    mysql_query('SET CHARACTER_SET utf8');

    mysql_query("INSERT INTO `properties` VALUES (1, 'Ø®ØµØ§Ø¦Øµ Ø¹Ø§Ù…Ù‡', 0, 1, '');");

    //load file
    $commands = file_get_contents($location);

    //delete comments
    $lines = explode("\n", $commands);
    $commands = '';
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line && !strpos($line, '--')) {
            $commands .= $line . "\n";
        }
    }

    //convert to array
    $commands = explode(";", $commands);
    /* 	print_r("<pre>");
      print_r($commands);
      print_r("<pre>"); */
    //run commands
    $total = $success = 0;
    foreach ($commands as $command) {

        if (trim($command)) {
            print_r($command . "<br>");
            if (mysql_query($command)) {
                $success +=1;
                $total += 1;
            }
            // $success += (@mysql_query($command)==false ? 0 : 1);
            // $total += 1;
        }
    }

    //return number of successful queries and total number of queries found
    return array(
        "success" => $success,
        "total" => $total
    );
}

function checkAllowedLimits() {
    global $myUserRecord;
    global $mySellbillRecord;

    $userblocknum = file_get_contents("../views/default/archiveview/userblock.txt");
    $allusers = $myUserRecord->queryAll();
    if (count($allusers) >= $userblocknum) {
        header("location:?do=finished");
        exit;
    }
}

function checkSoftwareActivation() {
    global $ProgramsettingDAO;

    $Programesetting = $ProgramsettingDAO->load(1);

    if (!isset($Programesetting->serial) || empty($Programesetting->serial)) {
        header("location:?do=activate");
        exit;
    } else {
        $serialCal = serialcheck();
        //print_r($serialCal);
        if ($Programesetting->serial == $serialCal) {

        } else {
            header("location:?do=activate");
            exit;
        }
    }
}

function serialcheck() {

    exec('wmic csproduct get "UUID"', $macaddress, $isExecuted);
    $macaddress = $macaddress[1];
    $mac = str_replace(array('-'), '', $macaddress);
    $random_salt = hash('sha512', '1305');
    // Create salted password
    $hashedMac = hash('sha512', $mac . $random_salt);
    return $hashedMac;
}

function activate() {
    global $ProgramsettingDAO;

    $id = filter_input(INPUT_POST, "serial");
    $serialCal = serialcheck();

    if ($id == $serialCal) {
        $Programesetting = $ProgramsettingDAO->load(1);
        $Programesetting->serial = $id;
        $ProgramsettingDAO->update($Programesetting);
    } else {
        header("location:?do=activate");
    }
}

?>
