<?php

// كنترول الموظفين
//
//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include_once("initiateStaticSessionCommingWithCurl.php");
include_once("dailyentryfun.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/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/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/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');

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

//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.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');





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




//$saveId=$BranchDAO->querysaveid($_SESSION['branchid']);
//creat object from employeePersonal
$EmployeepersonnelDAO = new EmployeepersonnelMySqlDAO();
$Employeepersonnel = new Employeepersonnel();
$EmployeepersonnelEX = new EmployeepersonnelMySqlExtDAO();


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

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

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


$bank = new Bank();
$bankDAO = new BankMySqlDAO();

$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO;
$bankAccountEX = new BankaccountMySqlExtDAO;

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


//creat object from employee
$empDao = new EmployeeMySqlDAO();
$emp = new Employee();
$empEX = new EmployeeMySqlExtDAO();

$salaryReportDAO = new SalaryreportMySqlDAO;
$salaryReport = new Salaryreport;

//create object from savedailay
$SavedailyDAO = new SavedailyMySqlDAO();
$Savedaily = new Savedaily();
$SavedailyEX = new SavedailyMySqlExtDAO();
//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

$do = $_GET['do'];

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


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

    $today = date("Y-m-d H:i:s");
    $smarty->assign('today', $today);


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

    $save = $mySaveRecord->queryAll();
    $smarty->assign("save", $save);
    $bank = $bankDAO->queryAll();
    $smarty->assign("bank", $bank);

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

    $allemp = $empEX->queryAllemployeebycondation(0, $queryString);
    $smarty->assign('allemp', $allemp);

    //$smarty->assign("customemployeePersonal", 1);
    $smarty->display("employeePersonalview/add.html");
}

