<?php

//the global file operation
include("../public/impOpreation.php");
//Transaction
include_once("../models/sql/Transaction.class.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

  ======================== */
if ($do != "printorder") {
    //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();

//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

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

//check and use the condition that suite this action
if (empty($do)) {
//here the permssion check
    include_once ("../public/authentication.php");

    #########################################نقل الى الورش
    $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);
    $queryString2 = '';
    $ordersAtWorkshop_2 = $toWorkshopOrderEX->queryByOrderStatusEX(2, $queryString2);
    foreach ($ordersAtWorkshop_2 as $data) {
        ##عامل التوصيل "السائق"
        $driver = $userDAO->load($data->driverId);
        $data->driverId = $driver->employeename;
        ##الفرع
        $branch = $BranchDAO->load($data->branchId);
        $data->branchId = $branch->branchName;
    }
    $smarty->assign('ordersAtWorkshop_2', $ordersAtWorkshop_2);

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

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

    ##كل الطلبيات
    $allOrders = $toWorkshopOrderDAO->queryAll();
    foreach ($allOrders as $data) {
        ##الفرع
        $branch = $BranchDAO->load($data->branchId);
        $data->branchId = $branch->branchName;
        $data->orderStatus = getStatus($data->orderStatus);
    }
    $smarty->assign('allOrders', $allOrders);

    $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"]);
    }
    //here the smarty templates
    $smarty->display("workshoptransportview/add.html");
} elseif ($do == "orderdetails") {
    $id = filter_input(INPUT_GET, "id");
    $order = $toWorkshopOrderDAO->load($id);
    $orderbills = array();
    $orderBillsSimple = $toWorkshopOrderBillDAO->queryByToworkshoporderid($id);
    foreach ($orderBillsSimple as $myBill) {
        $bill = $billsDAO->load($myBill->billid);
        ## client name
        $client = $clientDAO->load($bill->clientid);
        $bill->clientname = $client->clientname;
        ## get products
        $productNo = 0;
        $productName = "";
        $products = $billsProductsEX->getproducts($bill->id, 0);
        $categories;
        foreach ($products as $pro) {
            $productNo += $pro->productno;

            $product = $productDAO->load($pro->productid);
            $pro->productName = $product->productName;
            $productCat = $productCatDAO->load($product->productCatId);
            $pro->productCatName = $productCat->productCatName;

            $parentId = $product->productCatId;
            $pathArr = getProductPath_recursive($parentId, $categories, 0);
            $productName .= "عدد " . $productNo . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $product->productName . '/' . $pathArr . "<br/>";
        }
        $productName = rtrim($productName, " - ");
        $bill->deleted = $productName;
        $bill->billstatus = $productNo;

        if (!empty($bill->id)) {
            array_push($orderbills, $bill);
        }
    }

    ##عامل التوصيل "السائق"
    $drivers = $userEX->queryWithGroupId(7);
    $smarty->assign("drivers", $drivers);
    ##الورشة
    $workshops = $workshopDAO->queryAll();
    $smarty->assign("workshops", $workshops);
    ##عامل التوصيل
    $deliveryWorkers = $userEX->queryWithGroupId(6);
    $smarty->assign("deliveryWorkers", $deliveryWorkers);
    $smarty->assign("order", $order);

    $smarty->assign("orderbills", $orderbills);
    //here the smarty templates
    $smarty->display("workshoptransportview/orderdetail.html");
} elseif ($do == "printorder") {
    $allIDs = filter_input(INPUT_GET, "id");
    $allIDs = decrypt_url($allIDs);
    $allIDs = explode(",", $allIDs);
    if (!empty($allIDs)) {
        ##عامل التوصيل "السائق"
        $drivers = $userEX->queryWithGroupId(7);
        $smarty->assign("drivers", $drivers);
        ##الورشة
        $workshops = $workshopDAO->queryAll();
        $smarty->assign("workshops", $workshops);
        ##عامل التوصيل
        $deliveryWorkers = $userEX->queryWithGroupId(6);
        $smarty->assign("deliveryWorkers", $deliveryWorkers);
        $smarty->assign("order", $order);
        foreach ($allIDs as $id) {
            $order = $toWorkshopOrderDAO->load($id);
            $orderbills = array();
            $orderBillsSimple = $toWorkshopOrderBillDAO->queryByToworkshoporderid($id);
            foreach ($orderBillsSimple as $myBill) {
                $bill = $billsDAO->load($myBill->billid);
                ## client name
                $client = $clientDAO->load($bill->clientid);
                $bill->clientname = $client->clientname;

                //# load names of all product cats which belongs to this product .
                $billsProductsReport = $billsProductsDAO->queryByBillid($bill->id);
                $productDetails = $productDAO->load($billsProductsReport[0]->productid);

                $productCatDetails = $productCatDAO->load($productDetails->productCatId);

                $productCat_parent = $productCatDetails->productCatParent;
                $productCat_names = '';
                $productCat_names = $productCatDetails->productCatName . ' - ';


                if ($productCat_parent == 0) {

                } else {
                    $productCatId = $productCatDetails->productCatParent;
                    $productCat_names = getproductcatdetails($productCatId, $productCat_names);
                }

                ## get products
                $productNo = 0;
                $productName = "";
                $products = $billsProductsEX->getproducts($bill->id, 0);
                foreach ($products as $pro) {
                    $productNo += $pro->productno;
                    //$productName .= $pro->deleted . " - ";
                    $productName .= $pro->deleted . " - " . $productCat_names;
                }
                $productName = rtrim($productName, " - ");
                $bill->deleted = $productName;
                $bill->billstatus = $productNo;

                if (!empty($bill->id)) {
                    $bill->id = $order->id;
                    array_push($orderbills, $bill);
                }
            }
            $smarty->assign("order", $order);
            $smarty->assign("orderbills", $orderbills);
            //here the smarty templates
            $smarty->display("workshoptransportview/print.html");
        }
    }
} 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("workshoptransport", 1);

if ($do != "printorder") {
    $smarty->display("footer.html");
}

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

function getStatus($status) {

    $stMsg = "";
    switch ($status) {
        case 0:
            $stMsg = "تحت التوصيل للورشة";
            break;
        case 1:
            $stMsg = "تحت التصنيع فى الورشة";
            break;
        case 2:
            $stMsg = "تحت التوصيل للفرع";
            break;
        case 3:
            $stMsg = "منتهى";
            break;

        default:
            break;
    }
    return $stMsg;
}

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 getproductcatdetails($productCatId, $productCat_names) {

    global $productCatDAO;

    $productCatDetails = $productCatDAO->load($productCatId);


    $productCat_parent = $productCatDetails->productCatParent;
    $productCat_names = trim($productCat_names, ' - ');
    $productCat_names .= ' - ' . $productCatDetails->productCatName;

    if ($productCat_parent != 0) {

        $productCatId = $productCatDetails->productCatParent;
        $productCat_names = getproductcatdetails($productCatId, $productCat_names);
    }


    return $productCat_names;
}

function getProductPath_recursive($parentid, $categories, $level) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0 && $level < 2) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        return getProductPath_recursive($newParentId, $categories, ($level + 1));
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

?>