<?php

$do = isset($_GET['do']) ? $_GET['do'] : '';
$ajaxDoArr = array('', 'add', 'saveaccesslog');
if (!in_array($do, $ajaxDoArr)) {
    //the global file operation
    include("../public/impOpreation.php");
}
################################################################################
# this controller is only to save time of attendance and departure
################################################################################
//Transaction
include_once("../models/sql/Transaction.class.php");

// get the config file
include_once("../public/config.php");


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


require_once('../models/dao/EmployeeattendanceDAO.class.php');
require_once('../models/dto/Employeeattendance.class.php');
require_once('../models/mysql/EmployeeattendanceMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeattendanceMySqlExtDAO.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');
//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');
//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');

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


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

$employeeAttendance = new Employeeattendance();
$employeeAttendanceDAO = new EmployeeattendanceMySqlDAO();
$employeeAttendanceEX = new EmployeeattendanceMySqlExtDAO();

$employee = new Employee();
$employeeDAO = new EmployeeMySqlDAO();
$employeeEX = new EmployeeMySqlExtDAO();
//Employeesubgroup
$employeeSubGroup = new Employeesubgroup();
$employeeSubGroupDAO = new EmployeesubgroupMySqlDAO();
$employeeSubGroupEX = new EmployeesubgroupMySqlExtDAO();
//Employeegroup
$employeeGroup = new Employeegroup();
$employeeGroupDAO = new EmployeegroupMySqlDAO();
$employeeGroupEX = new EmployeegroupMySqlExtDAO();

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


//check and use the condetion that suite this action
$sysdate = date('Y-m-d H:i:s');
if (isset($_GET['testdate']) && !empty($_GET['testdate'])) {
    $sysdate = $_GET['testdate'];
}
$day = date('Y-m-d', strtotime($sysdate));
$time = date("H:i:s", strtotime($sysdate));

