<?php

$do = isset($_GET['do']) ? $_GET['do'] : '';
$ajaxDoArr = array('getdaytoclose', 'closeday');
//the global file operation
if (!in_array($do, $ajaxDoArr)) {
    include("../public/impOpreation.php");
}

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
//Transaction
include_once("../models/sql/Transaction.class.php");

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");

//Employee
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');
//Employeegroup
require_once('../models/dao/EmployeegroupDAO.class.php');
require_once('../models/dto/Employeegroup.class.php');
require_once('../models/mysql/EmployeegroupMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeegroupMySqlExtDAO.class.php');
//Employeesubgroup
require_once('../models/dao/EmployeesubgroupDAO.class.php');
require_once('../models/dto/Employeesubgroup.class.php');
require_once('../models/mysql/EmployeesubgroupMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeesubgroupMySqlExtDAO.class.php');
//Employeeattendancesystem
require_once('../models/dao/EmployeeattendancesystemDAO.class.php');
require_once('../models/dto/Employeeattendancesystem.class.php');
require_once('../models/mysql/EmployeeattendancesystemMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeattendancesystemMySqlExtDAO.class.php');

//Employeeclosedaygroupstatus
require_once('../models/dao/EmployeeclosedaygroupstatusDAO.class.php');
require_once('../models/dto/Employeeclosedaygroupstatu.class.php');
require_once('../models/mysql/EmployeeclosedaygroupstatusMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeclosedaygroupstatusMySqlExtDAO.class.php');
//Employeeclosedayhistory
require_once('../models/dao/EmployeeclosedayhistoryDAO.class.php');
require_once('../models/dto/Employeeclosedayhistory.class.php');
require_once('../models/mysql/EmployeeclosedayhistoryMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeclosedayhistoryMySqlExtDAO.class.php');
//Employeeclosedaystatus
require_once('../models/dao/EmployeeclosedaystatusDAO.class.php');
require_once('../models/dto/Employeeclosedaystatu.class.php');
require_once('../models/mysql/EmployeeclosedaystatusMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeclosedaystatusMySqlExtDAO.class.php');
//Employeeclosedaysubgroupstatus
require_once('../models/dao/EmployeeclosedaysubgroupstatusDAO.class.php');
require_once('../models/dto/Employeeclosedaysubgroupstatu.class.php');
require_once('../models/mysql/EmployeeclosedaysubgroupstatusMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeclosedaysubgroupstatusMySqlExtDAO.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');

//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 :-storeCTRL
  ======================== */

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("header.html");
}
//create object  from employee
$employee = new Employee();
$employeeDAO = new EmployeeMySqlDAO();
$employeeEX = new EmployeeMySqlExtDAO();
//Employeegroup
$employeeGroup = new Employeegroup();
$employeeGroupDAO = new EmployeegroupMySqlDAO();
$employeeGroupEX = new EmployeegroupMySqlExtDAO();
//Employeesubgroup
$employeeSubGroup = new Employeesubgroup();
$employeeSubGroupDAO = new EmployeesubgroupMySqlDAO();
$employeeSubGroupEX = new EmployeesubgroupMySqlExtDAO();
//Employeeattendancesystem
$employeeAttendanceSystem = new Employeeattendancesystem();
$employeeAttendanceSystemDAO = new EmployeeattendancesystemMySqlDAO();
$employeeAttendanceSystemEX = new EmployeeattendancesystemMySqlExtDAO();

