<?php

// كنترول المرتبات
//
//the global file operation
include("../public/impOpreation.php");
include_once("dailyentryfun.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");
require_once('../models/sql/Connection.class.php');
require_once('../models/sql/ConnectionFactory.class.php');
require_once('../models/sql/ConnectionProperty.class.php');
require_once('../models/sql/QueryExecutor.class.php');
require_once('../models/sql/Transaction.class.php');
require_once('../models/sql/SqlQuery.class.php');
require_once('../models/core/ArrayList.class.php');
require_once('../models/dao/DAOFactory.class.php');

require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.class.php');

require_once('../models/dao/SalaryreportDAO.class.php');
require_once('../models/dto/Salaryreport.class.php');
require_once('../models/mysql/SalaryreportMySqlDAO.class.php');
require_once('../models/mysql/ext/SalaryreportMySqlExtDAO.class.php');

require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');

require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');

require_once('../models/dao/EmployeeDAO.class.php');
require_once('../models/dto/Employee.class.php');
require_once('../models/mysql/EmployeeMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeMySqlExtDAO.class.php');

require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.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/CostcenterdetailDAO.class.php');
require_once('../models/dto/Costcenterdetail.class.php');
require_once('../models/mysql/CostcenterdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterdetailMySqlExtDAO.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');







$do = $_GET['do'];
if (isset($_POST["fromCtrl"]) && isset($_POST["fromCtrl"]) == "employeePersonal") {
    //no header its curl request
} else {
    $smarty->display("header.html");
}


$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");



//creat object from employeePersonal
$EmployeepersonnelDAO = new EmployeepersonnelMySqlDAO();
$Employeepersonnel = new Employeepersonnel();
$EmployeepersonnelEX = new EmployeepersonnelMySqlExtDAO();

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

//creat object from save
$saveDAo = new SaveMySqlDAO();
$save = new Save();
$saveEX = new SaveMySqlExtDAO();

//creat object from Savedaily
$SavedailyDAO = new SavedailyMySqlDAO();
$Savedaily = new Savedaily();
$SavedailyEX = new SavedailyMySqlExtDAO();

// create object from employee
$myEmpDAO = new EmployeeMySqlDAO();
$myEmp = new Employee();
$myEmpEX = new EmployeeMySqlExtDAO();
//create object from salary report
$SalaryreportDAO = new SalaryreportMySqlDAO();
$Salaryreport = new Salaryreport();
$SalaryreportEX = new SalaryreportMySqlExtDAO();

//create object from savedailay
$SavedailyDAO = new SavedailyMySqlDAO();
$Savedaily = new Savedaily();
$SavedailyEX = new SavedailyMySqlExtDAO();

$Costcenterdetail = new Costcenterdetail();
$CostcenterdetailDAO = new CostcenterdetailMySqlDAO();
$CostcenterdetailEX = new CostcenterdetailMySqlExtDAO();

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

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



//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();

