<?php

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


//Expensetype
require_once('../models/dao/ExpensestypeDAO.class.php');
require_once('../models/dto/Expensestype.class.php');
require_once('../models/mysql/ExpensestypeMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensestypeMySqlExtDAO.class.php');

####Projectexchmaterial
require_once('../models/dao/ProjectexchmaterialDAO.class.php');
require_once('../models/dto/Projectexchmaterial.class.php');
require_once('../models/mysql/ProjectexchmaterialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectexchmaterialMySqlExtDAO.class.php');

#####Projectexchmaterialdetail
require_once('../models/dao/ProjectexchmaterialdetailDAO.class.php');
require_once('../models/dto/Projectexchmaterialdetail.class.php');
require_once('../models/mysql/ProjectexchmaterialdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectexchmaterialdetailMySqlExtDAO.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();


$ExpensetypeDAO = new ExpensestypeMySqlDAO();
$Expensetype = new Expensestype();
$ExpensetypeEX = new ExpensestypeMySqlExtDAO();


//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 Projectexchmaterial();
$ProjectexchmaterialDAO = new ProjectexchmaterialMySqlDAO();
$ProjectexchmaterialEx = new ProjectexchmaterialMySqlExtDAO();

####Projectexchmaterialdetail
$Projectexchmaterialdetail = new Projectexchmaterialdetail();
$ProjectexchmaterialdetailDAO = new ProjectexchmaterialdetailMySqlDAO();
$ProjectexchmaterialdetailEx = new ProjectexchmaterialdetailMySqlExtDAO();
$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("projectmaterialview/add.html");
}
##show
elseif ($do == 'show') {
    //here the permission check
    include_once("../public/authentication.php");

    $projectid = filter_input(INPUT_POST, "projectname");
    if (empty($projectid))
    $projectid = filter_input(INPUT_GET, "proid");
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");
    $casesid = filter_input(INPUT_POST, "casesid");

    $queryString = " where 1 ";
    if (isset($projectid) && !empty($projectid)) {
        $queryString .= " and projectmaterials.projectid = " . $projectid;
    } if( $_SESSION['projectids'] != 0){
        $queryString .= ' AND projectmaterials.projectid in (' . $_SESSION['projectids'] . ')';
    }
    
    if (isset($datefrom) && !empty($datefrom)) {
        $queryString .= ' and projectmaterials.sysdate >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= ' and projectmaterials.sysdate <= "' . $dateto . '" ';
    }
    
    if (isset($casesid) && !empty($casesid)) {
        $queryString .= ' and projectmaterials.casesid = ' .$casesid;
    }
    $alldata = R::findAll("projectmaterials" , " $queryString ");
    foreach ($alldata as $value) {
         $projectData = $ProjectDAO->load($value->projectid);
         $value->projectname = $projectData->name;
         $user = R::getRow('SELECT user.* FROM `user` WHERE userid = ? ',[$value->userid] );
         $value->employeename = $user['employeename'];
    }
    $smarty->assign("alldata", $alldata);

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

    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 = R::load("projectmaterials" , $id);
    $smarty->assign("editelement", $editelement);

    $allproductData = R::findAll("projectmaterialdetails" , " projectmaterialid = ? ",[$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("projectmaterialview/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");
    }
}
##del
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 $ProjectexchmaterialDAO;
    global $ProjectexchmaterialEx;
    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);
    $casesid = filter_input(INPUT_POST, 'casesid', FILTER_DEFAULT);

    $projectmaterials = R::dispense('projectmaterials');
    $projectmaterials->casesid  = $casesid;
    $projectmaterials->projectid  = $projectid;
    $projectmaterials->storeid = $storeid;
    $projectmaterials->billdate = $billdate;
    $projectmaterials->sysdate = date("Y-m-d");
    $projectmaterials->totalnum = $totalpronumber;
    $projectmaterials->totalbuyprice = $finaltotalprice;
    $projectmaterials->userid = $_SESSION['userid'];
    $projectmaterialid = R::store($projectmaterials);
    


    ######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);
        $oldimage = filter_input(INPUT_POST, 'oldimage' . $i);
        $handle = new upload($_FILES['image'. $i]);
        $imagePhoto = uploadImageswhioutresize($handle, "../upload/projectmaterials");
     
        if (empty($productid)) {continue;}
        $projectmaterialdetails = R::dispense('projectmaterialdetails');
        $projectmaterialdetails->projectmaterialid  = $projectmaterialid;
        $projectmaterialdetails->productid = $productid;
        $projectmaterialdetails->productnumber = $productnumber;
        $projectmaterialdetails->probuyprice = $probuyprice;
        if ($imagePhoto != '.') {
        $projectmaterialdetails->image = $imagePhoto;
        }else if ($oldimage) {
           $projectmaterialdetails->image = $oldimage;
        }
        R::store($projectmaterialdetails);


    }
}

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


function delete($id) {

    $projectmaterials = R::load('projectmaterials',$id);
    $projectmaterialdetails = R::findAll("projectmaterialdetails" , " projectmaterialid = ? ",[$id]);
    R::trashAll($projectmaterialdetails);
    R::trash($projectmaterials);

}

function entryinsert_data($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 entryinsert_data_reverse($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 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 = increaseProductQuantity($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;
}

?>