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

//Workshop
require_once('../models/dao/WorkshopDAO.class.php');
require_once('../models/dto/Workshop.class.php');
require_once('../models/mysql/WorkshopMySqlDAO.class.php');
require_once('../models/mysql/ext/WorkshopMySqlExtDAO.class.php');
//Bill
require_once('../models/dao/BillsDAO.class.php');
require_once('../models/dto/Bill.class.php');
require_once('../models/mysql/BillsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsMySqlExtDAO.class.php');
//Billsproduct
require_once('../models/dao/BillsproductsDAO.class.php');
require_once('../models/dto/Billsproduct.class.php');
require_once('../models/mysql/BillsproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsproductsMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.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');
//Workshop
require_once('../models/dao/WorkshopDAO.class.php');
require_once('../models/dto/Workshop.class.php');
require_once('../models/mysql/WorkshopMySqlDAO.class.php');
require_once('../models/mysql/ext/WorkshopMySqlExtDAO.class.php');
//Billsproduct
require_once('../models/dao/BillsproductsDAO.class.php');
require_once('../models/dto/Billsproduct.class.php');
require_once('../models/mysql/BillsproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsproductsMySqlExtDAO.class.php');

//Toworkshoporder
require_once('../models/dao/ToworkshoporderDAO.class.php');
require_once('../models/dto/Toworkshoporder.class.php');
require_once('../models/mysql/ToworkshoporderMySqlDAO.class.php');
require_once('../models/mysql/ext/ToworkshoporderMySqlExtDAO.class.php');
//Toworkshoporderbill
require_once('../models/dao/ToworkshoporderbillDAO.class.php');
require_once('../models/dto/Toworkshoporderbill.class.php');
require_once('../models/mysql/ToworkshoporderbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ToworkshoporderbillMySqlExtDAO.class.php');
//Branch
require_once('../models/dao/BranchDAO.class.php');
require_once('../models/dto/Branch.class.php');
require_once('../models/mysql/BranchMySqlDAO.class.php');
require_once('../models/mysql/ext/BranchMySqlExtDAO.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 :- accountstree

  OPERTATION in Controller

  1- display add form, add
  2- add in tbl
  3- display show and tempdelete
  4- edit
  5- update

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

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

//here goes the instances and general variables
//Workshop
$workshop = new Workshop();
$workshopDAO = new WorkshopMySqlDAO();
$workshopEX = new WorkshopMySqlExtDAO();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();
//Toworkshoporder
$toWorkshopOrder = new Toworkshoporder();
$toWorkshopOrderDAO = new ToworkshoporderMySqlDAO();
$toWorkshopOrderEX = new ToworkshoporderMySqlExtDAO();
//Toworkshoporderbill
$toWorkshopOrderBill = new Toworkshoporderbill();
$toWorkshopOrderBillDAO = new ToworkshoporderbillMySqlDAO();
$toWorkshopOrderBillEX = new ToworkshoporderbillMySqlExtDAO();
//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

$today = date("Y-m-d");
$now = date("Y-m-d H:i:s");
$smarty->assign("now", $now);
//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    //here the smarty templates
    $smarty->display("workshopview/add.html");
} elseif ($do == "add") {
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($_GET['do'] == "show") {

    show();
    $smarty->assign("customCheck", 1);
    $smarty->display("workshopview/show.html");
} elseif ($do == "edit") {
    $data = edit();
    $smarty->assign("data", $data);

    $smarty->display("workshopview/Edit.html");
} elseif ($_GET['do'] == "update") {
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
        //echo $e;
    }
} elseif ($_GET['do'] == "delete") {

    try {
        $id = $_GET["id"];
        delete($id);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
        //echo $e;
    }
}
##fatma transfer bills show
elseif ($do == "billtransport") {
    //here the permssion check
    include_once("../public/authentication.php");

    //السائقين
    $drivers = $userEX->queryWithGroupName("سائقين");
    $smarty->assign("drivers", $drivers);
    //الورش
    $workshops = $workshopDAO->queryAll();
    $smarty->assign('workshops', $workshops);
    //عامل التوصيل
    $deliveryWorkers = $userEX->queryWithGroupId(6);
    $smarty->assign("deliveryWorkers", $deliveryWorkers);
    //المستلم
    #########################################تحت التوصيل
    $orderNo = filter_input(INPUT_POST, "orderNo");
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");
    $queryString = '';
    if (isset($orderNo) && !empty($orderNo)) {
        $queryString .=' and orderNo = "' . $orderNo . '"';
    }
    if (isset($datefrom) && !empty($datefrom)) {
        $queryString .=' and deliverWorkshopDate >= "' . $datefrom . '"';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .=' and deliverWorkshopDate <= "' . $dateto . '"';
    }

    /* if ($queryString == ' and orderStatus = 0 ') {
      $queryString .= ' and deliverWorkshopDate = "' . $today . '" ';
      } */

    $ordersAtWorkshop = $toWorkshopOrderEX->queryByOrderStatusEX(0, $queryString);
    foreach ($ordersAtWorkshop as $data) {
        ##عامل التوصيل "السائق"
        $driver = $userDAO->load($data->driverId);
        $data->driverId = $driver->employeename;
        ##الفرع
        $branch = $BranchDAO->load($data->branchId);
        $data->branchId = $branch->branchName;
    }
    $smarty->assign('ordersAtWorkshop', $ordersAtWorkshop);

    $underManufacturingOrders = $toWorkshopOrderEX->queryByOrderStatusEX(1, $queryString);
    foreach ($underManufacturingOrders as $data) {
        ##عامل التوصيل "السائق"
        $driver = $userDAO->load($data->driverId);
        $data->driverId = $driver->employeename;
        ##الفرع
        $branch = $BranchDAO->load($data->branchId);
        $data->branchId = $branch->branchName;
    }
    $smarty->assign('underManufacturingOrders', $underManufacturingOrders);

    $finishedOrders = $toWorkshopOrderEX->queryByOrderStatusEX("2,3", $queryString);
    foreach ($finishedOrders as $data) {
        ##عامل التوصيل "السائق"
        $driver = $userDAO->load($data->driverId);
        $data->driverId = $driver->employeename;
        ##الفرع
        $branch = $BranchDAO->load($data->branchId);
        $data->branchId = $branch->branchName;
    }
    $smarty->assign('finishedOrders', $finishedOrders);



    $execusionmsg = $_SESSION["execmsg"];
    if ($execusionmsg == 1) {
        $smarty->assign("msg1", "تم تنفيذ الامر بنجاح");
        $smarty->assign("msg2", "تمت العملية بنجاح ");
        $smarty->assign("showmsg", 1);
        unset($_SESSION["execmsg"]);
    } else if ($execusionmsg == 2) {
        $smarty->assign("msg1", "يوجد خطأ");
        $smarty->assign("msg2", "لقد حدث خطأ اثناء اجراء العملية");
        $smarty->assign("showmsg", 1);
        unset($_SESSION["execmsg"]);
    }



    //my js
    $smarty->assign("workshoptransport", 1);
    $smarty->display("workshopview/transfer.html");
}
##fatma transfer bills show
elseif ($do == "receive") {
    //here the permssion check
    include_once("../public/authentication.php");
    //Transaction
    $mytransactions = new Transaction ();

    try {
        $id = receive();
        $mytransactions->commit();
        //$_SESSION["execmsg"] = 1;
        //header("location:?do=billtransport");
        $id = encrypt_url($id);
        header("location:workshoptransport.php?do=printorder&id=" . $id);
    } catch (Exception $e) {

        $mytransactions->rollback();
        $_SESSION["execmsg"] = 2;
        header("location:?do=billtransport");
    }
}
##fatma transfer bills show
elseif ($do == "deliver") {
    //here the permssion check
    include_once("../public/authentication.php");
    //Transaction
    $mytransactions = new Transaction ();

    try {
        $id = deliver();
        $mytransactions->commit();
        $id = encrypt_url($id);
        //$_SESSION["execmsg"] = 1;
        //header("location:?do=billtransport");
        header("location:workshoptransport.php?do=printorder&id=" . $id);
    } catch (Exception $e) {

        $mytransactions->rollback();
        $_SESSION["execmsg"] = 2;
        header("location:?do=billtransport");
    }
}
##
elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("customValidation", 1);