//user
$userDAO = new UserMySqlDAO();

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
//dispaly  add form
if (!isset($_GET['do'])) {

    $userData = $userDAO->load($_SESSION['userid']);
    if ($userData->searchinonesave == 1) {
        $userSave = $mySaveEx->loadEx($_SESSION['saveid']);
        $smarty->assign('userSave', $userSave);
    } else {
        if (!isset($userData->saveids) || $userData->saveids == 0)
            $queryString = '';
        else
            $queryString = ' and saveid in (' . $userData->saveids . ')';

        $userSaves = $mySaveEx->queryWithConditionWithQueryString($queryString);
        $smarty->assign('userSaves', $userSaves);
    }

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);


    $today = date("Y-m-d");
    $from = $_POST['from'];
    if ($from != "") {
        $start = $from . '-01';
        $end = $from . '-31';

        if ($_SESSION['branchId'] > 0)
            $queryString = ' AND branchid = ' . $_SESSION['branchId'];


        // $allEmp = $myEmpEX->queryAllemployeeSalary($from, $end);
        $allEmp = $myEmpEX->queryAllemployeeSalaryWithQueryString($from, $end, $queryString);
        $i = 0;
        $allEmpsalary = array();
        $z = array();
        $x[] = array();
        foreach ($allEmp as $emp) {
            $id = ($emp->employeeId);
            $qs = ' AND employeepersonneldate <= "'.$end.' 23:59:59"';
            $allsalarys = $myEmpEX->getall($id,$qs);

            $x[0] = $allsalarys->employeeId;
            $x[1] = $allsalarys->employeeName;
            $x[2] = (float) $allsalarys->employeeSalary;

            $x[3] = (float) $allsalarys->employeeBouns;
            $x[4] = (float) $allsalarys->Reward + (float) $allsalarys->employeeBouns;
            $x[5] = (float) $allsalarys->Discount;

            $x[6] = (float) $allsalarys->Withdraw;
            $x[7] = (float) $allsalarys->Absence;
            $x[9] = (float) $allsalarys->Repayment;
            $x[10] = ((float) $allsalarys->empdept) - ((float) $allsalarys->Repayment);
            $x[12] = (float) $allsalarys->permission;
            $x[13] = (float) $allsalarys->allLeave;

            
            $lastSalary = $SalaryreportEX->getEmpLastRow($id);
            $prevDebt = 0;
            if ($lastSalary->salaryreportnet < 0)
            $prevDebt += (float) $lastSalary->salaryreportnet;
        $x[11] = $prevDebt;
        
        $total = ((float) $allsalarys->employeeBouns + (float) $allsalarys->Reward + (float) $allsalarys->employeeSalary) -
        ((float) $allsalarys->Discount + (float) $allsalarys->Withdraw + (float) $allsalarys->Absence + (float) $allsalarys->Repayment + (float) $allsalarys->permission + (float) $allsalarys->allLeave) + $prevDebt;
        
        $x[8] = $total;
        
        //thismonthNet
        $x[14] = ((float) $allsalarys->employeeBouns + (float) $allsalarys->Reward + (float) $allsalarys->employeeSalary) -
        ((float) $allsalarys->Discount + (float) $allsalarys->Withdraw + (float) $allsalarys->Absence + (float) $allsalarys->Repayment + (float) $allsalarys->permission + (float) $allsalarys->allLeave);
        
        $allEmpsalary[$i] = $x;
        
            //$z[$i]= $allsalarys->employeeId;
            $i++;

            //print_r($x);
        } //end of foreach
        //  print_r($y);
        $smarty->assign('allEmpsalary', $allEmpsalary);
        //$smarty->assign('z', $z);
        $smarty->assign('salarymonthdate', $from);
    }

    $today = date("Y-m");
    $smarty->assign('today', $today);
    $smarty->display('salaryReportview/show.html');
}