//save employee personnel in db
elseif ($do == "add") {
    include_once("../public/authentication.php");

    $employeepersonneltype = $_POST["type"];
    $employeeid = (int) $_POST["empName"];
    $paymethod = $_POST["paymethod"];
    $employeepersonneldate = $_POST["employeepersonneldate"];
    $deviceid = $_POST["deviceid"];
    $userid = $_SESSION['userid'];

    if ($_POST["saveid"]) {
        $saveid = $_POST["saveid"];
    } elseif ($_SESSION['saveid']) {
        $saveid = $_SESSION['saveid'];
    }

    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        $_POST["netSalary"] = getEmployeeNetSalary($employeeid);
        $deviceid = $_POST["deviceid"];
    }
    try {
        if ($employeepersonneltype == 10) { //kabd قبض Salary
            $Costcenterid = (int) $_POST["Costcenterid"];
            $salarymonthdate = date("Y-m", strtotime($employeepersonneldate));
            curlAddSalary($employeeid, $salarymonthdate, $Costcenterid);
            header("location:?do=sucess");
        } else {
            $employeepersonnelvalue = $_POST["empValue"];
            $netSalary = $_POST["netSalary"];
            //if ($employeepersonneltype == 3 && $netSalary < $employeepersonnelvalue) {
            if (in_array($employeepersonneltype, array(2, 3, 7, 9, 11, 12, 14)) && $netSalary < $employeepersonnelvalue) { //, 6
                if ($netSalary > 0) { //we will take part from this month and part from next month
                    $valueForNextMonth = $employeepersonnelvalue - $netSalary;
                    $id = add($netSalary, 0, $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, $saveid);
                    $id = add($valueForNextMonth, 1, $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, $saveid);
                } else { //no money available for this month take from next month
                    $valueForNextMonth = $employeepersonnelvalue;
                    $id = add($employeepersonnelvalue, 1, $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, $saveid);
                }
            } else {
                // $id = add($employeepersonnelvalue);
                $id = add($employeepersonnelvalue, '', $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, $saveid);
            }

            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

                1;
            } else {
                $print = (int) $_POST["print"];
                if ($print == 1) {
                    //print details
                    header("location:?do=editprint&id=" . $id);
                } else {
                    header("location:?do=sucess");
                }
            }
        }
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "addhazem") {
    include_once("../public/authentication.php");



    // $day = date('l', strtotime('2022-07-21 08:00:26'));
    // echo  $day;
    // exit();
    $data2 = "
     63;1;2022-07-22 08:00:00;1;7;0;
     **63;1;2022-07-22 16:00:00;1;7;0
     **63;1;2022-07-22 19:00:00;1;7;0;
     **63;1;2022-07-23 10:00:00;1;7;0;
     ";
    try {



        $lists = explode("**", $data2);
        foreach ($lists as $list) {
            $data = explode(';', $list);
            if ($list) {
                $employeeid = $data[3];
                $employeepersonneldate = $data[2];
                $deviceid = $data[4];
                $userid = $data[0];
                $time = date('H:i:s', strtotime($employeepersonneldate));
                $MONTH = date('m', strtotime($employeepersonneldate));
                $date = date('Y-m-d', strtotime($employeepersonneldate));
                $employeeholidays = R::count('employeeholidays', 'holiday_date = ?', [$date]);
                $day = date('l', strtotime($employeepersonneldate));
                $employee = R::getRow('SELECT * FROM employee WHERE employeeId = ?', [$employeeid]);
                $employeeattendancesystemweek = R::getRow('SELECT * FROM employeeattendancesystemweek WHERE employee_id = ? and attendancedayen = ?', [$employeeid, $day]);
                $startTime = date('H:i:s', strtotime('+' . $employee['numberOfMinutesOfDelayAllowed'] . ' minutes', strtotime($employeeattendancesystemweek['attendancetime'])));
                $getone = $EmployeepersonnelEX->countEmployeePersonnel($employeeid, $date);
                $minutes = $employee['Hourlyrate'] / 60;
                if ($employeeholidays) {
                    $employeepersonneltype = 13;
                    if (!$getone) {
                        $employeepersonnelvalue = 0;
                        add($employeepersonnelvalue, '', $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, 1);
                    } else if ($getone && $employeepersonneldate != $getone->employeepersonneldate) {
                        $getonebefore = $EmployeepersonnelEX->countEmployeePersonnelbefore($employeeid, $employeepersonneldate);
                        if (!$getonebefore) {
                            $diff_time = abs(strtotime($employeepersonneldate) - strtotime($getone->employeepersonneldate)) / 60;
                            $employeepersonnelvalue = $diff_time * $minutes;
                            add($employeepersonnelvalue, '', $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, 1);
                        }
                    } else {
                    }
                } else {

                    if ($getone) {
                        $getonebefore = $EmployeepersonnelEX->countEmployeePersonnelbefore($employeeid, $employeepersonneldate);
                        if ($employeeattendancesystemweek['departuretime'] < $time && !$getonebefore) {
                            $diff_time = abs(strtotime($time) - strtotime($employeeattendancesystemweek['departuretime'])) / 60;
                            $employeepersonnelvalue = $diff_time * $minutes;
                            $employeepersonneltype = 13;
                            add($employeepersonnelvalue, '', $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, 1);
                        }
                    } else if (!$getone && $time > $startTime) {

                        $diff_time = abs(strtotime($time) - strtotime($startTime)) / 60;

                        $employeepersonnel5 = R::getcell('SELECT count(*) FROM employeepersonnel WHERE employeeid = ? and employeepersonneltype = 5 and conditions = 0 ', [$employeeid]);
                        $employeepersonneltype = 5;
                        if ($diff_time > 0 && $employeepersonnel5 < $employee['numberOfCountsOfDelayAllowed']) {

                            if ($diff_time < 15) {
                                $employeepersonnelvalue = $employee['quarterHourLateWithoutPermissionDisount'];
                            } else if ($diff_time > 15 && $diff_time < 30) {
                                $employeepersonnelvalue = $employee['halfHourLateWithoutPermissionDisount'];
                            } else if ($diff_time > 30 && $diff_time < 60) {
                                $employeepersonnelvalue = $employee['hourLateWithoutPermissionDisount'];
                            } else if ($diff_time > 60 && $diff_time < 120) {
                                $employeepersonnelvalue = $employee['twoHoursLateWithoutPermissionDisount'];
                            } else {
                                $employeepersonnelvalue = $employee['twoHoursLateWithoutPermissionDisount'];
                            }
                        }

                        add($employeepersonnelvalue, '', $paymethod, $employeepersonneltype, $deviceid, $employeeid, $employeepersonneldate, $userid, 1);
                    } else {


                        add(0, '', $paymethod, 0, $deviceid, $employeeid, $employeepersonneldate, $userid, 1);
                    }
                }
            }
        }
        echo 1;
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
}
//show all
elseif ($do == "show") {
    if ($userData->searchinonesave == 0) {
        show();
    }

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

    $smarty->display('employeePersonalview/show.html');
} elseif ($do == "showdeptdef") {
    showdeptdef();
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display('employeePersonalview/showdeptdef.html');
}

//show all
elseif ($do == "editprint") {


    $mydata = editprint();

    $smarty->assign('mydata', $mydata);

    $smarty->display('employeePersonalview/editprint.html');
}



//delete
elseif ($do == "delete") {
    include_once("../public/authentication.php");

    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        $empid = (int) $_POST["empName"];
        $empValue = (float) $_POST["empValue"];
        $emDate = $_POST["employeepersonneldate"];
        $type = (int) $_POST["type"];
        $result = $EmployeepersonnelEX->queryByEmpDayTypeValue($empid, $empValue, $emDate, $type);
        $_GET["id"] = $result[0]->employeepersonnelid;
    }

    try {
        delete();

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo 1;
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        //echo $e;
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo -1;
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "noResult") {
    $smarty->display("employeePersonalview/noResult.html");
} elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}




