<?php

//the global file operation
include("../public/impOpreation.php");
//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");

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

//Breadcrumb
//require_once("../library/breadcrumb.php");
//get the do the action
$do = $_GET['do'];

//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');
//Serialsarchive
require_once('../models/dao/SerialsarchiveDAO.class.php');
require_once('../models/dto/Serialsarchive.class.php');
require_once('../models/mysql/SerialsarchiveMySqlDAO.class.php');
require_once('../models/mysql/ext/SerialsarchiveMySqlExtDAO.class.php');

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

  Controller Name :- saveCTRL اضافة وتعديل وعرض الخزن

  OPERTATION in Controller

  1-display add form
  2- add in Save tbl
  3-insert into savedaily tbl
  4-display sucess or error
  5-display show form
  6-edit in Save data

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


//here the global templates
$smarty->display("header.html");


//here goes the instances and general variables
//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();
//Serialsarchive
$serialsArchive = new Serialsarchive();
$serialsArchiveDAO = new SerialsarchiveMySqlDAO();
$serialsArchiveEX = new SerialsarchiveMySqlExtDAO();
//Breadcrumb
//$breadcrumbObject = new Breadcrumb();
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $emp = $userDAO->load($_SESSION['userid']);
    $smarty->assign('emp', $emp);
    $smarty->display("generateserial/add.html");
} elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");
    try {
        // here the function that do the action
        $data = add();
        $serial = $data[0];
        $flag = $data[1];
        $smarty->assign('serial', $serial);
        $smarty->assign('flag', $flag);
        $smarty->display("generateserial/serial.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");
    $id = (int) $_GET['id'];
    $data = $serialsArchiveEX->loadEX($id);
    $smarty->assign('data', $data);
    $smarty->display("generateserial/edit.html");
} elseif ($do == "update") {

    //here the permssion check
    include_once("../public/authentication.php");
    try {
        // here the function that do the action
        $data = update();
        $serial = $data[0];
        $flag = $data[1];
        $smarty->assign('serial', $serial);
        $smarty->assign('flag', $flag);
        $smarty->display("generateserial/serial.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
} elseif ($do = "show") {

    $allData = $serialsArchiveEX->queryAllEX();
    $smarty->assign('allData', $allData);
    $smarty->display("generateserial/show.html");
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}




$smarty->assign("customValidation", 1);

//here the global templates
$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */

function add() {
    global $serialsArchive;
    global $serialsArchiveDAO;
    global $serialsArchiveEX;

    $devId = filter_input(INPUT_POST, "devid");
    $userno = filter_input(INPUT_POST, "userno");
    $syncusers = filter_input(INPUT_POST, "syncusers");
    $synctime = filter_input(INPUT_POST, "synctime");
    if (!isset($synctime) || empty($synctime)) {
        $synctime = 2;
    }
    $clientname = filter_input(INPUT_POST, "clientname");
    $dateto = filter_input(INPUT_POST, "dateto");
    if (!isset($dateto) || empty($dateto)) {
        //default is one year licence
        $dateto = date('Y-m-d', strtotime(date("Y-m-d", mktime()) . " + 365 day"));
    }

    $data = $serialsArchiveEX->checkifexist($devId, $userno, $syncusers, $clientname, $dateto, $synctime);

    $flag = "هذه البانات موجودة سابقا والسيريال هو:-";
    if (count($data) < 1) {
        $serialsArchive->deviceid = $devId;
        $serialsArchive->userno = $userno;
        $serialsArchive->syncusers = $syncusers;
        $serialsArchive->synctime = $synctime;
        $serialsArchive->clientname = $clientname;
        $serialsArchive->dateto = $dateto;
        $serialsArchive->userid = $_SESSION['userid'];
        $serialsArchive->sysdate = date('Y-m-d');
        $serialsArchive->conditions = 0;

        $serialsArchiveDAO->insert($serialsArchive);
        $flag = 0;
    }
    $serial = generateSerial($devId, $userno, $syncusers, $synctime, $clientname, $dateto);

    return array($serial, $flag);
}

function update() {
    global $serialsArchive;
    global $serialsArchiveDAO;
    global $serialsArchiveEX;
    $id = filter_input(INPUT_POST, "id");
//    $devId = filter_input(INPUT_POST, "devid");
    $userno = filter_input(INPUT_POST, "userno");
    $syncusers = filter_input(INPUT_POST, "syncusers");
    $synctime = filter_input(INPUT_POST, "synctime");
    if (!isset($synctime) || empty($synctime)) {
        $synctime = 2;
    }
    $clientname = filter_input(INPUT_POST, "clientname");
    $dateto = filter_input(INPUT_POST, "dateto");
    if (!isset($dateto) || empty($dateto)) {
        //default is one year licence
        $dateto = date('Y-m-d', strtotime(date("Y-m-d", mktime()) . " + 365 day"));
    }

    $serialsArchive = $serialsArchiveDAO->load($id);
    //$serialsArchive->deviceid = $devId;
    $serialsArchive->userno = $userno;
    $serialsArchive->syncusers = $syncusers;
    $serialsArchive->synctime = $synctime;
    $serialsArchive->clientname = $clientname;
    $serialsArchive->dateto = $dateto;
    //$serialsArchive->userid = $_SESSION['userid'];
    //$serialsArchive->sysdate = date('Y-m-d');
    //$serialsArchive->conditions = 0;

    $serialsArchiveDAO->update($serialsArchive);
    $flag = 0;
    $serial = generateSerial($serialsArchive->deviceid, $userno, $syncusers, $synctime, $clientname, $dateto);

    return array($serial, $flag);
}

function generateSerial($devId, $userno, $syncusers, $synctime, $clientname, $dateto) {

    $mac = $devId;
    $random_salt = hash('sha512', '1305');

    // Create salted password
    $hashedMac = hash('sha512', $mac . $random_salt);
    $enc_userno = encrypt_Str($userno);
    $enc_syncusers = encrypt_Str($syncusers);
    $enc_synctime = encrypt_Str($synctime);
    $enc_clientname = encrypt_Str($clientname);
    $enc_dateto = encrypt_Str($dateto);
    $completeSerial = $hashedMac . "-" . $enc_userno . "-" . $enc_syncusers . "-" . $enc_synctime . "-" . $enc_clientname . "-" . $enc_dateto;

    return $completeSerial;
}

function encrypt_Str($string) {
    $key = "TrY_If->You%&Dare->0159"; //key to encrypt and decrypts.
    $result = '';
    $test = "";
    for ($i = 0; $i < strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $keychar = substr($key, ($i % strlen($key)) - 1, 1);
        $char = chr(ord($char) + ord($keychar));

        $test[$char] = ord($char) + ord($keychar);
        $result.=$char;
    }

    return urlencode(base64_encode($result));
}

function decrypt_Str($string) {
    $key = "TrY_If->You%&Dare->0159"; //key to encrypt and decrypts.
    $result = '';
    $string = base64_decode(urldecode($string));
    for ($i = 0; $i < strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $keychar = substr($key, ($i % strlen($key)) - 1, 1);
        $char = chr(ord($char) - ord($keychar));
        $result.=$char;
    }
    return $result;
}

//--------------
//define('SALT', 'whateveryouwant');
//
//function encrypt($text)
//{
//    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
//}
//
//function decrypt($text)
//{
//    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
//}
//$encryptedmessage = encrypt("your message");
//echo decrypt($encryptedmessage);
?>