//show all كل اللى قبض
elseif ($do == "show") {

    include_once("../public/authentication.php");

    show();

    $smarty->display('salaryReportview/showfinsh.html');
} elseif ($do == "editprint") {

    include_once("../public/authentication.php");

    editprint();

    $smarty->display('salaryReportview/editprint.html');
} elseif ($do == "Receipt") {
    //include_once("../public/authentication.php");
    if (isset($_POST["fromCtrl"]) && $_POST["fromCtrl"] == "employeePersonal") {
        try {
            Receipt();
            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    } else {
        try {
            Receipt();
            header("location:?do=sucess");
        } catch (Exception $e) {
            //echo $e;
            header("location:?do=error");
        }
    }
} elseif ($do == "delete") {

    include_once("../public/authentication.php");

    try {
        delete();

        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
}
##
else if ($do == "salaryEntitlementEntry-notFinised") {

    $userData = $userDAO->load($_SESSION['userid']);
    if ($userData->searchinonesave == 1) {
        $userSave = $mySaveEx->loadEx($_SESSION['saveid']);
        $smarty->assign('userSave', $userSave);
    } else {
        if (!isset($userData->saveids) || $userData->saveids == 0)
            $queryString = '';
        else
            $queryString = ' and saveid in (' . $userData->saveids . ')';

        $userSaves = $mySaveEx->queryWithConditionWithQueryString($queryString);
        $smarty->assign('userSaves', $userSaves);
    }

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $from = $_REQUEST["from"];
    if (!empty($from)) {
        $start = $from . '-01';
        $end = $from . '-31';

        if ($_SESSION['branchId'] > 0)
            $queryString = ' AND branchid = ' . $_SESSION['branchId'];

        //$allmydata = show();##this gets old salry "mean that employee recieve it"
        // $allEmp = $myEmpEX->queryAllemployeeSalary($from, $end);
        $allEmp = $myEmpEX->queryAllemployeeSalaryWithQueryString($from, $end, $queryString); ##this gets new salay "mean unrecieved salaries"
        $i = 0;
        $allEmpsalary = array();
        $z = array();
        $x[] = array();
        #################################################################
        ##last day of choosen month
        list($year, $month) = explode('-', $from);
        $lastDay = date("t", strtotime("$year-$month-01"));
        ##
        $dailyEntry->entryComment = "استحقاق مرتبات شهر " . $from;
        $dailyEntry->fromFlag = 1;
        $dailyEntry->thedate = "$year-$month-$lastDay 23:59:59"; //last day , last second of choosen month
        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();

        list($sumBounus, $sumReward, $sumPlenty, $sumSocialInsurance, $sumWorkTax, $sumMainSalary) = [0, 0, 0, 0, 0, 0];
        foreach ($allEmp as $value) {
            $id = ($value->employeeId);
            $qs = ' AND employeepersonneldate <= "'.$end.' 23:59:59"';
            $allsalarys = $myEmpEX->getall($id,$qs);

            //            var_dump($value);
            // من المرتب الاساسى
            $dailyEntryDebtor = new stdClass();
            $dailyEntryDebtor->value = $value->employeeSalary;
            $dailyEntryDebtor->accountstreeid = $value->treeId2;
            $dailyEntryDebtor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryDebtor->accountstreeid);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            ##
            $sumBounus += (float) $allsalarys->employeeBouns;
            $sumReward += (float) $allsalarys->Reward;
            $sumPlenty += (float) $allsalarys->Discount + (float) $allsalarys->Absence + (float) $allsalarys->permission + (float) $allsalarys->allLeave;
            $sumSocialInsurance += $value->socialInsurance;
            $sumWorkTax += $value->workTax;
            $sumMainSalary += (float) $allsalarys->employeeSalary;

            $x[0] = $allsalarys->employeeId;
            $x[1] = $allsalarys->employeeName;
            $x[2] = (float) $allsalarys->employeeSalary;
            $x[3] = (float) $allsalarys->employeeBouns;
            $x[4] = (float) $allsalarys->Reward + (float) $allsalarys->employeeBouns;
            $x[5] = (float) $allsalarys->Discount;
            $x[6] = (float) $allsalarys->Withdraw;
            $x[7] = (float) $allsalarys->Absence;
            $x[9] = (float) $allsalarys->Repayment;
            $x[10] = ((float) $allsalarys->empdept) - ((float) $allsalarys->Repayment);
            $x[12] = (float) $allsalarys->permission;
            $x[13] = (float) $allsalarys->allLeave;
            $lastSalary = $SalaryreportEX->getEmpLastRow($id);
            $prevDebt = 0;
            if ($lastSalary->salaryreportnet < 0)
                $prevDebt += (float) $lastSalary->salaryreportnet;
            $x[11] = $prevDebt;
            $total = ((float) $allsalarys->employeeBouns + (float) $allsalarys->Reward + (float) $allsalarys->employeeSalary) -
                ((float) $allsalarys->Discount + (float) $allsalarys->Withdraw + (float) $allsalarys->Absence + (float) $allsalarys->Repayment + (float) $allsalarys->permission + (float) $allsalarys->allLeave) + $prevDebt;
            $x[8] = $total;
            $allEmpsalary[$i] = $x;
            //$z[$i]= $allsalarys->employeeId;
            $i++;
        }
        $smarty->assign('allEmpsalary', $allEmpsalary);
        //$smarty->assign('z', $z);
        $smarty->assign('salarymonthdate', $from);

        //عمولات موظفين و رواتب اضافيه --- 161 //دى وقت اضافى
        if ($sumBounus > 0) {
            $dailyEntryDebtor = new stdClass();
            $dailyEntryDebtor->value = $sumBounus;
            $dailyEntryDebtor->accountstreeid = 161;
            $dailyEntryDebtor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryDebtor->accountstreeid);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        }
        //مكافات --- 167
        if ($sumReward > 0) {
            $dailyEntryDebtor = new stdClass();
            $dailyEntryDebtor->value = $sumReward;
            $dailyEntryDebtor->accountstreeid = 167;
            $dailyEntryDebtor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryDebtor->accountstreeid);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        }


        //صندوق الجزاءات  تحت التزامات متداولة --- 52
        if ($sumPlenty > 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = $sumPlenty;
            $dailyEntryCreditor->accountstreeid = 52;
            $dailyEntryCreditor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryCreditor->accountstreeid);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        }
        //تحت مصروفات عموميه  تامينات اجتماعيه  --- 162
        if ($sumSocialInsurance > 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = $sumSocialInsurance;
            $dailyEntryCreditor->accountstreeid = 162;
            $dailyEntryCreditor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryCreditor->accountstreeid);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        }

        // ضريبه كسب العمل --- 176
        if ($sumWorkTax > 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = $sumWorkTax;
            $dailyEntryCreditor->accountstreeid = 176;
            $dailyEntryCreditor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryCreditor->accountstreeid);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        }

        // مصروفات مستحقة – أجور و مرتبات --- 97
        $sumNetSalary = $sumMainSalary + $sumBounus + $sumReward - $sumPlenty - $sumSocialInsurance - $sumWorkTax;
        if ($sumNetSalary > 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = $sumNetSalary;
            $dailyEntryCreditor->accountstreeid = 97;
            $dailyEntryCreditor->accountstreeName = R::getCell('select customName from accountstree where id=' . $dailyEntryCreditor->accountstreeid);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        }

        //السلف بتدخل مع فيد الاستحقاق ولاالفرق بين اللى  اتسحب و اللى اتسدد  و المسحوبات كمان لان لها قيد  منفصل
        ##getTotal
        $dailyEntry->totaldebtor = 0;
        foreach ($dailyEntryDebtorArray as $value) {
            $dailyEntry->totaldebtor += $value->value;
        }
        $dailyEntry->totalcreditor = 0;
        foreach ($dailyEntryCreditorArray as $value) {
            $dailyEntry->totalcreditor += $value->value;
        }

        $smarty->assign('dailyEntryDebtorArray', $dailyEntryDebtorArray);
        $smarty->assign('dailyEntryCreditorArray', $dailyEntryCreditorArray);
        $smarty->assign('dailyEntry', $dailyEntry);
        $smarty->assign('rowSpan', (count($dailyEntryDebtorArray) + count($dailyEntryCreditorArray)));
        $smarty->assign('sumNetSalary', $sumNetSalary);




        $salaryEntitlementEntryArr = array($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
        setcookie('salaryEntitlementEntryArr', serialize($salaryEntitlementEntryArr), time() + (86400 * 1), "/"); // 1 days expiration
    }
    $today = date("Y-m");
    $smarty->assign('today', $today);
    $smarty->display('salaryReportview/salaryEntitlementEntry.html');
} elseif ($do == "dosalaryEntitlementEntry-notFinised") {
    $salaryEntitlementEntry = unserialize($_COOKIE['salaryEntitlementEntryArr']);
    $dailyEntry = $salaryEntitlementEntry[0];
    $dailyEntryDebtorArray = $salaryEntitlementEntry[1];
    $dailyEntryCreditorArray = $salaryEntitlementEntry[2];

    $operationId = 1;
    $operationDetailLink = 'salaryReportController.php?do=dosalaryEntitlementEntry';
    //insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $operationId, $operationDetailLink);
    ##remove cookiee // Set the cookie with an expiration time in the past
    //setcookie('salaryEntitlementEntryArr', '', time() - 3600, '/');
} elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}