$smarty->assign("customemployeePersonal", 1);
$smarty->assign("customValidation", 1);
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1 || $_GET['do'] == 'addhazem') {
    //no header its curl request
} else {
    $smarty->display("footer.html");
}

function editprint()
{
    global $EmployeepersonnelEX;
    $id = $_GET["id"];


    $mydata = $EmployeepersonnelEX->loadEX($id);
    return $mydata;
}

function show()
{
    global $smarty;
    global $empEX;
    global $empDao;
    global $myUserRecord;
    global $EmployeepersonnelEX;

    $queryString = ' AND employee.conditions = 0 AND';
    $queryString2 = ' AND employee.conditions = 0 AND';

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

    $empName = $_REQUEST["empName"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];
    $employeepersonneltype = $_REQUEST["employeepersonneltype"];

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



    if (isset($from) && $from != '' && isset($to) && $to != '') {
        $queryString .= ' date(employeepersonnel.employeepersonneldate) >= "' . $from . '" AND date(employeepersonnel.employeepersonneldate) <= "' . $to . '" AND';
        $queryString2 .= ' date(salaryreport.salaryreportdate) >= "' . $from . '" AND date(salaryreport.salaryreportdate) <= "' . $to . '" AND';
    } else {
        $queryString .= ' YEAR(employeepersonnel.employeepersonneldate) = YEAR(CURRENT_DATE()) AND MONTH(employeepersonnel.employeepersonneldate) = Month(CURRENT_DATE()) AND';
        $queryString2 .= ' YEAR(salaryreport.salaryreportdate) = YEAR(CURRENT_DATE()) AND MONTH(salaryreport.salaryreportdate) = Month(CURRENT_DATE()) AND';
    }



    if (isset($employeepersonneltype) && $employeepersonneltype != '-1') {
        if ($employeepersonneltype == 10) {
            //kabd قبض only
            $queryString .= ' employeepersonnel.employeeid = -1000 AND'; //means stop getting data from employeepersonnel
        } else {
            //dont search in salary report
            $queryString2 .= ' salaryreport.employeeid = -1000 AND'; //means stop getting data from salaryreport
        }
    }
    $userData = $myUserRecord->load($_SESSION['userid']);
    if ($userData->searchinonesave == 1) {
        $queryString .= ' ((employeepersonnel.paymenttype = 0 AND employeepersonnel.payid= ' . $userData->saveid . ')|| employeepersonnel.paymenttype = 1) AND';
    }

    $arr = explode(' ', $queryString);

    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {
            //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
            //$queryString .= ' ';
        } else if ($lastWord == 'WHERE') {
            //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }

    $arr = explode(' ', $queryString2);

    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {
            //remove it
            array_pop($arr);
            //form the string again
            $queryString2 = implode(' ', $arr);
            //$queryString .= ' ';
        } else if ($lastWord == 'WHERE') {
            //remove it
            array_pop($arr);
            $queryString2 = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }



    if ($_SESSION['branchId'] > 0)
        $qs = 'AND employee.branchid = ' . $_SESSION['branchId'];
    $allemp = $empEX->queryAllemployee(' where employee.conditions = 0 ' . $qs);

    $smarty->assign('allemp', $allemp);

    $allReward = 0;
    $allDiscount = 0;
    $allWithdrawal = 0;
    $allLoan = 0;
    $allLate = 0;
    $allPayLoan = 0;
    $allPaySalary = 0;
    $allEditDebit = 0;
    $allAbsence = 0;
    $allKabd = 0;
    $allPermission = 0;
    $artisticpenalty = 0;
    $extratime = 0;
    $allLeave = 0;

    $empIds = array();
    $allEmployeepersonnel = $EmployeepersonnelEX->queryAllEXWithDeleted2($queryString, $queryString2);
    foreach ($allEmployeepersonnel as $personnel) {
        if (!in_array($personnel->employeeid, $empIds)) {

            array_push($empIds, $personnel->employeeid);
        }
        if ($personnel->employeepersonneltype == 1 || $personnel->employeepersonneltype == 13) {
            if ($personnel->conditions == 0) {
                $allReward += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 2) {
            if ($personnel->conditions == 0) {
                $allDiscount += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 3) {
            if ($personnel->conditions == 0) {
                $allWithdrawal += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 4) {
            if ($personnel->conditions == 0) {
                $allLoan += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 5) {
            if ($personnel->conditions == 0) {
                $allLate += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 6) {
            if ($personnel->conditions == 0) {
                $allPayLoan += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 7) {
            if ($personnel->conditions == 0) {
                $allPaySalary += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 8) {
            if ($personnel->conditions == 0) {
                $allEditDebit += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 9) {
            if ($personnel->conditions == 0) {
                $allAbsence += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 10) {
            if ($personnel->conditions == 0) {
                $allKabd += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 11) {
            if ($personnel->conditions == 0) {
                $allPermission += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 12) {
            if ($personnel->conditions == 0) {
                $artisticpenalty += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 13) {
            if ($personnel->conditions == 0) {
                $extratime += $personnel->employeepersonnelvalue;
            }
        } elseif ($personnel->employeepersonneltype == 14) {
            if ($personnel->conditions == 0) {
                $allLeave += $personnel->employeepersonnelvalue;
            }
        }
    }
    $allSalary = 0;

    $date1 = $from;
    $date2 = $to;

    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);

    $year1 = date('Y', $ts1);
    $year2 = date('Y', $ts2);

    $month1 = date('m', $ts1);
    $month2 = date('m', $ts2);

    $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
    $diff++;
    foreach ($empIds as $empId) {
        $employeeData = $empDao->load($empId);
        $allSalary += $employeeData->employeeSalary * $diff; //*no of months
    }
    $smarty->assign('allEmployeepersonnel', $allEmployeepersonnel);

    $smarty->assign('allReward', $allReward);
    $smarty->assign('allDiscount', $allDiscount);
    $smarty->assign('allWithdrawal', $allWithdrawal);
    $smarty->assign('allLoan', $allLoan);
    $smarty->assign('allLate', $allLate);
    $smarty->assign('allPayLoan', $allPayLoan);
    $smarty->assign('allPaySalary', $allPaySalary);
    $smarty->assign('allEditDebit', $allEditDebit);
    $smarty->assign('allSalary', $allSalary);
    $smarty->assign('allAbsence', $allAbsence);
    $smarty->assign('allKabd', $allKabd);
    $smarty->assign('allPermission', $allPermission);
    $smarty->assign('artisticpenalty', $artisticpenalty);
    $smarty->assign('extratime', $extratime);
    $smarty->assign('allLeave', $allLeave);
}

function showdeptdef()
{
    global $smarty;
    global $empEX;
    global $EmployeepersonnelEX;

    $queryString = ' AND';

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

    $empName = $_REQUEST["empName"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];
    $employeepersonneltype = $_REQUEST["employeepersonneltype"];

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



    if (isset($from) && $from != '' && isset($to) && $to != '') {
        $queryString .= ' employeepersonnel.employeepersonneldate >= "' . $from . '" AND employeepersonnel.employeepersonneldate <= "' . $to . '" AND';
    }






    $arr = explode(' ', $queryString);

    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {
            //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
            //$queryString .= ' ';
        } else if ($lastWord == 'WHERE') {
            //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }


    if ($_SESSION['branchId'] > 0)
        $queryStringAll = ' where  branchid = ' . $_SESSION['branchId'];

    $allemp = $empEX->queryAllemployee($queryStringAll);
    $smarty->assign('allemp', $allemp);

    if (isset($queryString) && $queryString != "") {
        $allEmployeepersonneladvance = $EmployeepersonnelEX->queryAllEXsum($queryString, 4);
        $directPayment = $EmployeepersonnelEX->queryAllEXsum($queryString, 6);
        $Paymentfromsalary = $EmployeepersonnelEX->queryAllEXsum($queryString, 7);

        $remin = ($allEmployeepersonneladvance->total) - (($directPayment->total) + ($Paymentfromsalary->total));

        $smarty->assign('allEmployeepersonneladvance', $allEmployeepersonneladvance);
        $smarty->assign('directPayment', $directPayment);
        $smarty->assign('Paymentfromsalary', $Paymentfromsalary);
        $smarty->assign('remin', $remin);
    }
}

function delete()
{

    global $mySave;
    global $mySaveEx;
    global $mySaveRecord;

    global $mySavedaily;
    global $mySavedailyEx;
    global $mySavedailyRecord;

    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;

    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;



    $id = $_GET["id"];

    $CostcenterdetailEX->updatedellbytypeandmodelid('9,10,11', $id, 1);


    //print_r($Employeepersonnel);
    $mydata = $EmployeepersonnelDAO->load($id);

    $employeepersonneltype = $mydata->employeepersonneltype;
    $employeepersonnelvalue = $mydata->employeepersonnelvalue;


    $Employeepersonnel->conditions = 1;
    $Employeepersonnel->done = 1;
    $Employeepersonnel->userid = $_SESSION['userid'];
    $Employeepersonnel->employeepersonnelid = $id;

    $saveid = $_SESSION['saveid'];
    if ($mydata->paymenttype == 0)
        $saveid = $mydata->payid;

    if ($EmployeepersonnelEX->updatedel($Employeepersonnel)) {
        if ($employeepersonneltype == 3 || $employeepersonneltype == 4 || $employeepersonneltype == 6) { //سحب او سلفه
            //Insert in employeePersonnel
            if ($id != null) {

                $saveValueafterValid;
                $saveValueBefore = getSaveValueBefore($saveid);
                // الغاء سحب او سلف
                if ($employeepersonneltype == 3 || $employeepersonneltype == 4) {

                    $saveValueafterValid = $saveValueBefore + $employeepersonnelvalue;
                }

                //الغاء سداد سلفه
                elseif ($employeepersonneltype == 6) {
                    $saveValueafterValid = $saveValueBefore - $employeepersonnelvalue;
                }




                updateSave($saveid, $saveValueafterValid);


                //الغاء سحب
                if ($employeepersonneltype == 3) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 0, $saveid, 'حذف سحب لموظف', $id, $saveValueafterValid, 'employeePersonalController.php');
                }
                // الغاء سلفه
                elseif ($employeepersonneltype == 4) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 0, $saveid, 'حذف سلفه لموظف', $id, $saveValueafterValid, 'employeePersonalController.php');
                }



                // الغاء سداد سلفه
                elseif ($employeepersonneltype == 6) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 1, $saveid, ' حذف سداد سلفه لموظف', $id, $saveValueafterValid, 'employeePersonalController.php');
                }
                //print_r($currentvalue);
            }
            reverseEntryWithItsID($mydata->dailyentryid);
        }
    }
}

function add(
    $employeepersonnelvalue,
    $saveInNextMonth = 0,
    $paymethod = 0,
    $employeepersonneltype = 0,
    $deviceid = '01',
    $employeeid,
    $employeepersonneldate = "date('Y-m-d H:i:s')",
    $userid = 0,
    $saveid = 0
) {

    global $mySave;
    global $mySaveEx;
    global $mySaveRecord;

    global $mySavedaily;
    global $mySavedailyEx;
    global $mySavedailyRecord;

    global $Employeepersonnel;
    global $EmployeepersonnelDAO;

    global $empDao;
    global $emp;
    global $empEX;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    global $bankAccountDAO;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    // $employeepersonneltype = $_POST["type"];
    $employeepersonnelnote = $_POST["desc"];
    // $employeeid = $_POST["empName"];
    $Costcenterid = $_POST["Costcenterid"];
    // $paymethod = $_POST["paymethod"];
    $isMandobReward = (int) $_POST["isMandobReward"];
    // //$today = date("Y-m-d H:i:s");
    // $employeepersonneldate = $_POST["employeepersonneldate"];
    // $deviceid = $_POST["deviceid"];
    // $timePart = date('H:i:s', strtotime($employeepersonneldate));
    // if ($saveInNextMonth == 1) { //use first day from next month
    //     $employeepersonneldate = date("Y-m-1 $timePart", strtotime('+1 months'));
    // }

    $Employeepersonnel->employeepersonneldate = $employeepersonneldate; //$today;
    $Employeepersonnel->conditions = 0;
    $Employeepersonnel->employeepersonnelvalue = $employeepersonnelvalue;
    $Employeepersonnel->employeepersonneltype = $employeepersonneltype;
    $Employeepersonnel->employeepersonnelnote = $employeepersonnelnote;
    $Employeepersonnel->employeeid = $employeeid;
    $Employeepersonnel->deviceid = $deviceid;
    $Employeepersonnel->employeedeviceid = $deviceid . $employeeid;
    $Employeepersonnel->userid = $userid;

    $treeIdBankAccount = 0;
    $treeIdSave = 0;
    $paymethodTreeId = 0;

    if ($paymethod == 1) {
        ##bank
        $bankid = $_POST["bankid"];
        $bankaccountid = $_POST["bankaccountid"];
        $checkNo = $_POST["checkNo"];

        $Employeepersonnel->paymenttype = 1;
        $Employeepersonnel->payid = $bankid;
        $Employeepersonnel->payid2 = $bankaccountid;
        $Employeepersonnel->checknum = $checkNo;

        $bankAccountData = $bankAccountDAO->load($bankaccountid);
        $treeIdBankAccount = $paymethodTreeId = $bankAccountData->treeId;
    } else {
        ##save
        $Employeepersonnel->paymenttype = 0;
        $Employeepersonnel->payid = $saveid;
        $Employeepersonnel->payid2 = 0;
        $Employeepersonnel->checknum = "";

        $saveData = $mySaveRecord->load($saveid);
        $treeIdSave = $paymethodTreeId = $saveData->treeId;
    }

    $myempdata = $empDao->load($employeeid);
    $modelId;
    $empdept = $myempdata->empdept;
    //here types that affect employee debt, part of net salary is calculated in ajax employeePersonalajex.php?do=getNetSalary and salaryReportController.php
    if ($employeepersonneltype == 4 || $employeepersonneltype == 6) {
        $empdeptafter;
        //سلفه
        if ($employeepersonneltype == 4) {
            $empdeptafter = $empdept + $employeepersonnelvalue;
        }

        //سداد سلفه
        elseif ($employeepersonneltype == 6) {

            $empdeptafter = $empdept - $employeepersonnelvalue;
        }


        $emp->empdept = $empdeptafter;
        $emp->employeeId = $employeeid;
        $empEX->updatedept($emp);
    } elseif ($employeepersonneltype == 8) {

        $empdeptafter = $employeepersonnelvalue;
        $emp->empdept = $empdeptafter;
        $emp->employeeId = $employeeid;
        $empEX->updatedept($emp);
    } else {
        $empdeptafter = $empdept;
    }

    $Employeepersonnel->empdeptafter = $empdeptafter;
    $Employeepersonnel->empdeptbefor = $empdept;
    $Employeepersonnel->isMandobReward = $isMandobReward;
    $modelId = $EmployeepersonnelDAO->insert($Employeepersonnel);
    //print_r($Employeepersonnel);
    //$Revenuestype->userid=$_SESSION['userid'];

    if ($employeepersonneltype == 3 || $employeepersonneltype == 4 || $employeepersonneltype == 6) { //سحب او سلفه
        if ($employeepersonneltype == 3) {
            $Costcenterdetail->processname = 'سحب لموضف';
            $Costcenterdetail->type = 9;
        } elseif ($employeepersonneltype == 4) {
            $Costcenterdetail->processname = 'سلفه لموظف';
            $Costcenterdetail->type = 10;
        } elseif ($employeepersonneltype == 6) {
            $Costcenterdetail->processname = 'سداد سلفه مباشره';
            $Costcenterdetail->type = 11;
        }
        $Costcenterdetail->costamount = $employeepersonnelvalue;
        $Costcenterdetail->costcenterid = $Costcenterid;
        $Costcenterdetail->costdate = date('Y-m-d');
        $Costcenterdetail->del = 0;
        $Costcenterdetail->modelid = $modelId;
        $Costcenterdetail->tablename = 'employeePersonalController.php';
        $Costcenterdetail->uesrid = $userid;

        if ($Costcenterid != -1 && $Costcenterid != '-1') {
            $CostcenterdetailDAO->insert($Costcenterdetail);
        }

        //Insert in employeePersonnel
        if ($employeepersonneltype == 8) {
        } else {
            if ($modelId != null) {

                // $saveId = $saveid;
                // if ($_POST["saveid"] != $_SESSION['saveid'])
                $saveId = $saveid;
                $saveValueafterValid;
                $saveValueBefore = getSaveValueBefore($saveId);

                if ($employeepersonneltype == 3 || $employeepersonneltype == 4) {

                    $saveValueafterValid = $saveValueBefore - $employeepersonnelvalue;
                } elseif ($employeepersonneltype == 6) {
                    $saveValueafterValid = $saveValueBefore + $employeepersonnelvalue;
                }




                updateSave($saveId, $saveValueafterValid);


                if ($employeepersonneltype == 3) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 1, $saveId, 'اضافه سحب لموظف', $modelId, $saveValueafterValid, 'employeePersonalController.php');
                } elseif ($employeepersonneltype == 4) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 1, $saveId, 'اضافه سلفه لموظف', $modelId, $saveValueafterValid, 'employeePersonalController.php');
                } elseif ($employeepersonneltype == 6) {

                    insertSavedaily($saveValueBefore, $employeepersonnelvalue, 0, $saveId, 'سداد سلفه لموظف', $modelId, $saveValueafterValid, 'employeePersonalController.php');
                }
                //print_r($currentvalue);
            }
        }
    }

    doEmployeePersonalDailyEntry($modelId);
    return $modelId;
}

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

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

    $saveData = getSaveDataFromSaveInUseSP($saveid); //$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 = getSaveDataFromSaveInUseSP($saveid); //$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 = getSaveDataFromSaveInUseSP($saveid); //$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);
    markSaveAsNOTInUse($saveid);
}

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

    $mySavedailyRecord->insert($mySavedaily);
}

function getSaveDataFromSaveInUseSP($saveid)
{
    global $mySaveEx;

    $noOfTries = 0;
    $save_data = $mySaveEx->callSaveInUseSP($saveid);

    while ($save_data->saveid < 0) {
        sleep(1);
        $noOfTries++;
        if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
            //markSaveAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
            liveBackupComment("-- force free save=$saveid with redbean");
            R::exec('UPDATE save SET  inUse = 0 where saveid = ' . $saveid);
        }
        $save_data = $mySaveEx->callSaveInUseSP($saveid);
    }
    return $save_data;
}