$smarty->display("footer.html");

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

function add() {
    global $workshop;
    global $workshopDAO;


    $name = $_POST['name'];
    $description = $_POST['description'];

    $workshop->name = $name;
    $workshop->description = $description;
    $workshop->thedate = date("Y-m-d");
    $workshop->userid = $_SESSION['userid'];
    $workshop->del = 0;

    $workshopDAO->insert($workshop);
}

//show tabel data
function show() {
    global $workshop;
    global $workshopDAO;

    global $smarty;

    $workshops = $workshopDAO->queryAll();
    $smarty->assign('workshops', $workshops);
}

// edit row
function edit() {
    global $workshop;
    global $workshopDAO;

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

//update row
function update() {
    global $workshop;
    global $workshopDAO;

    $userID = $_SESSION['userid'];
    $id = $_POST['id'];
    $name = $_POST['name'];
    $description = $_POST['description'];

    $workshop->name = $name;
    $workshop->description = $description;
    $workshop->thedate = date("Y-m-d");
    $workshop->userid = $_SESSION['userid'];
    $workshop->del = 0;
    $workshop->id = $id;


    $workshopDAO->update($workshop);
}

// temp delte row
function delete($id) {
    global $workshop;
    global $workshopDAO;

    global $smarty;

    $id = $_GET['id'];
    //1- check if there are any asset cat  associated with asset
    $alldata = $workshopDAO->delete($id);
}

function receive($id) {
    //Toworkshoporder
    global $toWorkshopOrder;
    global $toWorkshopOrderDAO;
    //Toworkshoporderbill
    global $toWorkshopOrderBill;
    global $toWorkshopOrderBillDAO;
    //bill
    global $bills;
    global $billsDAO;
    global $billsEX;

    global $billsProductsEX;

    $choosenOrders = $_POST["choosedItem_2"];
    $driverId = filter_input(INPUT_POST, "driver_2");
    //$branch = filter_input(INPUT_POST, "branch_2");
    //$deliveryDate = filter_input(INPUT_POST, "deliveryDate");
    $recieveWorkshopDate = filter_input(INPUT_POST, "recieveWorkshopDate");
    if (!isset($recieveWorkshopDate) || empty($recieveWorkshopDate)) {
        $recieveWorkshopDate = date("Y-m-d H:i:s");
    }
    $ids = '';
    foreach ($choosenOrders as $pro) {
        $ids .= $pro . ',';
        $toWorkshopOrder = $toWorkshopOrderDAO->load($pro);
        $toWorkshopOrder->orderStatus = 1;
        $toWorkshopOrder->recieveWorkshopDate = $recieveWorkshopDate;
        $toWorkshopOrder->deliverId = $driverId;
        $hours = dateTimeDiff($toWorkshopOrder->recieveWorkshopDate, $toWorkshopOrder->deliverWorkshopDate);
        if ($hours > $toWorkshopOrder->drivertimeout) {
            $toWorkshopOrder->driverdelay = $hours;
        } else {
            $toWorkshopOrder->driverdelay = 0;
        }
        $toWorkshopOrderDAO->update($toWorkshopOrder);
        $toWorkshopOrderBill = $toWorkshopOrderBillDAO->queryByToworkshoporderid($pro);
        foreach ($toWorkshopOrderBill as $aBill) {
            $billsEX->updateBillStatus(2, $aBill->billid); //status2 means at work shop recive
        }
    }
    $ids = rtrim($ids, ",");
    return $ids;
}

function deliver($id) {
    //Toworkshoporder
    global $toWorkshopOrder;
    global $toWorkshopOrderDAO;
    //Toworkshoporderbill
    global $toWorkshopOrderBill;
    global $toWorkshopOrderBillDAO;
    //bill
    global $bills;
    global $billsDAO;
    global $billsEX;

    global $billsProductsEX;

    $choosenOrders = $_POST["choosedItem_3"];
    $driverId = filter_input(INPUT_POST, "driver_3");
    $ids = '';
    foreach ($choosenOrders as $pro) {
        $ids .= $pro . ',';
        $toWorkshopOrder = $toWorkshopOrderDAO->load($pro);
        $toWorkshopOrder->orderStatus = 2;
        $toWorkshopOrder->deliverBranchDate = date("Y-m-d H:i:s");
        $toWorkshopOrder->driverIdBack = $driverId;
        $hours = dateTimeDiff($toWorkshopOrder->deliverBranchDate, $toWorkshopOrder->recieveWorkshopDate);
        if ($hours > $toWorkshopOrder->workshoptimeout) {
            $toWorkshopOrder->workshopdelay = $hours;
        } else {
            $toWorkshopOrder->workshopdelay = 0;
        }
        $toWorkshopOrderDAO->update($toWorkshopOrder);
        $toWorkshopOrderBill = $toWorkshopOrderBillDAO->queryByToworkshoporderid($pro);
        foreach ($toWorkshopOrderBill as $aBill) {
            $billsEX->updateBillStatus(3, $aBill->billid); //status2 means at work shop recive
        }
    }
    $ids = rtrim($ids, ",");
    return $ids;
}

function encrypt_url($string) {
    $key = "FATma_979805"; //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_url($string) {
    $key = "FATma_979805"; //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;
}

function dateTimeDiff($dateTime1, $dateTime2) {
    $dateTime1 = new DateTime($dateTime1);
    $dateTime2 = new DateTime($dateTime2);

    $diff = $dateTime2->diff($dateTime1);
    $hours = $diff->h;
    $hours = $hours + ($diff->days * 24);
    return $hours;
}

?>