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

//here the db files that include in the file
include("../public/include_dao.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/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');


$do = $_GET['do'];

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

$smarty->display("header.html");


//create object  from employee
$employeeDAO = new EmployeeMySqlDAO();
$employee = new Employee();
$employeeEX = new EmployeeMySqlExtDAO();

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



//create object from user
//dispaly  add form
if (empty($do)) {
    include_once("../public/authentication.php");

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

    $allemployee = $employeeEX->queryAllSimple($queryStringAll);
    $smarty->assign('allemployee', $allemployee);

    $empid = filter_input(INPUT_POST, "chooseEmp");
    $queryString = "";
    if (!empty($empid)) {
        $queryString = " and employeeId =" . $empid;
    }

    if ($_SESSION['branchId'] > 0)
        $queryString = ' AND  branchid = ' . $_SESSION['branchId'];
    $allData = $employeeEX->queryAllSimple($queryString);
    foreach ($allData as $value) {
        if (!empty($value->employeeBOD) && $value->employeeBOD != "0000-00-00") {
            $value->employeeBOD = floor((time() - strtotime($value->employeeBOD)) / (60 * 60 * 24 * 365));
        } else {
            $value->employeeBOD = "";
        }
    }
    $smarty->assign('allData', $allData);
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("employeereportview/show.html"); //the template page
} elseif ($do == "totals") {
    $employeeGroup = R::getAll('SELECT * FROM employeegroup WHERE del =0');
    $smarty->assign('employeeGroup', $employeeGroup);

    $allbranchdata = R::getAll('SELECT * FROM branch');
    $smarty->assign("allbranchdata", $allbranchdata);

    $month = filter_input(INPUT_POST, 'month');
    $empGroup = filter_input(INPUT_POST, 'empGroup');
    $branchId = filter_input(INPUT_POST, 'branchId');
    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');

    $sql = '';
    if ($month) {
        $sql .= ' AND MONTH(employeepersonneldate) = ' . date('m', strtotime($month)) . ' AND Year(employeepersonneldate) = ' . date('Y', strtotime($month));
    } else {
        $month = date('Y-m');
        $sql .= ' AND MONTH(employeepersonneldate) = MONTH(CURDATE()) AND Year(employeepersonneldate) = Year(CURDATE()) ';
    }

    if ($from && $to) {
        $month = '';
        $sql .= ' AND employeepersonneldate >= "' . $from . '" AND employeepersonneldate <= "' . $to . '"';
    }

    $smarty->assign('month', $month);
    $smarty->assign('empGroup', $empGroup);
    $smarty->assign('branchId', $branchId);
    $smarty->assign('from', $from);
    $smarty->assign('to', $to);


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

    if ($empGroup)
        $sql .= ' AND employee.employeegroupid = ' . $empGroup;

    $allEmployeePersonals = R::getAll('SELECT employee.employeeName,employeeSalary,employee.employeeId, SUM(employeepersonnelvalue) as total,COUNT(employeepersonnelid) AS typeCounter, employeepersonneltype
                        FROM employeepersonnel 
                        JOIN employee ON employee.employeeId = employeepersonnel.employeeid
                        WHERE employee.conditions = 0 AND employeepersonnel.conditions = 0
                        ' . $sql . '
                        GROUP BY employeepersonneltype, employeepersonnel.employeeid ');

    $empArr = [];
    foreach ($allEmployeePersonals as $emp) {
        $delay = $emp['total']; // تأخير
        $reward = $bonus = $dis = $withdraw = $borrow = $absence = $repay = $permission = $delay = $leave = '0';
        $rewardCounter = $bonusCounter = $disCounter = $withdrawCounter = $borrowCounter = $absenceCounter = $repayCounter = $permissionCounter = $delayCounter = $leaveCounter = '0';

        if ($emp['employeepersonneltype'] == 9) {
            $absence = $emp['total']; // غياب
            $absenceCounter = $emp['typeCounter'];
        } elseif ($emp['employeepersonneltype'] == 5) {
            $delay = $emp['total']; // تأخير
            $delayCounter = $emp['typeCounter'];
        } elseif ($emp['employeepersonneltype'] == 11) {
            $permission = $emp['total']; // استئذان
            $permissionCounter = $emp['typeCounter'];
        } elseif ($emp['employeepersonneltype'] == 2) {
            $dis = $emp['total']; // خصم
            $disCounter = $emp['typeCounter'];
        } elseif ($emp['employeepersonneltype'] == 3) {
            $withdraw = $emp['total']; // سحب
            $withdrawCounter = $emp['typeCounter'];
        } elseif ($emp['employeepersonneltype'] == 4) {
            $borrow = $emp['total']; // سلفة
            $borrowCounter = $emp['typeCounter'];
        }
        elseif ($emp['employeepersonneltype'] == 14) {
            $leave = $emp['total']; // اانصراف
            $leaveCounter = $emp['typeCounter'];
        }elseif( $emp['employeepersonneltype'] == 1) {
            $reward = $emp['total']; // مكافأة
            $rewardCounter = $emp['typeCounter'];
        } elseif( $emp['employeepersonneltype'] == 13) {
            $bonus = $emp['total']; // إضافي
            $bonusCounter = $emp['typeCounter'];
        } 
        $lastSalary = R::getRow('select salaryreportnet,salarymonthdate from salaryreport where employeeid = ' . $emp['employeeId'] . ' order by salaryreportid desc');
        if (array_key_exists($emp['employeeId'], $empArr)) {
            $empArr[$emp['employeeId']]['dis'] += $dis;
            $empArr[$emp['employeeId']]['disCounter'] += $disCounter;
            $empArr[$emp['employeeId']]['withdraw'] += $withdraw;
            $empArr[$emp['employeeId']]['withdrawCounter'] += $withdrawCounter;
            $empArr[$emp['employeeId']]['borrow'] += $borrow;
            $empArr[$emp['employeeId']]['borrowCounter'] += $borrowCounter;
            $empArr[$emp['employeeId']]['absence'] += $absence;
            $empArr[$emp['employeeId']]['absenceCounter'] += $absenceCounter;
            $empArr[$emp['employeeId']]['permission'] += $permission;
            $empArr[$emp['employeeId']]['permissionCounter'] += $permissionCounter;
            $empArr[$emp['employeeId']]['delay'] += $delay;
            $empArr[$emp['employeeId']]['delayCounter'] += $delayCounter;
            $empArr[$emp['employeeId']]['leave'] += $leave;
            $empArr[$emp['employeeId']]['leaveCounter'] += $leaveCounter;
            $empArr[$emp['employeeId']]['reward'] += $reward;
            $empArr[$emp['employeeId']]['rewardCounter'] += $rewardCounter;
            $empArr[$emp['employeeId']]['bonus'] += $bonus;
            $empArr[$emp['employeeId']]['bonusCounter'] += $bonusCounter;
        } else {
            $empArr[$emp['employeeId']] = [
                'name' => $emp['employeeName'],
                'dis' => $dis,
                'disCounter' => $disCounter,
                'withdraw' => $withdraw,
                'withdrawCounter' => $withdrawCounter,
                'borrow' => $borrow,
                'borrowCounter' => $borrowCounter,
                'absence' => $absence,
                'absenceCounter' => $absenceCounter,
                'permission' => $permission,
                'permissionCounter' => $permissionCounter,
                'delay' => $delay,
                'delayCounter' => $delayCounter,
                'leave' => $leave,
                'leaveCounter' => $leaveCounter,
                'bonus' => $bonus,
                'bonusCounter' => $bonusCounter,
                'reward' => $reward,
                'rewardCounter' => $rewardCounter,
                'salary' => $emp['employeeSalary'],
                'lastSalary' => $lastSalary['salaryreportnet'],
                'lastSalaryDate' => $lastSalary['salarymonthdate']
            ];
        }
    }

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

    $smarty->display("employeereportview/totals.html"); //the template page

}
//success
elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}
$smarty->assign("customValidation", 1);
$smarty->display("footer.html");
