<?php

ob_start();
include ("../public/impOpreation.php");

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

//here the db files that include in the file
//Programsetting
require_once ('../models/dao/ProgramsettingsDAO.class.php');
require_once ('../models/dto/Programsetting.class.php');
require_once ('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once ('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');
//Billtemplate
require_once('../models/dao/BilltemplateDAO.class.php');
require_once('../models/dto/Billtemplate.class.php');
require_once('../models/mysql/BilltemplateMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplateMySqlExtDAO.class.php');
//Billtemplatedetail
require_once('../models/dao/BilltemplatedetailDAO.class.php');
require_once('../models/dto/Billtemplatedetail.class.php');
require_once('../models/mysql/BilltemplatedetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplatedetailMySqlExtDAO.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');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//get the do the action
$do = $_GET['do'];


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

//here goes the instances and general variables
//Billtemplate
$billTemplate = new Billtemplate();
$billTemplateDAO = new BilltemplateMySqlDAO();
$billTemplateEX = new BilltemplateMySqlExtDAO();
//Billtemplatedetail
$billTemplateDetail = new Billtemplatedetail();
$billTemplateDetailDAO = new BilltemplatedetailMySqlDAO();
$billTemplateDetailEX = new BilltemplatedetailMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
//check and use the condition that suites this action
if (empty($do)) {
    //here the smarty templates
    $smarty->display("billTemplateview/bill.html");
} elseif ($do == "add") {
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    $allTemplates = $billTemplateDAO->queryAll();
    $smarty->assign("allTemplates", $allTemplates);
    //here the smarty templates
    $smarty->display("billTemplateview/show.html");
} elseif ($do == "edit") {
    $id = (int) filter_input(INPUT_GET, "id");
    edit($id);
    //here the smarty templates
    $smarty->display("billTemplateview/billedit.html");
} elseif ($do == "showdetail") {
    $id = (int) filter_input(INPUT_GET, "id");
    edit($id);
    //here the smarty templates
    $smarty->display("billTemplateview/showdetail.html");
} elseif ($do == "update") {
    try {
        $id = (int) filter_input(INPUT_POST, "id");
        delete($id);
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "delete") {
    try {
        $id = (int) filter_input(INPUT_GET, "id");
        delete($id);
        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->assign("customBillTemplate", 1);

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

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

function add() {
    global $billTemplate;
    global $billTemplateDAO;
    global $billTemplateEX;
    global $billTemplateDetail;
    global $billTemplateDetailDAO;
    global $billTemplateDetailEX;


    //Transaction
    $mytransactions = new Transaction();
    try {
        $id = (int) filter_input(INPUT_POST, "id");
        $name = filter_input(INPUT_POST, "name");

        //
        $billTemplate->name = $name;
        $billTemplate->userid = $_SESSION['userid'];
        $billTemplate->sysdate = date('Y-m-d H:i:s');
        $billTemplate->del = 0;
        if ($id > 0) {
            $billTemplateEX->insertWithId($billTemplate, $id);
        } else {
            $id = $billTemplateDAO->insert($billTemplate);
        }
        //
        if (empty($name)) {
            $billTemplate->name = "نموذج " . $id;
            $billTemplateDAO->update($billTemplate);
        }
        ////////////////
        $itr = (int) filter_input(INPUT_POST, "hidden_itr");
        for ($i = 1; $i <= $itr; $i++) {
            $detailid = (int) filter_input(INPUT_POST, "detailid$i");
            var_dump("detailid$id");
            var_dump($detailid);
            $parcode = filter_input(INPUT_POST, "parcode$i");
            $sizeId = 0;
            $colorId = 0;
            $product = filter_input(INPUT_POST, "product$i");
            if (strpos($product, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product));
                $product = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }

            $unitid = (int) filter_input(INPUT_POST, "productunit$i");
            $pronum = (float) filter_input(INPUT_POST, "pronum$i");
            if (isset($parcode, $product, $pronum) && !empty($parcode) && !empty($product) && !empty($pronum)) {
                $billTemplateDetail->billTemplateId = $id;
                $billTemplateDetail->type = 0;
                $billTemplateDetail->parcode = $parcode;
                $billTemplateDetail->productid = $product;
                $billTemplateDetail->sizeid = $sizeId;
                $billTemplateDetail->colorid = $colorId;
                $billTemplateDetail->unitid = $unitid;
                $billTemplateDetail->quantity = $pronum;

                if ($detailid > 0) {
                    $billTemplateDetailEX->insertWithId($billTemplateDetail, $detailid);
                } else {
                    $billTemplateDetailDAO->insert($billTemplateDetail);
                }
            }
        }
        $itr = (int) filter_input(INPUT_POST, "returnhidden_itr");
        for ($i = 1; $i <= $itr; $i++) {
            $detailid = (int) filter_input(INPUT_POST, "detailidRet$i");
            $parcode = filter_input(INPUT_POST, "returnparcode$i");
            $sizeId = 0;
            $colorId = 0;
            $product = filter_input(INPUT_POST, "returnproduct$i");
            if (strpos($product, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product));
                $product = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            $unitid = (int) filter_input(INPUT_POST, "returnproductunit$i");
            $pronum = (float) filter_input(INPUT_POST, "returnpronum$i");
            if (isset($parcode, $product, $pronum) && !empty($parcode) && !empty($product) && !empty($pronum)) {
                $billTemplateDetail->billTemplateId = $id;
                $billTemplateDetail->type = 1;
                $billTemplateDetail->parcode = $parcode;
                $billTemplateDetail->productid = $product;
                $billTemplateDetail->sizeid = $sizeId;
                $billTemplateDetail->colorid = $colorId;
                $billTemplateDetail->unitid = $unitid;
                $billTemplateDetail->quantity = $pronum;
                if ($detailid > 0) {
                    $billTemplateDetailEX->insertWithId($billTemplateDetail, $detailid);
                } else {
                    $billTemplateDetailDAO->insert($billTemplateDetail);
                }
            }
        }

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return $id;
}

function delete($id) {
    global $billTemplate;
    global $billTemplateDAO;
    global $billTemplateDetail;
    global $billTemplateDetailDAO;


    //Transaction
    $mytransactions = new Transaction();
    try {
        $billTemplateDAO->delete($id);
        $billTemplateDetailDAO->deleteByBillTemplateId($id);

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return 1;
}

function edit($id) {
    global $billTemplateDAO;
    global $billTemplateDetailEX;
    global $myProductunitEx;
    global $smarty;


    $billTemplate = $billTemplateDAO->load($id);
    $smarty->assign("billTemplate", $billTemplate);
    //
    $billTemplateDetails = $billTemplateDetailEX->queryByBillTemplateIdEXAndType($id, 0);
    $i = 1;
    foreach ($billTemplateDetails as $mydetales) {

        $parentId = $mydetales->productCatId;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;
        if ($mydetales->sizeName != '')
            $mydetales->productName .= "/ " . $mydetales->sizeName;
        if ($mydetales->colorName != '')
            $mydetales->productName .= "/ " . $mydetales->colorName;

        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->productid);
        $smarty->assign("myunitdata" . $i, $myunitdata);
        // add sold quantity to available quantity of parcode
        $productNumber = (float) $mydetales->productnumber;
        $mydetales->don += $mydetales->sellbilldetailquantity * $productNumber;
        $i++;
    }
    $smarty->assign("billTemplateSell", $billTemplateDetails);
    $smarty->assign("itrSell", count($billTemplateDetails));
    //
    $billTemplateDetails = $billTemplateDetailEX->queryByBillTemplateIdEXAndType($id, 1);
    $i = 1;
    foreach ($billTemplateDetails as $mydetales) {

        $myreunitdata = $myProductunitEx->queryWithProductId($mydetales->productid);

        $parentId = $mydetales->productCatId;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;
        if ($mydetales->sizeName != '')
            $mydetales->productName .= "/ " . $mydetales->sizeName;
        if ($mydetales->colorName != '')
            $mydetales->productName .= "/ " . $mydetales->colorName;

        //print_r($myreunitdata);
        //print_r("<br><br>");
        $smarty->assign("myreunitdata" . $i, $myreunitdata);
        $i++;
    }
    $smarty->assign("billTemplateRet", $billTemplateDetails);
    $smarty->assign("itrRet", count($billTemplateDetails));
}

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

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

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

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