$smarty->assign("customValidation", 1);
if (isset($_POST["fromCtrl"]) && isset($_POST["fromCtrl"]) == "employeePersonal") {
    //no header its curl request
} else {
    $smarty->display("footer.html");
}

////////////////////////////save///////////////////////////
function show()
{

    global $smarty;
    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;
    global $Salaryreport;
    global $SalaryreportDAO;
    global $SalaryreportEX;
    global $myEmpEX;
    global $saveEX;

    $allemployeedata = allemployee();
    $smarty->assign('allemployeedata', $allemployeedata);

    $queryString = '';

    $empName = $_REQUEST["empName"];
    $from = $_REQUEST["from"];
    $smarty->assign('salarymonthdate', $from);

    if (isset($empName) && $empName != '-1') {
        $queryString .= ' and salaryreport.employeeid = ' . $empName . ' ';
    }

    if (isset($from) && $from != '') {
        $queryString .= ' and salaryreport.salarymonthdate = "' . $from . '" ';
    }

    if ($_SESSION['branchId'] > 0)
        $queryString .= ' and branchid = ' . $_SESSION['branchId'];


    if (!empty($queryString)) {
        $queryString .= 'and  employee.conditions = 0 ';
        $allmydata = $SalaryreportEX->queryAllEX($queryString);
        foreach ($allmydata as $data) {
            $lastSalary = $SalaryreportEX->getEmpLastRowPrev($data->employeeid, $data->salaryreportid);
            $prevDebt = 0;
            if ($lastSalary->salaryreportnet < 0)
                $prevDebt += $lastSalary->salaryreportnet;
            $data->prevDebt = $prevDebt;
            $saveid = $data->saveid ?: $_SESSION['saveid'];
            $data->saveid = $saveEX->loadEx($saveid)->savename;
        }
    }
    //print_r($allmydata);

    $smarty->assign('allmydata', $allmydata);
    return $allmydata;
}