//Employeeclosedayhistory
$employeeCloseDayHistory = new Employeeclosedayhistory();
$employeeCloseDayHistoryDAO = new EmployeeclosedayhistoryMySqlDAO();
$employeeCloseDayHistoryEX = new EmployeeclosedayhistoryMySqlExtDAO();
//Employeeclosedaygroupstatus
$employeeCloseDayGroupStatus = new Employeeclosedaygroupstatu();
$employeeCloseDayGroupStatusDAO = new EmployeeclosedaygroupstatusMySqlDAO();
$employeeCloseDayGroupStatusEX = new EmployeeclosedaygroupstatusMySqlExtDAO();
//Employeeclosedaystatus
$Employeeclosedaystatus = new Employeeclosedaystatu();
$EmployeeclosedaystatusDAO = new EmployeeclosedaystatusMySqlDAO();
$EmployeeclosedaystatusEX = new EmployeeclosedaystatusMySqlExtDAO();
//Employeeclosedaysubgroupstatus
$Employeeclosedaysubgroupstatus = new Employeeclosedaysubgroupstatu();
$EmployeeclosedaysubgroupstatusDAO = new EmployeeclosedaysubgroupstatusMySqlDAO();
$EmployeeclosedaysubgroupstatusEX = new EmployeeclosedaysubgroupstatusMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//Store
//check and use the condetion that suite this action
if (empty($do) || $do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //here the smarty templates
    $smarty->display("employeeenddayview/add.html");
} elseif ($do == "getdaytoclose") {
    $day = filter_input(INPUT_POST, 'day');
    $employeegroupid = (int) filter_input(INPUT_POST, 'employeegroupid');
    $employeesubgroupid = (int) filter_input(INPUT_POST, 'employeesubgroupid');

    $queryString = ' WHERE employee.conditions=0 ';
    if ($employeesubgroupid > 0) {
        $queryString .= " and employeesubgroupid = $employeesubgroupid ";
    } elseif ($employeegroupid > 0) {
        $queryString .= " and employeegroupid = $employeegroupid ";
    }

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

    $employeeArr = $employeeEX->queryAllQueryString($queryString, $day);
    foreach ($employeeArr as $emp) {
        //$emp->attendanceSys = json_encode($employeeAttendanceSystemEX->getAttendanceSystemByEmployeeSubGroup($emp->employeesubgroupid));
        $attendanceSysData = $employeeAttendanceSystemEX->getAttendanceSystemByEmployeeSubGroup($emp->employeesubgroupid);
        $sys = new stdClass();
        //getting  times from AttendanceSystem
        $sys->attendanceTime = $attendanceSysData->attendanceTime;
        $sys->departureTime = $attendanceSysData->departureTime;
        //getting discount from employee
        $sys->halfHourLateWithPermissionDisount = $emp->halfHourLateWithPermissionDisount;
        $sys->hourLateWithPermissionDisount = $emp->hourLateWithPermissionDisount;
        $sys->hourAndHalfLateWithPermissionDisount = $emp->hourAndHalfLateWithPermissionDisount;
        $sys->twoHoursLateWithPermissionDisount = $emp->twoHoursLateWithPermissionDisount;
        $sys->halfHourLateWithoutPermissionDisount = $emp->halfHourLateWithoutPermissionDisount;
        $sys->hourLateWithoutPermissionDisount = $emp->hourLateWithoutPermissionDisount;
        $sys->hourAndHalfLateWithoutPermissionDisount = $emp->hourAndHalfLateWithoutPermissionDisount;
        $sys->twoHoursLateWithoutPermissionDisount = $emp->twoHoursLateWithoutPermissionDisount;
        $sys->halfHourPermissionDisount = $emp->halfHourPermissionDisount;
        $sys->hourPermissionDisount = $emp->hourPermissionDisount;
        $sys->hourAndHalfPermissionDisount = $emp->hourAndHalfPermissionDisount;
        $sys->twoHoursPermissionDisount = $emp->twoHoursPermissionDisount;
        $sys->dayAbsenceWithPermissionDisount = $emp->dayAbsenceWithPermissionDisount;
        $sys->dayAbsenceWithoutPermissionDisount = $emp->dayAbsenceWithoutPermissionDisount;
        $sys->moreThanTwoHoursLateWithPermissionDisount = $emp->moreThanTwoHoursLateWithPermissionDisount;
        $sys->moreThanTwoHoursLateWithoutPermissionDisount = $emp->moreThanTwoHoursLateWithoutPermissionDisount;
        $emp->attendanceSys = json_encode($sys);//take emp special attendance data not system
    }
    $smarty->assign('employeeArr', $employeeArr);
    $smarty->assign('day', $day);
    $smarty->assign('employeegroupid', $employeegroupid);
    $smarty->assign('employeesubgroupid', $employeesubgroupid);

    $smarty->display("employeeenddayview/day.html");
} elseif ($do == "closeday") {
    //Transaction
    $mytransactions = new Transaction();
    try {
        $day = filter_input(INPUT_POST, 'day');
        $empitr = (int) filter_input(INPUT_POST, 'empitr');
        $employeegroupid = (int) filter_input(INPUT_POST, 'employeegroupid_day');
        $employeesubgroupid = (int) filter_input(INPUT_POST, 'employeesubgroupid_day');
        
        if (isRealDate($day) && $empitr > 1) {//if there is one row only itr will equal 2
            //1-insert in employeeCloseDayHistory
            for ($i = 1; $i < $empitr; $i++) {
                $empid = (int) filter_input(INPUT_POST, 'empid' . $i);

                $id = (int)filter_input(INPUT_POST, 'id' . $empid);
                $oldEmployeeCloseDayHistory = $employeeCloseDayHistoryDAO->load($id);
                $attendanceTime = filter_input(INPUT_POST, 'attendanceTime' . $empid);
                $departureTime = filter_input(INPUT_POST, 'departureTime' . $empid);
                $latePeriod = (float) filter_input(INPUT_POST, 'latePeriod' . $empid);
                $lateHasPermission = (int) filter_input(INPUT_POST, 'lateHasPermission' . $empid);
                $lateDiscount = (float) filter_input(INPUT_POST, 'lateDiscount' . $empid);
                $isAbsent = (int) filter_input(INPUT_POST, 'isAbsent' . $empid);
                $absentHasPermission = (int) filter_input(INPUT_POST, 'absentHasPermission' . $empid);
                $absentDiscount = (float) filter_input(INPUT_POST, 'absentDiscount' . $empid);


                $employeeCloseDayHistory->id = $id;
                $employeeCloseDayHistory->day = $day;
                $employeeCloseDayHistory->employeeid = $empid;
                if ($isAbsent == 0) {//not absent
                    $employeeCloseDayHistory->attendanceTime = $attendanceTime . ":00";
                    $employeeCloseDayHistory->departureTime = $departureTime . ":00";
                    $employeeCloseDayHistory->latePeriod = $latePeriod;
                    $employeeCloseDayHistory->lateHasPermission = $lateHasPermission;
                    $employeeCloseDayHistory->lateDiscount = $lateDiscount;
                    $employeeCloseDayHistory->isAbsent = 0;
                    $employeeCloseDayHistory->absentHasPermission = 0;
                    $employeeCloseDayHistory->absentDiscount = 0;
                } elseif ($isAbsent == 1) {//absent
                    $employeeCloseDayHistory->attendanceTime = "00:00:00";
                    $employeeCloseDayHistory->departureTime = "00:00:00";
                    $employeeCloseDayHistory->latePeriod = 0;
                    $employeeCloseDayHistory->lateHasPermission = 0;
                    $employeeCloseDayHistory->lateDiscount = 0;
                    $employeeCloseDayHistory->isAbsent = $isAbsent;
                    $employeeCloseDayHistory->absentHasPermission = $absentHasPermission;
                    $employeeCloseDayHistory->absentDiscount = $absentDiscount;
                }
                $employeeCloseDayHistory->userid = $_SESSION['userid'];
                $employeeCloseDayHistory->sysdate = date('Y-m-d H:i:s');
                $employeeCloseDayHistory->del = 0;
                $employeeCloseDayHistory->status = 1;//affects has been done
                
                $employeeCloseDayHistoryDAO->update($employeeCloseDayHistory);
                affectOnSalary($employeeCloseDayHistory,$oldEmployeeCloseDayHistory);
            }
            
            

            //2-affect Employeeclose subgroup,group,day status
            if ($employeesubgroupid > 0) {
                $Employeeclosedaysubgroupstatus = $EmployeeclosedaysubgroupstatusEX->queryByDayAndEmployeesubgroupid($employeesubgroupid,$day);
                $Employeeclosedaysubgroupstatus->day = $day;
                $Employeeclosedaysubgroupstatus->employeesubgroupid = $employeesubgroupid;
                $Employeeclosedaysubgroupstatus->status = 1;
                $Employeeclosedaysubgroupstatus->userid = $_SESSION['userid'];
                $Employeeclosedaysubgroupstatus->sysdate = date('Y-m-d H:i:s');
                $Employeeclosedaysubgroupstatus->conditions = 0;
                if((int)$Employeeclosedaysubgroupstatus->id > 0){
                    $EmployeeclosedaysubgroupstatusDAO->update($Employeeclosedaysubgroupstatus);
                }else{
                    $EmployeeclosedaysubgroupstatusDAO->insert($Employeeclosedaysubgroupstatus);
                }
                
                


                //3-if group closed in that day mark it
                $subGroupData = $employeeSubGroupDAO->load($employeesubgroupid);
                $noOfSubGroupsInaGroup = count($employeeSubGroupEX->queryByEmployeegroupidEX($subGroupData->employeegroupid));
                $noOfSubGroupsClosedInaGroupForADay = count($EmployeeclosedaysubgroupstatusEX->queryByEmployeegroupidAndDayGetDistinctSubGroupsClosed($subGroupData->employeegroupid, $day));
                if ($noOfSubGroupsInaGroup == $noOfSubGroupsClosedInaGroupForADay) {
                    //mark as colsed
                    $employeeCloseDayGroupStatus = $employeeCloseDayGroupStatusEX->queryByDayAndEmployeegroupid($employeegroupid,$day);
                    $employeeCloseDayGroupStatus->day = $day;
                    $employeeCloseDayGroupStatus->employeegroupid = $employeegroupid;
                    $employeeCloseDayGroupStatus->status = 1;
                    $employeeCloseDayGroupStatus->userid = $_SESSION['userid'];
                    $employeeCloseDayGroupStatus->sysdate = date('Y-m-d H:i:s');
                    $employeeCloseDayGroupStatus->conditions = 0;
                    if((int)$employeeCloseDayGroupStatus->id > 0){
                        $employeeCloseDayGroupStatusDAO->update($employeeCloseDayGroupStatus);
                    }else{
                        $employeeCloseDayGroupStatusDAO->insert($employeeCloseDayGroupStatus);
                    }
                    
                }
            } else if ($employeegroupid > 0) {
                $EmployeeclosedaysubgroupstatusEX->insertAllSubGroupStatusForADaySpecial($day, $_SESSION['userid'], date('Y-m-d H:i:s'));
                //3-mark group as closed in that day
                $employeeCloseDayGroupStatus = $employeeCloseDayGroupStatusEX->queryByDayAndEmployeegroupid($employeegroupid,$day);
                $employeeCloseDayGroupStatus->day = $day;
                $employeeCloseDayGroupStatus->employeegroupid = $employeegroupid;
                $employeeCloseDayGroupStatus->status = 1;
                $employeeCloseDayGroupStatus->userid = $_SESSION['userid'];
                $employeeCloseDayGroupStatus->sysdate = date('Y-m-d H:i:s');
                $employeeCloseDayGroupStatus->conditions = 0;
                if((int)$employeeCloseDayGroupStatus->id > 0){
                    $employeeCloseDayGroupStatusDAO->update($employeeCloseDayGroupStatus);
                }else{
                    $employeeCloseDayGroupStatusDAO->insert($employeeCloseDayGroupStatus);
                }
            }
            //4- affect day as closed if allgroups closed
            $noOfGroups = $employeeGroupEX->queryAllEXCount();
            $noOfGroupsClosedInADay = $employeeCloseDayGroupStatusEX->getNoOfGroupsClosedInADay($day);
            if ($noOfGroups == $noOfGroupsClosedInADay) {
                //mark as colsed
                $res = $EmployeeclosedaystatusDAO->queryByDay($day);
                $Employeeclosedaystatus = $res[0];
                $Employeeclosedaystatus->day = $day;
                $Employeeclosedaystatus->status = 1;
                $Employeeclosedaystatus->userid = $_SESSION['userid'];
                $Employeeclosedaystatus->sysdate = date('Y-m-d H:i:s');
                $Employeeclosedaystatus->conditions = 0;
                if((int)$Employeeclosedaystatus->id > 0){
                    $EmployeeclosedaystatusDAO->update($Employeeclosedaystatus);
                }else{
                    $EmployeeclosedaystatusDAO->insert($Employeeclosedaystatus);
                }
                
            }
        }
        echo 1;
        $mytransactions->commit();
    } catch (Exception $e) {
        echo -1;
        $mytransactions->rollback($e);
    }
} elseif ($do == "closedayshow") {

    $month = filter_input(INPUT_POST, 'theDay');
    $empid = (int) filter_input(INPUT_POST, 'empid');

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

    // $employees = $employeeDAO->queryByConditions(0);
    $allEmployee = $employeeEX->queryAllemployeebycondation(0, $queryStringAll);
    $smarty->assign("allEmployee", $allEmployee);

    if ($empid > 0 && isset($month) && !empty($month)) {
        $from = $month . "-01";
        $to = $month . "-31";

        $queryString = ' and employeeid =' . $empid;
        $queryString .= ' and day >= "' . $from . '" and day <= "' . $to . '" ';
        $queryString .= ' order by day asc ';

        $employeeHistory = $employeeCloseDayHistoryEX->getEmployeeHistoryByQueryString($queryString);

        $smarty->assign("employeeHistory", $employeeHistory);
    }


    //here the smarty templates
    $smarty->display("employeeenddayview/show.html");
} elseif ($do == "sucess") {

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

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

$smarty->assign("employeeendday", 1);
$smarty->assign("customValidation", 1);

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("footer.html");
}

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

