<?php

//the global file operation
include("../public/impOpreation.php");
include("../library/class.upload.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");

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

require_once('../models/dao/ProjectDAO.class.php');
require_once('../models/dto/Project.class.php');
require_once('../models/mysql/ProjectMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectMySqlExtDAO.class.php');


require_once('../models/dao/CostcenterDAO.class.php');
require_once('../models/dto/Costcenter.class.php');
require_once('../models/mysql/CostcenterMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterMySqlExtDAO.class.php');

//Accountstree
require_once('../models/dao/AccountstreeDAO.class.php');
require_once('../models/dto/Accountstree.class.php');
require_once('../models/mysql/AccountstreeMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountstreeMySqlExtDAO.class.php');

//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');


####Projectexchmaterial
require_once('../models/dao/ProjectexchmaterialreturnDAO.class.php');
require_once('../models/dto/Projectexchmaterialreturn.class.php');
require_once('../models/mysql/ProjectexchmaterialreturnMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectexchmaterialreturnMySqlExtDAO.class.php');

#####Projectexchmaterialdetail
require_once('../models/dao/ProjectexchmaterialdetailreturnDAO.class.php');
require_once('../models/dto/Projectexchmaterialdetailreturn.class.php');
require_once('../models/mysql/ProjectexchmaterialdetailreturnMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectexchmaterialdetailreturnMySqlExtDAO.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');

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