function markSaveAsNOTInUse($saveid)
{ //mark as not in use "free him to be able to change debt again"
    global $mySaveEx;
    $mySaveEx->markSaveAsNOTInUse($saveid);
}

function getEmployeeNetSalary($id)
{ //copied from employeePersonalajex.php?do=getNetSalary
    global $empEX;

    $today = date("Y-m-d");
    $from = date("Y-m");
    if ($from != "") {
        $start = $from . '-01';
        $end = $from . '-31';
        //
        $x[] = array();
        $qs = ' AND employeepersonneldate <= "'.$end.' 23:59:59"';
            $allsalarys = $empEX->getall($id,$qs);

        if ($allsalarys->employeeBouns == null || $allsalarys->employeeBouns == "") {
            $allsalarys->employeeBouns = 0;
        }
        if ($allsalarys->empdept == null || $allsalarys->empdept == "" || $allsalarys->empdept == 0) {
            $allsalarys->empdept = 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;
        }

        $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[10] = ($allsalarys->empdept) - ($allsalarys->Repayment); //current dept



        $total = (($allsalarys->employeeBouns) + ($allsalarys->Reward) + ($allsalarys->employeeSalary)) -
            (($allsalarys->Discount) + ($allsalarys->Withdraw) + ($allsalarys->Absence) + ($allsalarys->Repayment));

        $x[8] = $total; //net salary
        //echo $x[8] . "*" . $x[10]; //net salary,current dept
        return array($x[8], $x[10]);
    }
}