function editprint()
{

    global $smarty;
    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;
    global $Salaryreport;
    global $SalaryreportDAO;
    global $SalaryreportEX;
    global $myEmpEX;


    $id = $_GET["id"];
    $queryString = '';
    $empName = $_REQUEST["empName"];
    $from = $_REQUEST["from"];

    if (isset($id) && $id != '') {
        $queryString .= ' and salaryreport.salarymonth ="' . $id . '" ';
    }
    $allmydata = $SalaryreportEX->queryAllEX($queryString);
    $smarty->assign('allmydata', $allmydata);
}

function Receipt()
{

    global $smarty;
    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;
    global $Salaryreport;
    global $SalaryreportDAO;
    global $SalaryreportEX;
    global $mySaveRecord;

    global $myEmpDAO;
    global $myEmp;
    global $myEmpEX;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;


    if (isset($_POST["fromCtrl"]) && $_POST["fromCtrl"] == "employeePersonal") {
        $_POST['empid'] = array($_POST["empid"]);
        $_SESSION['userid'] = $_POST["userid"];
        $_SESSION['saveid'] = $_POST["saveid"];
        $_SESSION['dbname'] = $_POST["dbname"];
    }
    $salarymonthdate = $_POST['salarymonthdate'];
    $Costcenterid = $_POST["Costcenterid"];
    $todayx = date("Ymd");

    if ($_POST['saveid'])
        $saveid = $_POST['saveid'];
    else
        $saveid = $_SESSION['saveid'];

    $Monthsalarydata = $SalaryreportEX->loadcase($todayx);
    $salarymonth = $Monthsalarydata->salarymonth;
    if ($salarymonth != "") {

        $year = substr($salarymonth, 8, 2);
        $year++;
        $todayx = $todayx . $year;
    } else {

        $todayx = $todayx . '1';
    }


    $today = date("Y-m-d H:i:s");

    //
    $start = $salarymonthdate . '-01';
    $end = $salarymonthdate . '-31';


    $saveData = $mySaveRecord->load($saveid);
    $allsalarysfinal = 0;
    if (isset($_POST['empid'])) {
        foreach ($_POST['empid'] as $value) {
            $lastSalary = $SalaryreportEX->getEmpLastRow($value);
            $prevDebt = 0;
            if ($lastSalary->salaryreportnet < 0)
                $prevDebt += $lastSalary->salaryreportnet;


            $qs = ' AND employeepersonneldate <= "'.$end.' 23:59:59"';
            $allsalarys = $myEmpEX->getall($value,$qs);
            // $allsalarys = $myEmpEX->getall($value);

            if ($allsalarys->employeeBouns == null || $allsalarys->employeeBouns == "") {
                $allsalarys->employeeBouns = 0;
            }

            if ($allsalarys->Reward == null || $allsalarys->Reward == "") {
                $allsalarys->Reward = 0;
            }
            if ($allsalarys->Discount == null || $allsalarys->Discount == "") {
                $allsalarys->Discount = 0;
            }

            if ($allsalarys->Withdraw == null || $allsalarys->Withdraw == "") {
                $allsalarys->Withdraw = 0;
            }

            if ($allsalarys->Absence == null || $allsalarys->Absence == "") {
                $allsalarys->Absence = 0;
            }

            if ($allsalarys->Repayment == null || $allsalarys->Repayment == "") {
                $allsalarys->Repayment = 0;
            }

            if ($allsalarys->permission == null || $allsalarys->permission == "") {
                $allsalarys->permission = 0;
            }

            if ($allsalarys->allLeave == null || $allsalarys->allLeave == "") {
                $allsalarys->allLeave = 0;
            }



            $x[0] = $allsalarys->employeeId;
            $x[1] = $allsalarys->employeeName;
            $x[2] = $allsalarys->employeeSalary;

            $x[3] = $allsalarys->employeeBouns;
            $x[4] = $allsalarys->Reward;
            $x[5] = $allsalarys->Discount;

            $x[6] = $allsalarys->Withdraw;
            $x[7] = $allsalarys->Absence;
            $x[9] = $allsalarys->Repayment;
            $x[12] = $allsalarys->permission;
            $x[13] = $allsalarys->allLeave;


            $total = (($allsalarys->employeeBouns) + ($allsalarys->Reward) + ($allsalarys->employeeSalary)) -
                (($allsalarys->Discount) + ($allsalarys->Withdraw) + ($allsalarys->Absence) + ($allsalarys->Repayment) + ($allsalarys->permission) + ($allsalarys->allLeave)) + $prevDebt;
            //eman
            $netsalary = $total;
            //eman
            //fatma
            if ($total < 0) {
                $total = 0; //if net salary <0 so he will recieve 0 money
            }

            $Salaryreport->employeeid = $value;
            $Salaryreport->salarymonthdate = $salarymonthdate;
            $Salaryreport->salarymonth = $todayx;
            $Salaryreport->salaryreportbouns = $allsalarys->employeeBouns + 0;
            $Salaryreport->Reward = $allsalarys->Reward + 0;
            $Salaryreport->salaryreportdate = $today;
            $Salaryreport->salaryreportdiscount = $allsalarys->Discount + 0;
            $Salaryreport->salaryreportnet = $netsalary;
            $Salaryreport->salaryreportsalary = $allsalarys->employeeSalary;
            $Salaryreport->salaryreportwithdrawal = $allsalarys->Withdraw + 0;
            $Salaryreport->Absence = $allsalarys->Absence + 0;
            $Salaryreport->permission = $allsalarys->permission + 0;
            $Salaryreport->allLeave = $allsalarys->allLeave + 0;

            $Salaryreport->Repayment = $allsalarys->Repayment + 0;
            $Salaryreport->userid = $_SESSION['userid'];
            $Salaryreport->costcenterid = $Costcenterid;
            $Salaryreport->saveid = $saveid;



            $salaryreportid = $SalaryreportDAO->insert($Salaryreport);



            $Costcenterdetail->costamount = $total;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $salaryreportid;
            $Costcenterdetail->processname = 'قبض موظف';
            $Costcenterdetail->tablename = 'salaryReportController.php';
            $Costcenterdetail->type = 8;
            $Costcenterdetail->uesrid = $_SESSION['userid'];

            if (!empty($Costcenterid) && $Costcenterid != '-1') {
                $CostcenterdetailDAO->insert($Costcenterdetail);
            }
            //eman
            $EmployeepersonnelEX->updatedon($start, $end. ' 23:59:59', 1, $value, $_SESSION['userid'], $salarymonthdate);

            //            $EmployeepersonnelEX->updatedonDateFromTo($start, $end, 1, $value, $_SESSION['userid'], $salarymonthdate);


            $myempdata = $myEmpDAO->load($value);
            $myEmp->empdept = ($myempdata->empdept) - ($allsalarys->Repayment + 0);
            $myEmp->employeeId = $value;
            $myEmpEX->updatedept($myEmp);


            //daily Entry
            $dailyEntry->entryComment = 'مرتب موظف ' . $myempdata->employeeName;

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $total;
            $dailyEntryDebtor->accountstreeid = $myempdata->treeId2;


            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $total;
            $dailyEntryCreditor->accountstreeid = $saveData->treeId;

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $did = $returnedData[1];
            $Salaryreport->dailyentryid = $did;
            $Salaryreport->salaryreportid = $salaryreportid;
            $SalaryreportDAO->update($Salaryreport);





            $allsalarysfinal = $allsalarysfinal + $total;
        }




        $saveValueBefore = getSaveValueBefore($saveid);

        $saveValueafterValid = $saveValueBefore - $allsalarysfinal;





        updateSave($saveid, $saveValueafterValid);

        insertSavedaily($saveValueBefore, $allsalarysfinal, 1, $saveid, 'تقبيض مرتبات', $todayx, $saveValueafterValid, 'salaryReportController.php');

        //print_r('allsalarysfinal'.$allsalarysfinal.'<br>');
    }
}