include_once("dailyentryfun.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 :- productCatController

  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
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

$Project = new Project();
$ProjectDAO = new ProjectMySqlDAO();
$ProjectEx = new ProjectMySqlExtDAO();

//Costcenter
$Costcenter = new Costcenter();
$CostcenterDAO = new CostcenterMySqlDAO();
$CostcenterEx = new CostcenterMySqlExtDAO();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();



//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

###Projectexchmaterial
$Projectexchmaterial = new Projectexchmaterialreturn();
$ProjectexchmaterialDAO = new ProjectexchmaterialreturnMySqlDAO();
$ProjectexchmaterialEx = new ProjectexchmaterialreturnMySqlExtDAO();

####Projectexchmaterialdetail
$Projectexchmaterialdetail = new Projectexchmaterialdetailreturn();
$ProjectexchmaterialdetailDAO = new ProjectexchmaterialdetailreturnMySqlDAO();
$ProjectexchmaterialdetailEx = new ProjectexchmaterialdetailreturnMySqlExtDAO();
$today = date("Y-m-d");

//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
$Storedetail = new Storedetail();
//Store
$myStoreRecord = new StoreMySqlDAO();

//Product
$productDAO = new ProductMySqlDAO();
$ProductEX = new ProductMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();

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

    ##### store
    $storeData = $myStoreRecord->queryByConditions(0);
    $smarty->assign("storeData", $storeData);

    ####serial
    $serialno = getserails();
    $smarty->assign("serialno", $serialno);
    ##########storenegative
    $smarty->assign("storenegative", $_SESSION['storenegative']);
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $smarty->assign("today", date('Y-m-d'));
    $smarty->assign("projectValidation", 1);
    $smarty->display("projectoperationreturnview/add.html");
}
##show
elseif ($do == 'show') {
    //here the permission check
    include_once("../public/authentication.php");


    $projectid = filter_input(INPUT_POST, "projectname");
    $serialno = filter_input(INPUT_POST, "serialno");
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");

    $queryString = " where 1 ";
    if (isset($projectid) && !empty($projectid)) {
        $queryString .= " and projectexchmaterialreturn.projectid = " . $projectid;
    }
    if (isset($serialno) && !empty($serialno)) {
        $queryString .= " and projectexchmaterialreturn.serilno = " . $serialno;
    }
    if (isset($datefrom) && !empty($datefrom)) {
        $queryString .= ' and projectexchmaterialreturn.projdate >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= ' and projectexchmaterialreturn.projdate <= "' . $dateto . '" ';
    }
    $alldata = $ProjectexchmaterialEx->queryAllEX($queryString);

    $smarty->assign("alldata", $alldata);

    $smarty->assign("projectValidation", 1);
    $smarty->display("projectoperationreturnview/show.html");
}
##add
elseif ($do == 'add') {
    //here the permission check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
##edit
elseif ($do == 'edit') {
    //here the permission check
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id', FILTER_DEFAULT);

    $smarty->assign("storenegative", $_SESSION['storenegative']);

    $editelement = $ProjectexchmaterialDAO->load($id);
    $smarty->assign("editelement", $editelement);


    $allproductData = $ProjectexchmaterialdetailDAO->queryByProjectexchid($id);
    foreach ($allproductData as $data) {
        $productData = $productDAO->load($data->productid);
        $productName = $productData->productName;
        $data->productName = $productName;
    }
    $smarty->assign("allproductData", $allproductData);
    $smarty->assign("allproductcount", count($allproductData));
    #######get project name
    $projectData = $ProjectDAO->load($editelement->projectid);
    $smarty->assign("projectData", $projectData);

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

    ##### store
    $storeData = $myStoreRecord->queryByConditions(0);
    $smarty->assign("storeData", $storeData);

    $smarty->assign("projectValidation", 1);
    $smarty->display("projectoperationreturnview/edit.html");
}
##update
elseif ($do == "update") {
    //here the permission check
    include_once("../public/authentication.php");
    try {
        // here the function that do the action
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
##delete
elseif ($do == 'delete') {
    include_once("../public/authentication.php");
#####var
    $id = filter_input(INPUT_GET, 'id', FILTER_DEFAULT);

    try {
        // here the function that do the action
        ####delete
        delete($id);

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

    //here the smarty templates
    $smarty->display("succes.html");
}
##error
elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}


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

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

function add($id) {
    global $ProjectexchmaterialEx;
    global $ProjectexchmaterialDAO;
    global $Projectexchmaterial;
    global $Projectexchmaterialdetail;
    global $ProjectexchmaterialdetailDAO;
    global $accountsTreeDAO;
    global $ProjectDAO;


    ///var
    $serialno = filter_input(INPUT_POST, 'serialno', FILTER_DEFAULT);
    $storeid = filter_input(INPUT_POST, 'storeid', FILTER_DEFAULT);
    $projectid = filter_input(INPUT_POST, 'projectname', FILTER_DEFAULT);
    $billdate = filter_input(INPUT_POST, 'billdate', FILTER_DEFAULT);
    $totalpronumber = filter_input(INPUT_POST, 'totalpronumber', FILTER_DEFAULT);
    $finaltotalprice = filter_input(INPUT_POST, 'finaltotalprice', FILTER_DEFAULT);

    $offerhidden_itr = filter_input(INPUT_POST, 'offerhidden_itr', FILTER_DEFAULT);

    #######get project name
    $projectData = $ProjectDAO->load($projectid);
    $projectName = $projectData->name;


    $treeData = $accountsTreeDAO->queryByName($projectName);
    $treeSupplies = $accountsTreeDAO->queryByName('بضاعة تحت التسوية (' . $projectName . ')');

    if (count($treeData) == 0) {
        ###insert into treee ----- مدينون
        $treeid = addTreeElement($projectName, 23, 3, 0, 1, $notes = '', $theOrder = 0, $theValue = $finaltotalprice);

        ###insert into tree ----- خصوم
        $treeproid = addTreeElement('بضاعة تحت التسوية (' . $txtName . ')', 39, 1, 0, 1, $notes = '', $theOrder = 0, $theValue = $finaltotalprice);
    } else {
        $treeid = $treeData[0]->id;
        $treeproid = $treeSupplies[0]->id;
    }


    #####insert in dataentry
    $entryid = entryinsert_data($projectName, $finaltotalprice, $treeid, $treeproid);

    ######Projectexchmaterial
    $Projectexchmaterial->serilno = $serialno;
    $Projectexchmaterial->projectid = $projectid;
    $Projectexchmaterial->storeid = $storeid;
    $Projectexchmaterial->projdate = $billdate;
    $Projectexchmaterial->sysdate = date("Y-m-d");
    $Projectexchmaterial->totalnum = $totalpronumber;
    $Projectexchmaterial->totalbuyprice = $finaltotalprice;
    $Projectexchmaterial->entryid = $entryid;

    if (empty($id)) {
        $projmaterialid = $ProjectexchmaterialDAO->insert($Projectexchmaterial);
    } else {
        $Projectexchmaterial->id = $id;
        $projmaterialid = $ProjectexchmaterialEx->insertWithID($Projectexchmaterial);
    }


    ######Projectexchmaterialdetail
    for ($i = 1; $i <= $offerhidden_itr; $i++) {

        $productid = filter_input(INPUT_POST, 'projectproudctid' . $i);
        $productnumber = filter_input(INPUT_POST, 'productnumber' . $i);
        $probuyprice = filter_input(INPUT_POST, 'probuyprice' . $i);


        if (empty($productid)) {

            continue;
        }


        ####$Projectexchmaterialdetail
        $Projectexchmaterialdetail->projectexchid = $projmaterialid;
        $Projectexchmaterialdetail->productid = $productid;
        $Projectexchmaterialdetail->pronumber = $productnumber;
        $Projectexchmaterialdetail->probuyprice = $probuyprice;
        $ProjectexchmaterialdetailDAO->insert($Projectexchmaterialdetail);


        if (isset($productid) && $productid != '-1') {


            //////////////--Store From--///////////////////////////
            //get storefrom productquantity before change
            $storedetailFromData = getStoredetailData($storeid, $productid);

            $allStoredetailFromData = $storedetailFromData[0];
            $storedetailFromId = $storedetailFromData[1];
            $productquantityFromBefore = $storedetailFromData[2];

            //update productquantity in storedetail
            $productquantityFromAfter = increaseProductQuantity($storedetailFromId, $productquantityFromBefore, $productnumber);

            //insert in storereport
            insertStorereport($productid, $storeid, $productnumber, $productquantityFromBefore, $productquantityFromAfter, 0, $projmaterialid, "مرتجع صرف مواد للمشروع", "projectoperationControllerreturn.php");


            //update productquantity in storedetail
            /* $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $productnumber);


              //insert in storereport
              insertStorereport($productid, $storeid, $productnumber, $productquantityFromBefore, $productquantityFromAfter, 1, $projmaterialid, "مرتجع صرف مواد للمشروع", "projectoperationControllerreturn.php"); */
        }
    }
}

function update() {
    $editid = filter_input(INPUT_POST, 'editid', FILTER_DEFAULT);
    delete($editid);
    add($editid);
}

function delete($id) {
    global $ProjectexchmaterialDAO;
    global $Projectexchmaterial;
    global $Projectexchmaterialdetail;
    global $ProjectexchmaterialdetailDAO;
    global $accountsTreeDAO;
    global $ProjectDAO;

    $Projectexchmaterial = $ProjectexchmaterialDAO->load($id);

    #######get project name
    $projectData = $ProjectDAO->load($Projectexchmaterial->projectid);
    $projectName = $projectData->name;
    $finaltotalprice = $Projectexchmaterial->totalbuyprice;

    $treeData = $accountsTreeDAO->queryByName($projectName);
    $treeSupplies = $accountsTreeDAO->queryByName('بضاعة تحت التسوية (' . $projectName . ')');

    if (count($treeData) == 0) {
        ###insert into treee ----- مدينون
        $treeid = addTreeElement($projectName, 23, 3, 0, 1, $notes = '', $theOrder = 0, $theValue = $finaltotalprice);

        ###insert into tree ----- خصوم
        $treeproid = addTreeElement('بضاعة تحت التسوية (' . $txtName . ')', 39, 1, 0, 1, $notes = '', $theOrder = 0, $theValue = $finaltotalprice);
    } else {
        $treeid = $treeData[0]->id;
        $treeproid = $treeSupplies[0]->id;
    }


    #####insert in dataentry
    $entryid = entryinsert_data_reverse($projectName, $finaltotalprice, $treeid, $treeproid);

    ######Projectexchmaterialdetail
    $details = $ProjectexchmaterialdetailDAO->queryByProjectexchid($id);
    $storeid = $Projectexchmaterial->storeid;
    foreach ($details as $value) {
        if (isset($value->productid) && $value->productid != '-1') {
            $productid = $value->productid;
            $productnumber = $value->pronumber;

            //////////////--Store From--///////////////////////////
            //get storefrom productquantity before change
            $storedetailFromData = getStoredetailData($storeid, $productid);

            $allStoredetailFromData = $storedetailFromData[0];
            $storedetailFromId = $storedetailFromData[1];
            $productquantityFromBefore = $storedetailFromData[2];


            //update productquantity in storedetail
            $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $productnumber);


            //insert in storereport
            insertStorereport($productid, $storeid, $productnumber, $productquantityFromBefore, $productquantityFromAfter, 1, $id, "حذف مرتجع صرف مواد للمشروع", "projectoperationControllerreturn.php");

            $ProjectexchmaterialdetailDAO->delete($value->id);
        }
    }

    $ProjectexchmaterialDAO->delete($id);
}

function entryinsert_data($projectname, $value, $clientid, $projectid) {

    global $dailyEntry;
    global $dailyEntryCreditor;
    global $dailyEntryDebtor;

    ########## nsert into entry
    $dailyEntry->entryComment = 'تم ارجاع صرف مواد للمشروع';

    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $value;
    $dailyEntryDebtor->accountstreeid = $projectid;
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);


    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $value;
    $dailyEntryCreditor->accountstreeid = $clientid;
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

    $entryData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
    return $entryData[1];
}

function entryinsert_data_reverse($projectname, $value, $clientid, $projectid) {

    global $dailyEntry;
    global $dailyEntryCreditor;
    global $dailyEntryDebtor;

    ########## nsert into entry
    $dailyEntry->entryComment = 'الغاء ارجاع صرف مواد للمشروع';

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $value;
    $dailyEntryCreditor->accountstreeid = $projectid;
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $value;
    $dailyEntryDebtor->accountstreeid = $clientid;
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);


    $entryData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
    return $entryData[1];
}

