<?php

//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

//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
include("../public/include_dao.php");
//billPrinter
require_once('../models/dao/BillprinterDAO.class.php');
require_once('../models/dto/Billprinter.class.php');
require_once('../models/mysql/BillprinterMySqlDAO.class.php');
require_once('../models/mysql/ext/BillprinterMySqlExtDAO.class.php');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Restaurantkitchenprint
require_once('../models/dao/RestaurantkitchenprintDAO.class.php');
require_once('../models/dto/Restaurantkitchenprint.class.php');
require_once('../models/mysql/RestaurantkitchenprintMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantkitchenprintMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");
/* ======================

  Controller Name :- unitController

  OPERTATION in Controller

  1-display add form
  2- add in unit tble
  4-display sucess or error
  5-display show and delete
  6-delete from unit tbl
  7-display edit
  8- update unit tbl
  ======================== */

//here the global templates
if(!in_array($do, array('billprint','billprintWithoutPrice'))) {
    $smarty->display("header.html");
}


//here goes the instances and general variables
//Unit
$billPrinter = new Billprinter();
$billPrinterDAO = new BillprinterMySqlDAO();
$billPrinterEX = new BillprinterMySqlExtDAO();
//
$productCatDAO = new ProductcatMySqlDAO;
$productCatEx = new ProductcatMySqlExtDAO;
//Restaurantkitchenprint
$restaurantkitchenprint = new Restaurantkitchenprint();
$restaurantkitchenprintDAO = new RestaurantkitchenprintMySqlDAO();
$restaurantkitchenprintEX = new RestaurantkitchenprintMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();


$myUserEx = new UserMySqlExtDAO();

//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");
    //here the smarty templates
    $smarty->display("billPrinterView/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    show();

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("billPrinterView/show.html");
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    $printerId = $_GET['id'];
    try {
        $note = delete($printerId);
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        //header("location:?do=error");
    }
} elseif ($do == "edit") {//edit  unit
    include_once("../public/authentication.php");
    $data = edit();
    $smarty->assign("data", $data);
    #######
    $cats = $productCatEx->queryAllIn('0'.$data->cats);
    $catsArr = array();
    foreach ($cats as $value) {
        $theCat = new stdClass();
        $theCat->id = $value->productCatId;
        $theCat->text = $value->productCatName;
        array_push($catsArr, $theCat);
    }
    $smarty->assign("cats_hidden", json_encode($catsArr));

    $userids = R::getAll('select userid,employeename from user where usergroupid > 0 and userid in('.$data->userids.')');
    $useridsArr = array();
    foreach ($userids as $value) {
        $user = new stdClass();
        $user->id = $value['userid'];
        $user->text = $value['employeename'];
        array_push($useridsArr, $user);
    }
    $smarty->assign("userids_hidden", json_encode($useridsArr));
    ########
    $smarty->display("billPrinterView/edit.html");
} elseif ($do == "update") { //edit update
    include_once("../public/authentication.php");

    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}  elseif ($do == "resetPrinter") {//tempdelete
    include_once("../public/authentication.php");
    $printerId = $_GET['id'];
    try {
        R::debug(true);
        if($printerId > 0)
        {
            $printerData = $billPrinterDAO->load($printerId);
            $lastBill = R::getCell('select max(sellbillid) from sellbill where sellbilldate <= "'.date('Y-m-d H:i:s').'" and userid in ('.$printerData->userids.') and conditions = 0');
            if($lastBill > 0) {
                $foundRows = R::getAll('select * from billprint where billid = '.$lastBill);
                $typeArr = [];
                if(!empty($foundRows)) {
                    foreach ($foundRows as $value) {
                        $typeArr[] = $value['type'];
                        R::exec('update billprint set is_printed = 1 where id = '.$value['id']);
                    }
                    if(!in_array(1, $typeArr)) {
                        R::exec("INSERT INTO billprint (billid,is_printed,type,sysdate) VALUES (?,1,1, ?)", [$lastBill, date('Y-m-d H:i:s')]);
                    }
                     if(!in_array(0, $typeArr)) {
                        R::exec("INSERT INTO billprint (billid,is_printed,type,sysdate) VALUES (?,1,0, ?)", [$lastBill, date('Y-m-d H:i:s')]);
                    }
                }                   
                else
                {
                        R::exec("INSERT INTO billprint (billid,is_printed,type,sysdate) VALUES (?,1,1, ?)", [$lastBill, date('Y-m-d H:i:s')]);
                        R::exec("INSERT INTO billprint (billid,is_printed,type,sysdate) VALUES (?,1,0, ?)", [$lastBill, date('Y-m-d H:i:s')]);
                }
            }
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} 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);

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

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

// add in unit tbl
function add() {
    global $billPrinterDAO;
    global $billPrinter;

    $name = $_POST['printerName'];

    $cats = filter_input(INPUT_POST, 'cats', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    $cats_str = '';
    foreach ($cats as $value) {
        $cats_str .= $value . ",";
    }
    $cats_str = rtrim($cats_str, ',');

    $userids = filter_input(INPUT_POST, 'userids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    $userids_str = '';
    foreach ($userids as $value) {
        $userids_str .= $value . ",";
    }
    $userids_str = rtrim($userids_str, ',');

    $billPrinter->name = $name;
    $billPrinter->cats = $cats_str;
    $billPrinter->userids = $userids_str;
    $billPrinter->userid = $_SESSION['userid'];
    $billPrinter->sysdate = date('Y-m-d');
    $billPrinter->del = 0;
    $billPrinterDAO->insert($billPrinter);
}

//show
function show() {
    global $billPrinterDAO;
    global $billPrinter;
    global $smarty;


    $printersData = $billPrinterDAO->queryAll();
    $smarty->assign('printersData', $printersData);
}

function delete($printerId) {
    global $billPrinterDAO;
    //$deleteFlag;
    if (!empty($printerId)) {
        try {
            //temp delete from unit tbl
            $billPrinterDAO->delete($printerId);
            //$deleteFlag = "true";
            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

function edit() {
    global $billPrinterDAO;

    $id = $_GET['id'];
    $data = $billPrinterDAO->load($id);
    return $data;
}

function update() {
    global $billPrinterDAO;
    global $billPrinter;

    $id = $_POST['id'];
    $name = $_POST['printerName'];
    $cats = filter_input(INPUT_POST, 'cats', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    $cats_str = '';
    foreach ($cats as $value) {
        $cats_str .= $value . ",";
    }
    $cats_str = rtrim($cats_str, ',');

    $userids = filter_input(INPUT_POST, 'userids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    $userids_str = '';
    foreach ($userids as $value) {
        $userids_str .= $value . ",";
    }
    $userids_str = rtrim($userids_str, ',');


    $billPrinter = $billPrinterDAO->load($id);
    $billPrinter->name = $name;
    $billPrinter->cats = $cats_str;
    $billPrinter->userids = $userids_str;
    $billPrinterDAO->update($billPrinter);
}

?>