function delete()
{
    global $smarty;
    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;
    global $Salaryreport;
    global $SalaryreportDAO;
    global $SalaryreportEX;
    global $myEmpEX;

    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;






    $id = $_GET["id"];

    $mydata = $SalaryreportDAO->load($id);

    $CostcenterdetailEX->updatedellbytypeandmodelid(8, $id, 1);


    $fromx = $mydata->salarymonthdate;
    //print_r($mydata);
    $start = $fromx . '-01';
    $end = $fromx . '-31';


    $saveid = $mydata->saveid ?: $_SESSION['saveid'];
    $saveValueBefore = getSaveValueBefore($saveid);

    $saveValueafterValid = $saveValueBefore + $mydata->salaryreportnet;

    $EmployeepersonnelEX->updatedonDel($start, $end, 0, $mydata->employeeid, $_SESSION['userid'], $fromx);

    $Salaryreport->conditions = 1;
    $Salaryreport->salaryreportid = $id;
    $SalaryreportEX->updatedel($Salaryreport);

    updateSave($saveid, $saveValueafterValid);

    insertSavedaily($saveValueBefore, $mydata->salaryreportnet, 0, $saveid, 'حذف مرتب  موظف', $mydata->salarymonth, $saveValueafterValid, 'salaryReportController.php');
    reverseEntryWithItsID($mydata->dailyentryid);
}

// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update in Save tbl
function updateSave($saveid, $savevalueafter)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    //update initialvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;

    $mySaveEx->updateSaveValue($mySave);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename)
{

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = date("Y-m-d H:i:s");
    $mySavedaily->userid = $_SESSION['userid'];
    $mySavedaily->savedailysavebefore = $savedailysavebefore;
    $mySavedaily->savedailychangeamount = $savedailychangeamount;
    $mySavedaily->savedailychangetype = $savedailychangetype;
    $mySavedaily->saveid = $saveid;
    $mySavedaily->processname = $processname;
    $mySavedaily->savedailymodelid = $savedailymodelid;
    $mySavedaily->savedailysaveafter = $savedailysaveafter;
    $mySavedaily->tablename = $tablename;
    $mySavedaily->clientid = 0;

    $mySavedailyRecord->insert($mySavedaily);
}

function allemployee()
{

    global $myEmpDAO;
    global $myEmpEX;

    if ($_SESSION['branchId'] > 0)
        $queryString = ' AND branchid = ' . $_SESSION['branchId'];

    $allemp = $myEmpEX->queryAllemployeebycondation(0, $queryString);
    return $allemp;
}