function editInTree($txtName, $txtDebt, $treeid) {
    global $accountsTreeDAO;
    global $accountsTree;
    ###update into tree
    $getRow = $accountsTreeDAO->load($treeid);

    $accountsTree->name = $txtName;
    $accountsTree->customName = $txtName;
    $accountsTree->id = $treeid;
    $accountsTree->del = $getRow->del;
    $accountsTree->itemfrom = $getRow->itemfrom;
    $accountsTree->itemtype2 = $getRow->itemtype2;
    $accountsTree->layingOrder = $getRow->layingOrder;
    $accountsTree->sysdate = $getRow->sysdate;
    $accountsTree->notes = $getRow->notes;
    $accountsTree->parent = $getRow->parent;
    $accountsTree->theOrder = $getRow->theOrder;
    $accountsTree->theValue = $txtDebt;
    $accountsTree->userid = $getRow->userid;

    editTreeElement($accountsTree);
}

function getserails() {
    global $ProjectexchmaterialEx;

    function generateRandomString($length = 4) {
        $newnum = substr(str_shuffle("0123456789"), 0, $length);
        return date("Y") . '' . $newnum;
    }

    $number = generateRandomString();

    //to make sure there are no duplicate serails

    $checkifthere = $ProjectexchmaterialEx->queryAllbyserialno($number);
    if (count($checkifthere) > 0) {
        $number = generateRandomString();
    }

    return $number;
}

function getStoredetailData($storeid, $productid) {
    global $myStoredetailEx;

    //select data from storerawmaterialdetails by storeid and rawmaterialid
    $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

    $storedetailId = $storedetailData->storedetailid;
    $productquantityBefore = $storedetailData->productquantity;

    return array($storedetailData, $storedetailId, $productquantityBefore);
}

function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;

    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

function returndatatoStore($billid) {
    global $ProjectexchmaterialDAO;
    global $ProjectexchmaterialdetailDAO;


    $editelement = $ProjectexchmaterialDAO->load($billid);
    $storeid = $editelement->storeid;
    $allproductData = $ProjectexchmaterialdetailDAO->queryByProjectexchid($billid);
    foreach ($allproductData as $data) {
        $productid = $data->productid;
        $productnumber = $data->productnumber;
        $storedetailFromData = getStoredetailData($storeid, $productid);

        $allStoredetailFromData = $storedetailFromData[0];
        $storedetailFromId = $storedetailFromData[1];
        $productquantityFromBefore = $storedetailFromData[2];

        //update productquantity in storedetail
        $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $productnumber);
    }
}

function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;

    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

?>