<?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");
include("../library/uploadImages.php");
include '../library/Classes/PHPExcel/IOFactory.php';

//Productionrate
require_once('../models/dao/ProductionrateDAO.class.php');
require_once('../models/dto/Productionrate.class.php');
require_once('../models/mysql/ProductionrateMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateMySqlExtDAO.class.php');
//Productionrateproduct
require_once('../models/dao/ProductionrateproductDAO.class.php');
require_once('../models/dto/Productionrateproduct.class.php');
require_once('../models/mysql/ProductionrateproductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateproductMySqlExtDAO.class.php');

//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.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');

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 :- productionRateController

  OPERTATION in Controller///////////////////////////////////////////////////

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


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

//here goes the instances and general variables
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productionrate
$productionrate = new Productionrate();
$productionrateDAO = new ProductionrateMySqlDAO();
$productionrateEX = new ProductionrateMySqlExtDAO();

//Productionrateproduct
$Productionrateproduct = new Productionrateproduct();
$ProductionrateproductDAO = new ProductionrateproductMySqlDAO();
$ProductionrateproductEX = new ProductionrateproductMySqlExtDAO();

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

//Productunit
$productUnitExt = new ProductunitMySqlExtDAO();

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

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



$ProgramsettingDAO = new ProgramsettingsMySqlDAO();



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

    //$rows=$productExt->GetRawMaterials();


    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $smarty->assign("customProductionEquation", 1);
    //$smarty->assign("rows", $rows);
    $smarty->display("productionEquationView/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");



    try {
        $total = add();
        if ($total == 100) {
            header("location:?do=sucess");
        } else {
            $msg = "لابد ان يكون مجموع النسب يساوى 100";
            $smarty->assign("msg", $msg);

            $rows = $productExt->GetRawMaterials();
            $smarty->assign("rows", $rows);

            $smarty->display("productionEquationView/add.html");
            //print_r($total);
        }
    } catch (Exception $e) {
//        var_dump($e);
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    $id = $_GET["id"];
    $productionrate = $productionrateDAO->load($id);
    $Productionrateproduct = $ProductionrateproductEX->queryAllByProductionRateId($id);


    $i = 1;
    foreach ($Productionrateproduct as $p) {
        $product = $productExt->loadSizeColor($p->productId, $p->sizeid, $p->colorid);
        $productCat = $productCatDAO->load($product->productCatId);
        ##
        $oldfinalproductname = $product->productName . '/ ' . $productCat->productCatName;
        if (!empty($product->sizeName))
            $oldfinalproductname .= '/ ' . $product->sizeName;
        if (!empty($product->colorName))
            $oldfinalproductname .= '/ ' . $product->colorName;
        $p->productName = $oldfinalproductname;



        $productUnitData = $productUnitExt->queryWithProductId($p->productId);
        $smarty->assign("productUnitData" . $i, $productUnitData);
        $i++;
    }
    $smarty->assign("noOfRows", count($Productionrateproduct));
    $smarty->assign("Productionrateproduct", $Productionrateproduct);


    /* print_r("<pre>");
      print_r($productUnitData);
      print_r("</pre>"); */
    $product = $productExt->loadSizeColor($productionrate->finalName, $productionrate->sizeid, $productionrate->colorid);
    $productCat = $productCatDAO->load($product->productCatId);
    ##
    $oldfinalproductname = $product->productName . '/ ' . $productCat->productCatName;
    if (!empty($product->sizeName))
        $oldfinalproductname .= '/ ' . $product->sizeName;
    if (!empty($product->colorName))
        $oldfinalproductname .= '/ ' . $product->colorName;

    $smarty->assign("oldfinalproduct", $product);
    $smarty->assign("oldfinalproductname", $oldfinalproductname);


    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);


    $smarty->assign("productionrate", $productionrate);
    $smarty->assign("customProductionEquation", 1);

    $smarty->assign("customProductionEquationedit", 1);
    $smarty->display("productionEquationView/editEquation.html");
    //print_r($Productionrateproduct->conditions);
} elseif ($do == "update") {
    try {
        $total = update();
        if ($total == 100) {
            header("location:?do=sucess");
        } else {

            $msg = "لابد ان يكون مجموع النسب يساوى 100";
            $smarty->assign("msg", $msg);

            $rows = $productExt->GetRawMaterials();
            $smarty->assign("rows", $rows);

            $smarty->display("productionEquationView/add.html");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "details") {
    $id = $_GET["id"];
    $productionrate = $productionrateDAO->load($id);
    $Productionrateproduct = $ProductionrateproductEX->queryAllByProductionRateId($id);

    //Productunit
    $productUnitExt = new ProductunitMySqlExtDAO();
    $i = 1;
    foreach ($Productionrateproduct as $p) {
        $productUnitData = $productUnitExt->queryWithProductId($p->productId);
        $smarty->assign("productUnitData" . $i, $productUnitData);
        $i++;
    }
    $product = $productDAO->load($productionrate->finalName);
    $productCat = $productCatDAO->load($product->productCatId);

    $smarty->assign("oldfinalproduct", $productionrate->finalName);
    $smarty->assign("oldfinalproductname", $product->productName . '/ ' . $productCat->productCatName);


    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);


    $rows = @($productExt->GetRawMaterials());
    $smarty->assign("rows", $rows);

    $smarty->assign("noOfRows", count($Productionrateproduct));

    $smarty->assign("productionrate", $productionrate);
    $smarty->assign("Productionrateproduct", $Productionrateproduct);

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

    $smarty->assign("customProductionEquationedit", 1);
    $smarty->display("productionEquationView/details.html");
} elseif ($do == "show") {
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $rows = $productionrateDAO->queryAll();

    $smarty->assign("rows", $rows);
    $smarty->display("productionEquationView/show.html");
} elseif ($do == "stop") {
    try {

        stop_active();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "delete") {

    try {

        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "addexcel") {
    //here the permssion check
    include_once("../public/authentication.php");

    //here the smarty templates
    $smarty->display("productionEquationView/uploadexcel.html");
} elseif ($do == "addfromexcel") {
    include_once("../public/authentication.php");
    try {
        addFromExcel();
        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");
}
//here the global templates
//$smarty->assign("productScripts",1);

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







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

//add production rate products
function addproductionrateproducts($productionrateid) {
    global $Productionrateproduct;
    global $ProductionrateproductDAO;
    global $ProductionrateproductEX;

    $rowitr = $_POST["rowitr"];


    for ($i = 1; $i <= $rowitr; $i++) {
//        if (strlen($_POST["input" . $i . ""]) <= 0) {
//            //it means a row deleted by js or empty percentage (isnot important for me)
//        } else {

        if (isset($_POST["product" . $i . ""]) && !empty($_POST["product" . $i . ""]) && $_POST["product" . $i . ""] != -1) {
            if (isset($_POST["unitId" . $i . ""]) && !empty($_POST["unitId" . $i . ""]) && $_POST["unitId" . $i . ""] != -1) {
                $productId = $_POST["product" . $i . ""];
                $sizeId = 0;
                $colorId = 0;
                if (!empty($productId)) {
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                    }
                }
                $Productionrateproduct->conditions = 0;
                $Productionrateproduct->productId = $productId;
                $Productionrateproduct->productionRateId = $productionrateid;

                if (isset($_POST["inputt" . $i . ""]) && !empty($_POST["inputt" . $i . ""])) {
                    $Productionrateproduct->quantity = $_POST["inputt" . $i . ""];
                } else {
                    $Productionrateproduct->quantity = 0;
                }

                $Productionrateproduct->rate = $_POST["input" . $i . ""];

                $Productionrateproduct->unitId = $_POST["unitId" . $i . ""];
                $Productionrateproduct->thedate = date("Y-m-d");
                $Productionrateproduct->userId = $_SESSION['userid'];
                $Productionrateproduct->sizeid = $sizeId;
                $Productionrateproduct->colorid = $colorId;

                $productionRateProductId = $_POST["productionRateProductId" . $i];
                if (isset($productionRateProductId) && $productionRateProductId > 0) {
                    $Productionrateproduct->productionRateProductId = $productionRateProductId;
                    $ProductionrateproductEX->insertwithid($Productionrateproduct);
                } else {
                    $ProductionrateproductDAO->insert($Productionrateproduct);
                }
            }
        }
//        }
    }
}

//add
function add() {
    global $productionrateDAO;
    global $productionrate;
    global $Productionrateproduct;
    global $ProductionrateproductDAO;





    $rowitr = $_POST["rowitr"];
//    $totalpercentage = 0;
    $totalpercentage = 100;

    for ($i = 1; $i <= $rowitr; $i++) {
//        if (isset($_POST["input" . $i . ""]) && !empty($_POST["input" . $i . ""])) {
//            $Productionrateproduct->rate = $_POST["input" . $i . ""];
//        } else {
//            $Productionrateproduct->rate = 0;
//        }
        $Productionrateproduct->rate = 0;
        $totalpercentage += $Productionrateproduct->rate;
    }

    if ($totalpercentage == 100) {
        $productId = $_POST["finalProductId"];
        $sizeId = 0;
        $colorId = 0;
        if (!empty($productId)) {
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
        }

        $productionrate->conditions = 0;
        $productionrate->name = $_POST["name"];
        $productionrate->finalName = $productId;
        $productionrate->thedate = date("Y-m-d");
        $productionrate->userId = $_SESSION['userid'];
        $productionrate->sizeid = $sizeId;
        $productionrate->colorid = $colorId;
        $productionrateid = $productionrateDAO->insert($productionrate);

        addproductionrateproducts($productionrateid);
    }

    return $totalpercentage;
}

function addFromExcel() {
    global $productionrateDAO;
    global $productionrate;
    global $Productionrateproduct;
    global $ProductionrateproductDAO;
    global $productDAO;
    global $productUnitExt;


    ## upload file temporarely
    $handle = new upload($_FILES['pEquationSheet']);
    $excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        //$objReader->setUTFEncoder('iconv');
        //$objReader::setOutputEncoding('UTF-8');
        $objPHPExcel = $objReader->load($inputFileName);



        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        for ($row = 4; $row <= $highestRow; $row++) {
            //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $rowData = $rowData[0];

            ##getdata
            $col = 0;
            $name = $rowData[$col]; //$_POST["txtName"];
            $col++;
            $finalProductId = $rowData[$col];

            if (!empty($name) && !empty($finalProductId)) {
                $checkName = $productionrateDAO->queryByName($name);
                $checkFinalProduct = $productDAO->queryByParcode($finalProductId);
                if (count($checkName) == 0 && isset($checkFinalProduct[0]->productId) && $checkFinalProduct[0]->productId > 0) {
                    $productionrate->conditions = 0;
                    $productionrate->name = $name;
                    $productionrate->finalName = $checkFinalProduct[0]->productId;
                    $productionrate->thedate = date("Y-m-d");
                    $productionrate->userId = 1; //$_SESSION['userid'];
                    $productionrateid = $productionrateDAO->insert($productionrate);


                    ##Productionrateproducts
                    for ($i = 0; $i < 6; $i++) {//as ther are 6 Productionrateproducts defined in excel sheet for each productionequation
                        $col++;
                        $productid = $rowData[$col];
                        $col++;
                        $quantity = $rowData[$col];
                        if (isset($productid) && !empty($productid) && isset($quantity) && !empty($quantity)) {
                            $proUnit = $productUnitExt->getfirstunitt($productid);
                            if (isset($proUnit->productunitid) && $proUnit->productunitid > 0) {
                                $Productionrateproduct->conditions = 0;
                                $Productionrateproduct->productId = $productid;
                                $Productionrateproduct->productionRateId = $productionrateid;
                                $Productionrateproduct->quantity = $quantity;
                                $Productionrateproduct->rate = 0;
                                $Productionrateproduct->unitId = $proUnit->productunitid;
                                $Productionrateproduct->thedate = date("Y-m-d");
                                $Productionrateproduct->userId = 1; //$_SESSION['userid'];

                                $ProductionrateproductDAO->insert($Productionrateproduct);
                            }
                        }
                    }
                }
            }
        }





        unlink($inputFileName);
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}

//update
function update() {
    global $productionrateDAO;
    global $productionrate;
    global $Productionrateproduct;
    global $ProductionrateproductDAO;




    //get total percentage
    $rowitr = $_POST["rowitr"];
    $totalpercentage = 100;

    for ($i = 1; $i <= $rowitr; $i++) {
//        if (isset($_POST["input" . $i . ""]) && !empty($_POST["input" . $i . ""])) {
//            $Productionrateproduct->rate = $_POST["input" . $i . ""];
//        } else {
//            $Productionrateproduct->rate = 0;
//        }
        $Productionrateproduct->rate = 0;
        $totalpercentage += $Productionrateproduct->rate;
    }


    //if total percentage=100 continue
    if ($totalpercentage == 100) {
        //update productionrate
        $id = $_POST["productionrateid"];
        $productionrate = $productionrateDAO->load($id);


        $productId = $_POST["finalProductId"];
        $sizeId = 0;
        $colorId = 0;
        if (!empty($productId)) {
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
        }

        //$productionrate->conditions=0; //no change
        $productionrate->name = $_POST["name"];
        $productionrate->finalName = $productId;
        $productionrate->thedate = date("Y-m-d");
        $productionrate->userId = $_SESSION['userid'];
        $productionrate->sizeid = $sizeId;
        $productionrate->colorid = $colorId;
        $productionrateDAO->update($productionrate);




        //delete old ones in data base
        $ProductionrateproductDAO->deleteByProductionRateId($productionrate->productionRateId);


        //insert
        addproductionrateproducts($productionrate->productionRateId);
    }

    return $totalpercentage;
}

//stop
function stop_active() {
    global $productionrateDAO;
    global $productionrate;

    $id = $_GET["id"];
    $productionrate = $productionrateDAO->load($id);

    if ($productionrate->conditions == 0) {
        $productionrate->conditions = 1;
    } elseif ($productionrate->conditions == 1) {
        $productionrate->conditions = 0;
    }
    $productionrateDAO->update($productionrate);
}

//delete
function delete() {
    global $productionrateDAO;
    global $ProductionrateproductDAO;

    $id = $_GET["id"];
    print_r($id);
    $ProductionrateproductDAO->deleteByProductionRateId($id);
    $productionrateDAO->delete($id);
}

?>