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

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

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

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


//Projectkind
require_once('../models/dao/ProjectkindDAO.class.php');
require_once('../models/dto/Projectkind.class.php');
require_once('../models/mysql/ProjectkindMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectkindMySqlExtDAO.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();


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

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

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

$dailyEntryDebtor2 = new Dailyentrydebtor();
//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();
$today = date("Y-m-d");

###Projectexchmaterial
$Projectexchmaterial = new Projectexchmaterial();
$ProjectexchmaterialDAO = new ProjectexchmaterialMySqlDAO();
$ProjectexchmaterialEx = new ProjectexchmaterialMySqlExtDAO();

//Projectkind
$myProjectkind = new Projectkind();
$myProjectkindRecord = new ProjectkindMySqlDAO();
$myProjectkindEx = new ProjectkindMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

$allprojectkind = $myProjectkindEx->queryAllconditions();
$smarty->assign("allprojectkind", $allprojectkind);
$smarty->assign("today", date("Y-m-d"));


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

    $projectstages = R::findAll('projectstages','is_active = 1 ');
    $smarty->assign('projectstages', $projectstages);

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

   $projectstages = R::findAll('projectstages','is_active = 1 ');
    $smarty->assign('projectstages', $projectstages);
    $search_params = '';
    $search_orders = ' order by project.id desc ';
    $search_joins = '';
    $search_groups = '';
    $projectid = filter_input(INPUT_POST, 'projectid');
    if ($projectid != '' && $projectid != -1) {
        $search_params .= ' AND project.id = ' . $projectid;
    }else if( $_SESSION['projectids'] != 0){
        $search_params .= ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }

    $projectkindid = filter_input(INPUT_POST, 'projectkindid');
    if ($projectkindid != '' && $projectkindid != -1) {
        $search_params .= ' AND project.projectkindid = ' . $projectkindid;
    }


    $bannerdesigned = filter_input(INPUT_POST, 'bannerdesigned');
    if ($bannerdesigned != '') {
        $search_params .= ' AND project.bannerdesigned = ' . $bannerdesigned;
    }

    $projectsuit = filter_input(INPUT_POST, 'projectsuit');
    if ($projectsuit != '') {
        $search_params .= ' AND project.projectsuit = ' . $projectsuit;
    }


    $projectstageid = filter_input(INPUT_POST, 'projectstageid');
    if ($projectstageid != '' && $projectstageid != -1) {
        $search_params .= ' AND projectstagechosse.projectstageid = ' . $projectstageid;
        $search_joins .= ' LEFT JOIN projectstagechosse ON projectstagechosse.projectid = project.id ';
        // $search_groups .= ' group by projectstagechosse.projectid ';
    }

    $business_type = filter_input(INPUT_POST, 'business_type');
    if ($business_type != '') {
        $search_params .= ' AND project.business_type = ' . $business_type;
    }

    $supervision_type = filter_input(INPUT_POST, 'supervision_type');
    if ($supervision_type != '') {
        $search_params .= ' AND project.supervision_type = ' . $supervision_type;
    }

   



    $alldata = $ProjectEx->queryAllData($search_params, $search_orders, $search_joins, $search_groups);
    foreach ($alldata as $value) {
        $value->projectstages = R::getAll('select * from projectstages LEFT JOIN projectstagechosse ON projectstagechosse.projectstageid = projectstages.id where projectstagechosse.projectid = ? ',[$value->id]);
    }
    $smarty->assign("alldata", $alldata);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->assign("projectValidation", 1);
    $smarty->display("projectview/show.html");
} 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");
    }
} elseif ($do == 'edit') {
    //here the permission check
    include_once("../public/authentication.php");

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

    $editelement = $ProjectDAO->load($id);
    $editelement->projectstageids = explode(',', $editelement->projectstageids);
    $smarty->assign("editelement", $editelement);

    $projectstages = R::findAll('projectstages','is_active = 1 ');
    $smarty->assign('projectstages', $projectstages);

    $projecttimetableitems = R::findAll('projecttimetableitems','del < 2 and projectid = ? ',[$id]);
    $smarty->assign('projecttimetableitems', $projecttimetableitems);


    $smarty->assign("projectValidation", 1);
    $smarty->assign("project", 1);
    $smarty->display("projectview/edit.html");
} elseif ($do == 'timetableitems') {
    //here the permission check
    include_once("../public/authentication.php");

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

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

    $projecttimetableitems = R::findAll('projecttimetableitems','del < 2 and projectid = ? ',[$id]);
    $smarty->assign('projecttimetableitems', $projecttimetableitems);


    $smarty->display("projectview/detailtimetableitems.html");    
} 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");
    }
} elseif ($do == 'delete') {
    include_once("../public/authentication.php");
#####var
    $id = filter_input(INPUT_GET, 'id', FILTER_DEFAULT);


    try {

        $deletevalid = deleteproject($id);
        if ($deletevalid == 1) {
            header("location:?do=sucess");
        } else {
            $url = "projectController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = " عفوا لايمكنك حذف المشروع لانه مرتبط بعمليات اخرى";

            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "finish") {

    include_once("../public/authentication.php");
#####var
    $id = filter_input(INPUT_GET, 'id', FILTER_DEFAULT);


    try {
        // here the function that do the action
        finishproject($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");
}


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

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

function add() {
    global $clientDAO;
    global $client;
    global $Costcenter;
    global $CostcenterDAO;
    global $clientExt;
    global $Project;
    global $ProjectDAO;
    global $ProjectEx;




    ///var
    $txtName = filter_input(INPUT_POST, 'txtName', FILTER_DEFAULT);
    $txtDebt = filter_input(INPUT_POST, 'txtDebt', FILTER_DEFAULT);
    $chwckaddclient = filter_input(INPUT_POST, 'chwckaddclient', FILTER_DEFAULT);
    $textDetails = filter_input(INPUT_POST, 'textDetails', FILTER_DEFAULT);
    $projectkindid = filter_input(INPUT_POST, 'projectkindid', FILTER_DEFAULT);
    $bannerdesigned = filter_input(INPUT_POST, 'bannerdesigned', FILTER_DEFAULT);
    $projectsuit = filter_input(INPUT_POST, 'projectsuit', FILTER_DEFAULT);
    $addeddate = filter_input(INPUT_POST, 'addeddate', FILTER_DEFAULT);
    $expirydate = filter_input(INPUT_POST, 'expirydate', FILTER_DEFAULT);

    $owner_name = filter_input(INPUT_POST, 'owner_name', FILTER_DEFAULT);
    $business_type = filter_input(INPUT_POST, 'business_type', FILTER_DEFAULT);
    $supervision_type = filter_input(INPUT_POST, 'supervision_type', FILTER_DEFAULT);
    $supervision_amount = filter_input(INPUT_POST, 'supervision_amount', FILTER_DEFAULT);
    $projectstageids = filter_input(INPUT_POST, 'projectstageids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $timetableitemsitr = filter_input(INPUT_POST, 'timetableitemsitr', FILTER_DEFAULT);
    $projectstagesdata = filter_input(INPUT_POST, 'projectstagesdata', FILTER_DEFAULT);
    $projecttimetableitems = filter_input(INPUT_POST, 'projecttimetableitems', FILTER_DEFAULT);
    $expenses = filter_input(INPUT_POST, 'expenses', FILTER_DEFAULT);
    $income = filter_input(INPUT_POST, 'income', FILTER_DEFAULT);

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

    $handle = new upload($_FILES['imagecontract']);
    $contractPhoto = uploadImageswhioutresize($handle, "../upload/project");

    $handle = new upload($_FILES['filepdf']);
    $filepdf = uploadImageswhioutresize($handle, "../upload/project");


    ######$Costcenter
    $Costcenter->name = $txtName;
    $Costcenter->condation = 0;
    $costcenterid = $CostcenterDAO->insert($Costcenter);

    ###client
    if ($chwckaddclient == 1 ) {
        $client->clientname = $txtName;
        $client->clientdebt = $txtDebt;
        $client->clientdetails = $textDetails;
        $client->treeId = addTreeElement($txtName, 58, 3, 0, 1, '', 0, 0);
        $clientid = $clientExt->insertclient($client);
    } else {
        $clientid = 0;
    }


    ###insert into treee ----- مدينون
    $treeid = addTreeElement($txtName, 23, 3, 0, 1);

    ###insert into tree ----- خصوم
    $treeproid = addTreeElement('بضاعة تحت التسوية (' . $txtName . ')', 39, 1, 0, 1);




    ###insertinto project
    $Project->projectstagesdata = $projectstagesdata;
    $Project->projecttimetableitems = $projecttimetableitems;
    $Project->expenses = $expenses;
    $Project->income = $income;
    $Project->name = $txtName;
    $Project->filepdf = $filepdf;
    $Project->showpdf = $showpdf;
    $Project->owner_name = $owner_name;
    $Project->business_type = $business_type;
    $Project->supervision_type = $supervision_type;
    $Project->supervision_amount = $supervision_amount;
    $Project->totalcontract = $txtDebt;
    $Project->detail = $textDetails;
    $Project->image = $contractPhoto;
    $Project->clientid = $clientid;
    $Project->costcenterid = $costcenterid;
    $Project->treeid = $treeid;
    $Project->treeproid = $treeproid;
    $Project->entryid = 0;
    $Project->sysdate = date('Y-m-d');
    $Project->del = 0;
    $Project->finish = 0;
    $Project->projectkindid = $projectkindid;
    $Project->bannerdesigned = $bannerdesigned;
    $Project->projectsuit = $projectsuit;
    $Project->addeddate = $addeddate;
    $Project->expirydate = $expirydate;
    $Project->userid = $_SESSION['userid'];
    if (in_array("0", $projectstages)) {
        $Project->projectstageids =  '0';
    }else{
        $Project->projectstageids =  '-1,'.implode(",", $projectstageids);
    }
    $projectid = $ProjectDAO->insert($Project);

    for ($i=0; $i <= count($projectstageids); $i++) { 
        if (!$projectstageids[$i]) {continue;}
        $webclientprojects = R::dispense('projectstagechosse');
        $webclientprojects->projectid = $projectid;
        $webclientprojects->projectstageid = $projectstageids[$i];          
        R::store($webclientprojects);
    }

    for ($i2=1; $i2 <= $timetableitemsitr; $i2++) { 
        $clause = filter_input(INPUT_POST, 'clause'.$i2, FILTER_DEFAULT);
        $amount = filter_input(INPUT_POST, 'amount'.$i2, FILTER_DEFAULT);
        $duration = filter_input(INPUT_POST, 'duration'.$i2, FILTER_DEFAULT);
        $startdate = filter_input(INPUT_POST, 'startdate'.$i2, FILTER_DEFAULT);
        $enddate = filter_input(INPUT_POST, 'enddate'.$i2, FILTER_DEFAULT);

        if (!$clause) {continue;}
        $projecttimetableitems = R::dispense('projecttimetableitems');
        $projecttimetableitems->projectid = $projectid;
        $projecttimetableitems->clause = $clause;   
        $projecttimetableitems->amount = $amount; 
        $projecttimetableitems->duration = $duration; 
        $projecttimetableitems->startdate = $startdate; 
        $projecttimetableitems->enddate = $enddate; 
        $projecttimetableitems->del = 0;        
        R::store($projecttimetableitems);
    }

}

function update() {
    global $clientDAO;
    global $client;
    global $Costcenter;
    global $CostcenterDAO;
    global $clientExt;
    global $Project;
    global $ProjectDAO;
    global $CostcenterEx;
    global $accountsTree;
    global $accountsTreeDAO;



    ///var
    $txtName = filter_input(INPUT_POST, 'txtName', FILTER_DEFAULT);
    $txtDebt = filter_input(INPUT_POST, 'txtDebt', FILTER_DEFAULT);
    $textDetails = filter_input(INPUT_POST, 'textDetails', FILTER_DEFAULT);
    $editid = filter_input(INPUT_POST, 'editid', FILTER_DEFAULT);
    $clientid = filter_input(INPUT_POST, 'clientid', FILTER_DEFAULT);
    $costcenterid = filter_input(INPUT_POST, 'costcenterid', FILTER_DEFAULT);
    $treeid = filter_input(INPUT_POST, 'treeid', FILTER_DEFAULT);
    $treeproid = filter_input(INPUT_POST, 'treeproid', FILTER_DEFAULT);
    $entryid = filter_input(INPUT_POST, 'entryid', FILTER_DEFAULT);
    $sysdate = filter_input(INPUT_POST, 'sysdate', FILTER_DEFAULT);
    $del = filter_input(INPUT_POST, 'del', FILTER_DEFAULT);
    $projectkindid = filter_input(INPUT_POST, 'projectkindid', FILTER_DEFAULT);
    $bannerdesigned = filter_input(INPUT_POST, 'bannerdesigned', FILTER_DEFAULT);
    $projectsuit = filter_input(INPUT_POST, 'projectsuit', FILTER_DEFAULT);
    $addeddate = filter_input(INPUT_POST, 'addeddate', FILTER_DEFAULT);
    $expirydate = filter_input(INPUT_POST, 'expirydate', FILTER_DEFAULT);

    $owner_name = filter_input(INPUT_POST, 'owner_name', FILTER_DEFAULT);
    $business_type = filter_input(INPUT_POST, 'business_type', FILTER_DEFAULT);
    $supervision_type = filter_input(INPUT_POST, 'supervision_type', FILTER_DEFAULT);
    $supervision_amount = filter_input(INPUT_POST, 'supervision_amount', FILTER_DEFAULT);
    $projectstageids = filter_input(INPUT_POST, 'projectstageids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $timetableitemsitr = filter_input(INPUT_POST, 'timetableitemsitr', FILTER_DEFAULT);

     $projectstagesdata = filter_input(INPUT_POST, 'projectstagesdata', FILTER_DEFAULT);
    $projecttimetableitems = filter_input(INPUT_POST, 'projecttimetableitems', FILTER_DEFAULT);
    $expenses = filter_input(INPUT_POST, 'expenses', FILTER_DEFAULT);
    $income = filter_input(INPUT_POST, 'income', FILTER_DEFAULT);
        $showpdf = filter_input(INPUT_POST, 'showpdf', FILTER_DEFAULT);

    $handle = new upload($_FILES['filepdf']);
    $filepdf = updateImagesWithoutresiz($handle, 'hiddenfile', "../upload/project");


    $handle = new upload($_FILES['imagecontract']);
    $contractPhoto = updateImagesWithoutresiz($handle, 'hiddenfile', "../upload/project");
    ######update Costcenter
    $Costcenter->id = $costcenterid;
    $Costcenter->name = $txtName;
    $CostcenterEx->updateExt($Costcenter);

    ###client
    $client->clientid = $clientid;
    $client->clientname = $txtName;
    $client->clientdebt = $txtDebt;
    $client->clientdetails = $textDetails;
    $clientExt->updateClientname($client);



    ######UPDATE treee ----- مدينون
    editInTree($txtName, $txtDebt, $treeid);
    ###insert into tree ----- خصوم
    editInTree($txtName, $txtDebt, $treeproid);



###update project
    $Project->id = $editid;
    $Project->name = $txtName;
     $Project->filepdf = $filepdf;
    $Project->showpdf = $showpdf;
    $Project->owner_name = $owner_name;
    $Project->business_type = $business_type;
    $Project->supervision_type = $supervision_type;
    $Project->supervision_amount = $supervision_amount;
    $Project->totalcontract = $txtDebt;
    $Project->detail = $textDetails;
    $Project->image = $contractPhoto;
    $Project->clientid = $clientid;
    $Project->costcenterid = $costcenterid;
    $Project->treeid = $treeid;
    $Project->treeproid = $treeproid;
    $Project->entryid = $NEWentryid;
    $Project->sysdate = $sysdate;
    $Project->del = $del;
    $Project->finish = 0;
    $Project->projectkindid = $projectkindid;
    $Project->bannerdesigned = $bannerdesigned;
    $Project->projectsuit = $projectsuit;
    $Project->addeddate = $addeddate;
    $Project->expirydate = $expirydate;

     $Project->projectstagesdata = $projectstagesdata;
    $Project->projecttimetableitems = $projecttimetableitems;
    $Project->expenses = $expenses;
    $Project->income = $income;
    $Project->userid = $_SESSION['userid'];
    if (in_array("0", $projectstageids)) {
        $Project->projectstageids =  '0';
    }else{
        $Project->projectstageids =  '-1,'.implode(",", $projectstageids);
    }
    $ProjectDAO->update($Project);
    for ($i=0; $i <= count($projectstageids); $i++) { 
        if (!$projectstageids[$i]) {continue;}
         
        $projectstagechosseold = R::findAll('projectstagechosse', 'projectid = ? ',[$editid]);
        foreach ($projectstagechosseold as $value) {
            if (!in_array($value->projectstageid, $projectstageids)) {
               R::trash($value);
            }
        }
        $count = R::count('projectstagechosse', 'projectid = ? and projectstageid = ?', [$editid, $projectstageids[$i]]);
        if ($count == 0) {
            $webclientprojects = R::dispense('projectstagechosse');
            $webclientprojects->projectid = $editid;
            $webclientprojects->projectstageid = $projectstageids[$i];          
            R::store($webclientprojects);
        }
     }


     for ($i2=1; $i2 <= $timetableitemsitr; $i2++) { 
        $projecttimetableitemid = filter_input(INPUT_POST, 'projecttimetableitemid'.$i2, FILTER_DEFAULT);
        $clause = filter_input(INPUT_POST, 'clause'.$i2, FILTER_DEFAULT);
        $amount = filter_input(INPUT_POST, 'amount'.$i2, FILTER_DEFAULT);
        $duration = filter_input(INPUT_POST, 'duration'.$i2, FILTER_DEFAULT);
        $startdate = filter_input(INPUT_POST, 'startdate'.$i2, FILTER_DEFAULT);
        $enddate = filter_input(INPUT_POST, 'enddate'.$i2, FILTER_DEFAULT);

        if (!$clause) {continue;}
        if ($projecttimetableitemid) {
            $projecttimetableitems = R::load('projecttimetableitems',$projecttimetableitemid);
        }else{
             $projecttimetableitems = R::dispense('projecttimetableitems');
        }
       
        $projecttimetableitems->projectid = $editid;
        $projecttimetableitems->clause = $clause;   
        $projecttimetableitems->amount = $amount; 
        $projecttimetableitems->duration = $duration; 
        $projecttimetableitems->startdate = $startdate; 
        $projecttimetableitems->enddate = $enddate; 
        $projecttimetableitems->del = 0;        
        R::store($projecttimetableitems);
    }
}

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

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

    ########## nsert into entry
    $dailyEntry->entryComment = 'تم اضافة مشروع اسمه' . $projectname;

    $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 = $getRow->theValue;
    $accountsTree->userid = $getRow->userid;

    editTreeElement($accountsTree);
}

function finishproject($projectid) {

    global $dailyEntry;
    global $dailyEntryCreditor;
    global $dailyEntryDebtor2;
    global $dailyEntryDebtor;
    global $clientDAO;
    global $ProjectDAO;
    global $accountsTreeDAO;
    global $ProjectEx;
    global $clientExt;
    global $CostcenterEx;
    global $Costcenter;

    ##projectData
    $projectData = $ProjectDAO->load($projectid);
    $projectname = $projectData->name;
    $clientid = $projectData->clientid;
    $costcenterid = $projectData->costcenterid;
    $treeid = $projectData->treeid;
    $goodsid = $projectData->treeproid;

    $ProjectEx->updatefinished(1, $projectid);
    $clientExt->deletetemp($clientid);

    $Costcenter->condation = 1;
    $Costcenter->id = $costcenterid;
    $CostcenterEx->updatedel($Costcenter);
    /* -----==================================================== */
    //   1- من حساب عميل (المدفوع - اجمالى البضاعة)
    //  2 - حساب بضاعة تحت التسوية )(اجمالى البضاعة)
    // 3 - الى حساب المبيعات )(حساب عميل - حساب بضاعة تحت التسوية )
    /* =========================================================== */

    ###clientdebt
    $clientData = $clientDAO->load($clientid);
    $clientPaid = $clientData->clientdebt;
    if ($clientPaid < 0) {

        $clientPaid = abs($clientPaid);
    } else {
        $clientPaid = $clientPaid;
    }



    $suppliesTree = $accountsTreeDAO->queryByName('بضاعة تحت التسوية (' . $projectData->name . ')');
    $supplies = $suppliesTree[0]->theValue;

    #####clientaccountvalue
    $clientvalue = $clientPaid - $supplies;
    ########## nsert into entry
    $dailyEntry->entryComment = 'تم انهاء مشروع اسمه' . $projectname;
    $dailyEntryDebtorArray = array();
    $dailyEntryCreditorArray = array();
    ####من حساب العميل
    $dailyEntryDebtor->value = $clientvalue;
    $dailyEntryDebtor->accountstreeid = $treeid;

    #### بضاعة تحت التسوية
    $dailyEntryDebtor2->value = $supplies;
    $dailyEntryDebtor2->accountstreeid = $goodsid;
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor2);


    // $sellsvalue = $clientvalue - $supplies;
    ###المبيعات
    $dailyEntryCreditor->value = $clientPaid;
    $dailyEntryCreditor->accountstreeid = 16;

    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

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

function deleteproject($projectid) {
    global $ProjectDAO;
    global $ProjectexchmaterialDAO;
    global $ProjectEx;
    global $clientDAO;
    global $CostcenterDAO;

    $flag = 0;
    $projectmaterial = $ProjectexchmaterialDAO->queryByProjectid($projectid);
    if (count($projectmaterial) == 0) {
        $projData = $ProjectDAO->load($projectid);
        $projName = $projData->name;
        $dailyentryid = $projData->entryid;
        $clientid = $projData->clientid;
        $costcenterid = $projData->costcenterid;

        reverseEntryWithItsID($dailyentryid);
        delTreeElement($projName);
        delTreeElement('بضاعة تحت التسوية (' . $projName . ')');

        $ProjectEx->updatedel(1, $projectid);
        $clientDAO->delete($clientid);
        $CostcenterDAO->delete($costcenterid);
        $flag = 1;
    }

    return $flag;
}

?>