function doEmployeePersonalDailyEntry($EmployeepersonnelId)
{
    global $EmployeepersonnelDAO;
    global $empDao;
    global $mySaveRecord;
    global $bankAccountDAO;

    ## get data
    $Employeepersonnel = $EmployeepersonnelDAO->load($EmployeepersonnelId);
    $myempdata = $empDao->load($Employeepersonnel->employeeid);
    $employeepersonnelvalue = $Employeepersonnel->employeepersonnelvalue;
    $employeepersonneltype = $Employeepersonnel->employeepersonneltype;

    if ($Employeepersonnel->paymenttype == 1) {
        ##bank
        $bankid = $Employeepersonnel->payid;
        $bankaccountid = $Employeepersonnel->payid2;

        $bankAccountData = $bankAccountDAO->load($bankaccountid);
        $treeIdBankAccount = $paymethodTreeId = $bankAccountData->treeId;
    } else {
        ##save
        $saveid = $Employeepersonnel->payid;
        $saveData = $mySaveRecord->load($saveid);
        $treeIdSave = $paymethodTreeId = $saveData->treeId;
    }


    ## do daily entry for save involved only
    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $employeepersonnelvalue;
    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $employeepersonnelvalue;

    ######
    switch ($employeepersonneltype) {

            //سحب//-
        case 3:
            $dailyEntry->entryComment = 'سحب لموظف ' . $myempdata->employeeName;
            $dailyEntryDebtor->accountstreeid = $myempdata->treeId;
            $dailyEntryCreditor->accountstreeid = $paymethodTreeId;
            break;
            //سلفه//-
        case 4:
            $dailyEntry->entryComment = 'سلفه لموظف ' . $myempdata->employeeName;
            $dailyEntryDebtor->accountstreeid = $myempdata->treeId;
            $dailyEntryCreditor->accountstreeid = $paymethodTreeId;
            break;
            //سداد سلفه مباشره//+
        case 6:
            $dailyEntry->entryComment = 'سداد سلفه مباشره لموظف ' . $myempdata->employeeName;
            $dailyEntryDebtor->accountstreeid = $paymethodTreeId;
            $dailyEntryCreditor->accountstreeid = $myempdata->treeId;
            break;
    }
    //daily Entry
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
    $did = $returnedData[1];
    $Employeepersonnel->dailyentryid = $did;
    $Employeepersonnel->employeepersonnelid = $EmployeepersonnelId;
    $EmployeepersonnelDAO->update($Employeepersonnel);
}

//better to add client using erp files it self so use  curl "it is like post requist but in php"
function curlAddSalary($empid, $salarymonthdate, $Costcenterid)
{
    // set post fields
    $post = [
        'fromCtrl' => 'employeePersonal',
        'empid' => $empid,
        'Costcenterid' => $Costcenterid,
        'salarymonthdate' => $salarymonthdate,
        'userid' => $_SESSION['userid'],
        'saveid' => $_SESSION["saveid"],
        'dbname' => $_SESSION["dbname"],
    ];

    //$ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient');
    $ch = curl_init('http://localhost/ERP/controllers/salaryReportController.php?do=Receipt');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    // execute!
    $response = curl_exec($ch);

    // close the connection, release resources used
    curl_close($ch);

    // do anything you want with your response
    var_dump($response);
}