function isRealDate($date) {
    if (false === strtotime($date)) {
        return false;
    }
    list($year, $month, $day) = explode('-', $date);
    return checkdate($month, $day, $year);
}
function affectOnSalary($newEmployeeCloseDayHistory,$oldEmployeeCloseDayHistory){
    //1- check if there is changes => if same values do nothing
    if($oldEmployeeCloseDayHistory->status == 1 && $newEmployeeCloseDayHistory->isAbsent == $oldEmployeeCloseDayHistory->isAbsent && $newEmployeeCloseDayHistory->absentDiscount == $oldEmployeeCloseDayHistory->absentDiscount 
            && $newEmployeeCloseDayHistory->lateDiscount == $oldEmployeeCloseDayHistory->lateDiscount){
        //status 1 => already affect salary
        //in this case it is not new it affect salary before and no changes are made
        //echo "no thing";
    }else{
        //in this case it is new or edited depending on status
        if($oldEmployeeCloseDayHistory->status != -1){
            //echo "del";
            //editing and change in discount to salary remove it 
            if ($oldEmployeeCloseDayHistory->isAbsent == 0) {//not absent
                curlDeleteEmployeePersonal($oldEmployeeCloseDayHistory->employeeid, $oldEmployeeCloseDayHistory->day, $oldEmployeeCloseDayHistory->lateDiscount, 5);
            } elseif ($oldEmployeeCloseDayHistory->isAbsent == 1) {//absent
                curlDeleteEmployeePersonal($oldEmployeeCloseDayHistory->employeeid, $oldEmployeeCloseDayHistory->day, $oldEmployeeCloseDayHistory->absentDiscount, 9);
            }
        }
        
        //now affect salary with new
        //echo "add";
        if ($newEmployeeCloseDayHistory->isAbsent == 0) {//not absent
            //affect employee with late
            curlAddEmployeePersonal($newEmployeeCloseDayHistory->employeeid, $newEmployeeCloseDayHistory->day, $newEmployeeCloseDayHistory->lateDiscount, 5);
        } elseif ($newEmployeeCloseDayHistory->isAbsent == 1) {//absent
            //affect employee with absence?
            curlAddEmployeePersonal($newEmployeeCloseDayHistory->employeeid, $newEmployeeCloseDayHistory->day, $newEmployeeCloseDayHistory->absentDiscount, 9);
        }
    }
    
    
}
//like adding absent,late,... discount
function curlAddEmployeePersonal($empid, $day, $discountVal, $type) {
    if($discountVal != 0){
        //'type' => '5' it is late, 'type' => '9' it is absent
        $dayAsDateTime = $day." ".date('H:i:s');
        // set post fields
        $post = [
            'fromCtrl' => 'employeeendday',
            'empName' => $empid,
            'empValue' => $discountVal,
            'employeepersonneldate' => $dayAsDateTime,//date('Y-m-d H:i:s'),
            'type' => $type,
            'Costcenterid' => '-1',
            'netSalary' => '',
            'desc' => '',//"تقفيل يوم : $day",
            'paymethod' => '0',
            'bankid' => '-1',
            'checkNo' => '',
            'print' => '0',
            '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/employeePersonalController.php?do=add');
        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);
    }
}

function curlDeleteEmployeePersonal($empid, $day, $discountVal, $type) {
    if($discountVal != 0) {
        //'type' => '5' it is late, 'type' => '9' it is absent
        // set post fields
        $post = [
            'fromCtrl' => 'employeeendday',

            'empName' => $empid,
            'empValue' => $discountVal,
            'employeepersonneldate' => $day,
            'type' => $type,

            '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/employeePersonalController.php?do=delete');
        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);
    }
}