if (empty($do) || $do == "add") {
    //Transaction
    $mytransactions = new Transaction();
    try {
        header('Access-Control-Allow-Origin: *');
        header('Content-Type: application/json');

        $empid = (int) filter_input(INPUT_GET, 'empid');
        //with this step make sure any employee exist and not deleted will be in table
        if ((int) $employeeCloseDayHistoryEX->dayAttendanceCount($day) == 0) {
            $employeeCloseDayHistoryEX->beginDayAttendance($day, $sysdate, 1);
        }

        //set random name for the image, used time() for uniqueness
        $filename = time() . '.jpg';
        $filepath = '../upload/employeeAttendance/';
        move_uploaded_file($_FILES['webcam']['tmp_name'], $filepath . $filename);
        $img = imagecreatefromjpeg($filepath . $filename);
        // (B) WRITE TEXT
        $white = imagecolorallocate($img, 255, 0, 255);
        $txt = $sysdate; //date('Y-m-d H:i:s'); //date('yy-m-d:h:m:s');
        $font = "arial.ttf";
        $xxxx = imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);
        // (C) OUTPUT IMAGE
        // header('Content-type: image/jpeg');
        // imagejpeg($img);
        // imagedestroy($img);
        // OR SAVE TO A FILE
        // THE LAST PARAMETER IS THE QUALITY FROM 0 to 100
        imagejpeg($img, $filepath . $filename, 100);
        // Clear Memory
        imagedestroy($img);



        $employeeAttendance->empid = $empid;
        $employeeAttendance->theImage = $filename;
        $employeeAttendance->userid = 1; //(int) $_SESSION['userid'];
        $employeeAttendance->sysdate = $sysdate; //date('Y-m-d H:i:s');
        $employeeAttendance->fingerid = '';
        $employeeAttendance->rfid = '';
        $employeeAttendance->accessType = 0;
        $employeeAttendance->syncToServer = 0;
        $id = $employeeAttendanceDAO->insert($employeeAttendance);




        ///////endDay
        $employee = $employeeDAO->load($empid);
        $employeesubgroupid = $employee->employeesubgroupid;
        $employeegroupid = $employee->employeegroupid;
        $row = $employeeCloseDayHistoryEX->getEmployeeHistoryByQueryString(" and employeeid=$empid and day='" . $day . "' and del = 0");
        if (count($row) == 0) { //employee is deleted or dont exist
        } else {

            //2- update dataof attendance or departure in employeeCloseDayHistory table
            $employeeCloseDayHistory = $row[0];
            if ($employeeCloseDayHistory->attendanceTime == "00:00:00") {
                $employeeCloseDayHistory->attendanceTime = $time;
            } else {
                $employeeCloseDayHistory->departureTime = $time;
            }
            $employeeCloseDayHistory->isAbsent = 0;
            $employeeCloseDayHistory->absentHasPermission = 0;
            $employeeCloseDayHistory->absentDiscount = 0;
            $employeeCloseDayHistory->userid = 1; // $_SESSION['userid'];
            $employeeCloseDayHistory->sysdate = $sysdate; //date('Y-m-d H:i:s');
            $employeeCloseDayHistory->del = 0;
            $employeeCloseDayHistoryDAO->update($employeeCloseDayHistory);
        }
        //affect employee with late
        //curlAddEmployeePersonal($empid, $day, $lateDiscount, 5);
        //2-affect Employeeclose subgroup,group,day status
        /* if ($employeesubgroupid > 0 && count($row) > 0) {
          $empCount_subGroup = $employeeEX->getEmployeeCount(' and employeesubgroupid=' . $employeesubgroupid);
          $closedEmpCount_subGroup = $employeeCloseDayHistoryEX->getClosedEmployeeCountForSubGroupInADay($day, $employeesubgroupid);
          if ($empCount_subGroup == $closedEmpCount_subGroup) {
          $Employeeclosedaysubgroupstatus->day = $day;
          $Employeeclosedaysubgroupstatus->employeesubgroupid = $employeesubgroupid;
          $Employeeclosedaysubgroupstatus->status = 1;
          $Employeeclosedaysubgroupstatus->userid = 1; //$_SESSION['userid'];
          $Employeeclosedaysubgroupstatus->sysdate = $sysdate;//date('Y-m-d H:i:s');
          $Employeeclosedaysubgroupstatus->conditions = 0;
          $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));
          print_r($noOfSubGroupsInaGroup);
          print_r($noOfSubGroupsClosedInaGroupForADay);
          if ($noOfSubGroupsInaGroup == $noOfSubGroupsClosedInaGroupForADay) {
          //mark as colsed
          $employeeCloseDayGroupStatus->day = $day;
          $employeeCloseDayGroupStatus->employeegroupid = $employeegroupid;
          $employeeCloseDayGroupStatus->status = 1;
          $employeeCloseDayGroupStatus->userid = 1; //$_SESSION['userid'];
          $employeeCloseDayGroupStatus->sysdate = $sysdate;//date('Y-m-d H:i:s');
          $employeeCloseDayGroupStatus->conditions = 0;
          $employeeCloseDayGroupStatusDAO->insert($employeeCloseDayGroupStatus);
          print_r('in there');
          }
          //4- affect day as closed if allgroups closed
          $noOfGroups = $employeeGroupEX->queryAllEXCount();
          $noOfGroupsClosedInADay = $employeeCloseDayGroupStatusEX->getNoOfGroupsClosedInADay($day);
          if ($noOfGroups == $noOfGroupsClosedInADay) {
          //mark as colsed
          $Employeeclosedaystatus->day = $day;
          $Employeeclosedaystatus->status = 1;
          $Employeeclosedaystatus->userid = 1; //$_SESSION['userid'];
          $Employeeclosedaystatus->sysdate = $sysdate;//date('Y-m-d H:i:s');
          $Employeeclosedaystatus->conditions = 0;
          $EmployeeclosedaystatusDAO->insert($Employeeclosedaystatus);
          }
          } */

        // send data
        if (count($row) == 0) { //employee is deleted or dont exist
            $send_data = array("ststus" => 2, "msg" => "employee does not exist or not allowed", "image" => $hosturl_f . "/upload/employeeAttendance/" . $filename);
        } else {
            $send_data = array("ststus" => 1, "msg" => "sucess", "image" => $hosturl_f . "/upload/employeeAttendance/" . $filename);
        }
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        // send data
        $send_data = array("ststus" => 0, "msg" => "error", "image" => '');
    }
    echo json_encode($send_data);
}
##another diff version of add used for access point like finger print , rfid
elseif ($do == "saveaccesslog") {
    //Transaction
    $mytransactions = new Transaction();
    try {
        header('Access-Control-Allow-Origin: *');
        header('Content-Type: application/json');

        $accessLogArr = json_decode($_POST['data_arr']);
        $successIds = '';
        foreach ($accessLogArr as $log) {
            $sysdate = $log->sysdate;
            if ($log->accessType == 0) { //finger
                $empid = (int) $employeeEX->getEmpIdWithFingerId($log->fingerid);
            } else { //rfid
                $empid = (int) $employeeEX->getEmpIdWithRFID($log->rfid);
            }
            if ($empid > 0) {
                $day = date('Y-m-d', strtotime($sysdate));
                $time = date("H:i:s", strtotime($sysdate));

                //with this step make sure any employee exist and not deleted will be in table
                if ((int) $employeeCloseDayHistoryEX->dayAttendanceCount($day) == 0) {
                    $employeeCloseDayHistoryEX->beginDayAttendance($day, $sysdate, 1);
                }



                //set random name for the image, used time() for uniqueness
                $filename = $log->theImage;
                if ($filename != "") {

                    $filepath = '../upload/employeeAttendance/';
                    if (file_exists($filepath . $filename)) {
                        chmod($filepath . $filename, 0777);
                        unlink($filepath . $filename);
                    }

                    $success = file_put_contents($filepath . $filename, base64_decode($log->theImage_base64));
                    $img = imagecreatefrompng($filepath . $filename);
                    // (B) WRITE TEXT
                    $white = imagecolorallocate($img, 255, 0, 255);
                    $txt = $sysdate; //date('Y-m-d H:i:s'); //date('yy-m-d:h:m:s');
                    $font = "arial.ttf";
                    $xxxx = imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);
                    // (C) OUTPUT IMAGE
                    // header('Content-type: image/jpeg');
                    // imagejpeg($img);
                    // imagedestroy($img);
                    // OR SAVE TO A FILE
                    // THE LAST PARAMETER IS THE QUALITY FROM 0 "normal" to 9 "compressed" default 9
                    imagepng($img, $filepath . $filename, 0);
                    // Clear Memory
                    imagedestroy($img);
                }


                $employeeAttendance->empid = $empid;
                $employeeAttendance->theImage = $filename;
                $employeeAttendance->userid = 1; //(int) $_SESSION['userid'];
                $employeeAttendance->sysdate = $sysdate; //date('Y-m-d H:i:s');
                $employeeAttendance->fingerid = $log->fingerid;
                $employeeAttendance->rfid = $log->rfid;
                $employeeAttendance->accessType = $log->accessType;
                $employeeAttendance->syncToServer = 1;
                $id = $employeeAttendanceDAO->insert($employeeAttendance);

                $successIds .= $log->id . ",";



                ///////endDay
                $employee = $employeeDAO->load($empid);
                $employeesubgroupid = $employee->employeesubgroupid;
                $employeegroupid = $employee->employeegroupid;
                $row = $employeeCloseDayHistoryEX->getEmployeeHistoryByQueryString(" and employeeid=$empid and day='" . $day . "' and del = 0");
                if (count($row) == 0) { //employee is deleted or dont exist
                } else {

                    //2- update dataof attendance or departure in employeeCloseDayHistory table
                    $employeeCloseDayHistory = $row[0];
                    if ($employeeCloseDayHistory->attendanceTime == "00:00:00") {
                        $employeeCloseDayHistory->attendanceTime = $time;
                    } else {
                        $employeeCloseDayHistory->departureTime = $time;
                    }
                    $employeeCloseDayHistory->isAbsent = 0;
                    $employeeCloseDayHistory->absentHasPermission = 0;
                    $employeeCloseDayHistory->absentDiscount = 0;
                    $employeeCloseDayHistory->userid = 1; // $_SESSION['userid'];
                    $employeeCloseDayHistory->sysdate = $sysdate; //date('Y-m-d H:i:s');
                    $employeeCloseDayHistory->del = 0;
                    $employeeCloseDayHistoryDAO->update($employeeCloseDayHistory);
                }
            }
        }

        $sucessIds = rtrim($sucessIds, ',');
        $send_data = $successIds;
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        // send data
        $send_data = -1;
    }
    echo $send_data;
} elseif ($do == "attendanceReport") {
    $empid = (int) filter_input(INPUT_POST, 'empid');
    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');

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

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

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

    $queryString = '';

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

    if ($empid > 0) {
        $queryString .= " and empid = $empid ";
    }
    if ($from != '') {
        $queryString .= " and date(employeeattendance.sysdate) >= '" . $from . "' ";
    }
    if ($to != '') {
        $queryString .= " and date(employeeattendance.sysdate) <= '" . $to . "' ";
    }

    if ($queryString == '') {
        $queryString = " and date(employeeattendance.sysdate) = '" . date('Y-m-d') . "' ";
    }

    $employeeAttendanceData = $employeeAttendanceEX->queryByQueryString($queryString);

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

    $smarty->display("employeeAttendanceView/show.html");
}

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