<?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');

require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');
//get the do the action
$do = filter_input(INPUT_GET, "do"); //$_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

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

  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();


//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

//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);


$userblocknum = file_get_contents("../views/default/archiveview/userblock.txt");
//print($databsesNames);
$databases = array_reverse(explode(",", $databsesNames));
$smarty->assign("databases", $databases);


if (!isset($do)) {


    $allusers = $myUserRecord->queryAll();
    $allbills = $mySellbillRecord->queryAll();

    if (count($allusers) >= $userblocknum || count($allbills) >= $userblocknum) {
        header("location:?do=finished");
        exit;
    }

    $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;

        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");
}

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 = 1; //1 to show menu
    $myUserGroup->hidecat = 0;
    $myUserGroup->clientnegative = 1;
    $myUserGroup->suplliernegative = 1;
    $myUserGroup->storenegative = 1;
    $myUserGroup->directDiscount = 0;
    $myUserGroup->percentageDiscount = 0;
    $myUserGroup->priceupdate = 0;
    $myUserGroup->allowEditDelInBills = 0;
    $myUserGroup->allowEditDelInBuyBills = 0;
    $myUserGroup->showsStorerQuantity = 0;
    $myUserGroup->showSellAllPrice = 0;
    $myUserGroup->showSellHalfPrice = 0;
    $myUserGroup->showSellUnitPrice = 0;
    $myUserGroup->showBuyPrice = 0;
    $myUserGroup->productno = 0;
    $myUserGroup->kempilano = 0;
    $myUserGroup->productnotsellno = 0;
    $myUserGroup->clientcheckno = 0;
    $myUserGroup->suppliercheckno = 0;
    $myUserGroup->productRequist = 0;
    $myUserGroup->otherRequist = 0;
    $myUserGroup->toWorkShopOrder = 0;
    $myUserGroup->insuranceBill = 0;
    $myUserGroup->sellreportpricetype = 0;
    $myUserGroup->netprofit = 0;
    $myUserGroup->hideproductcatid = 0;
    $myUserGroup->directSaveBills = 0;
    $myUserGroup->seeAllHalls = 0;
    $myUserGroup->homePageIcon = 0;
    $myUserGroup->sendKitchen = 1;
    $myUserGroup->printKitchen = $printKitchen;
    $myUserGroup->endBill = 1;
    $myUserGroup->endPrintBill = 1;

    $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 = "manager";
    $user->saveid = 1;
    $user->usergroupid = 1;
    $user->username = "admin";

    $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("initialValues/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
    );
}

?>
