<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$month = "";
$year = "";
$employee_id = "";
$shitEmployee = "";
$LeavesArray = "";
$absentCount = "";
$totalHoliday = 0;
$holidayCount = 0;
$totalPayamount = 0;
$totalPayamounts = 0;
$advanceSalary = 0;
$loanPerMonth = 0;
$lateCount = 0;
$advanceSalary = 0;
$loanPerMonth = 0;
$timeTotal = array();
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("Y-m-d", strtotime($datefrom));
$dateto = date("Y-m-d", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        #borderless-table tr, #borderless-table th, #borderless-table td {
            font-size: 12px !important;
            text-align: center;
            padding: 15px 3px !important;
        }

        li.optgroup:nth-child(3n) ~ li span:not(.optgroup) {
            color: #999 !important;
        }
    </style>
</head>
<body>
<?php
if($paid == 1){
	$data['employee_id'] = $employee_id;
	$data['amount'] = $amount;
	$data['advance'] = 0;
	$data['description'] = "Automated from Monthly Attendance - ".$month;
	$data['date_time'] = 'NOW()';
	$data['create_date'] = 'NOW()';
	
	$q = SalarySetup::AddSalarySetup($data);
	?>
	<script>
	$(document).ready(function () {
		window.location.href = 'attendance.php?month=<?=$month?>&view=&year=<?=$year?>&employee_id=<?=$employee_id?>
	});
	</script>
	<?php
}
?>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Attendance Report</h3>
            </div>
            <?php if (isset($_GET['sucess'])) { ?>
                <div class="alert alert-success  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>*</strong> Successfully Updated.
                </div>
            <?php } ?>
            <?php if (isset($_GET['error'])) { ?>
                <div class="alert alert-error  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    Error Ocurred. Try Again Later.
                </div>
            <?php } ?>
            <?php if (isset($_GET['availed'])) { ?>
                <div class="alert alert-error  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    Your leaves limit is over. Contact to admin
                </div>
            <?php } ?>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr style="border-top: 1px solid #ddd;">
                        <td class="col s6">Month<br>
                            <select class="form-control" name="month" id="month">
                                <?php
                                if ($month) {
                                    $monthcount = $month;
                                } else {
                                    $monthcount = date('F');
                                }
                                for ($m = 1; $m <= 12; ++$m) {
                                    echo '<option value="' . date('F', mktime(0, 0, 0, $m, 1)) . '"';
                                    if (date('F', mktime(0, 0, 0, $m, 1)) == trim($monthcount)) {
                                        echo ' selected';
                                        $monthCheck = $m;
                                    }
                                    echo '>' . date('F', mktime(0, 0, 0, $m, 1)) . '</option>';
                                }
                                ?>
                            </select>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col s6">Year<br>
                            <select class="form-control" name="year" id="year">
                                <?php
                                if ($year) {
                                    $currentYear = $year;
                                } else {
                                    $currentYear = date('Y');
                                }
                                for ($i = 1; $i <= 10; $i++) {
                                    $yearcount = 2016 + $i;
                                    echo '<option value="' . $yearcount . '"';
                                    if ($currentYear == $yearcount) {
                                        echo ' selected';
                                    }
                                    echo '>' . $yearcount . '</option>';
                                }
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s12">Employee Name<br>
                            <?php
                            $icon = "";
                            $filterGetCust = " ORDER BY status, name";
                            $qryEmployee = EmployeeSetup::GetEmployeeSetupList($filterGetCust);
                            if ($qryEmployee) {
                                echo '<select id="employee_id" name="employee_id" class="form-control">';
                                echo '<option value="">All</option>';
                                $activeGroup = 0;
                                $inactiveGroup = 0;
                                foreach ($qryEmployee as $qery) {
                                    if ($activeGroup == 0 && $qery->status == 'active') {
                                        $activeGroup = 1;
                                        $icon = "../../images/active.png";
                                        echo '<optgroup label="' . ucfirst($qery->status) . '">';
                                    } else if ($inactiveGroup == 0 && $qery->status == 'inactive') {
                                        $inactiveGroup = 1;
                                        $icon = "../../images/disable.png";
                                        echo '</optgroup><optgroup label="' . ucfirst($qery->status) . '">';
                                    }
                                    echo '<option data-icon="' . $icon . '" value=' . $qery->id;
                                    if ($qery->id == $employee_id) {
                                        echo ' selected ';
                                    }
                                    echo '>' . $qery->name . '</option>';
                                }
                                echo '</optgroup></select>';
                                echo '</select>';
                            }
                            ?>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="2" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button
                                    onclick="exportTableToCSV('payment-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Export CSV
                                </button>
                            <?php } ?>
                            <?php if (!empty($_GET['employee_id'])) { ?>
                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>

                        </td>
                    </tr>
                </table>
            </form>
            <table class="table">
                <tr>
                    <td colspan="2" class="col-lg-4">

                        <a style="margin-left:30px; display: block; cursor:pointer;font-size: 10px;padding: 1px;"
                           data-toggle="modal"
                           href="#myModalPaid"
                           class="modal-trigger"
                           title="Download">
                            <button
                                class="right btn waves-effect waves-light"
                                style=" margin-left: 15px;">
                                Download
                            </button>
                        </a>
                        <a style="margin-left:30px; display: block; cursor:pointer;font-size: 10px;padding: 1px;"
                           data-toggle="modal"
                           href="#myModal"
                           class="modal-trigger"
                           title="Import">
                            <button
                                class="right btn waves-effect waves-light"
                                style=" margin-left: 15px;">
                                Import
                            </button>
                        </a>

                        <!-- Modal -->
                        <div id="myModalPaid" class="modal">
                            <form action="http://192.168.1.200/form/Download" method="post" name="mainform">
                                <!-- Modal content-->
                                <div class="modal-content">

                                    <h4 class="modal-title">Download Data From Device</h4>

                                    <p>Please select the period to import data</p>
                                                                <span class="col-lg-4">Date From<br>
                                                                    <input type="text" name="sdate" id="datepicker"
                                                                           placeholder="Date From"
                                                                           value="<?= $datefrom ?>"
                                                                           class="form-control"/>
                                                                </span>
                                                                <span class="col-lg-4"> Date To<br>
                                                                    <input type="text" name="edate" id="datepicker1"
                                                                           placeholder="Date To"
                                                                           value="<?= $dateto ?>" class="form-control"/>
                                                                </span>
                                    <?php
                                    $maxEmp = EmployeeSetup::GetMaxMachineIdFromEmployee();
                                    for ($a = 1; $a <= $maxEmp->machineid; $a++) {
                                        echo '<input type="hidden" checked="" name="uid" value="' . $a . '">';
                                    }
                                    ?>
                                </div>
                                <div class="modal-footer">
                                    <input type="submit" class="btn waves-effect waves-light" name="submit"
                                           id="submit" value="Download"/>
                                </div>
                            </form>
                        </div>

                        <!-- Modal -->
                        <div id="myModal" class="modal">
                            <form action="test.php" method="post" name="testform"
                                  enctype="multipart/form-data">
                                <!-- Modal content-->
                                <div class="modal-content">
                                    <h4 class="modal-title">Import Data</h4>

                                    <p>Please select file to import</p>
                                                                <span class="col-lg-4">Import File<br>
                                                                    <input class="form-control" type="file"
                                                                           name="importfile"
                                                                           id="importfile"/>
                                                                </span>
                                    <br><br><br>
                                </div>

                                <div class="modal-footer">
                                    <input type="submit" class="btn waves-effect waves-light" name="submit"
                                           id="submit" value="Download"/>
                                </div>
                            </form>
                        </div>
                    </td>
                </tr>
            </table>


            <hr><?php
            if (isset($_GET['view']) && empty($employee_id)) {
                ?>
                <div id="borderless-table">
                    <table style="text-align:center;" class="display table bordered striped">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th style="text-align: left;">Employee</th>
                            <?php
                            if ($year) {
                                $year = $year;
                            } else {
                                $year = date('Y');
                            }
                            for ($d = 1; $d <= 31; $d++) {
                                $time = mktime(12, 0, 0, $monthCheck, $d, $year);
                                if (date('m', $time) == $monthCheck)
                                    echo '<th>' . date('d', $time) . '</th>';
                            }
                            ?>
                            <th>Late</th>
                            <th>Absent</th>
                            <th>AL/CL</th>
                            <th>Holiday</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $getYearMonth = date('Y-m-00', strtotime($year . '-' . $monthCheck . '-01'));
                        $holidayFilter = ' WHERE STR_TO_DATE(ac_date, "%Y-%m") = "' . $getYearMonth . '"';
                        $holidays = HolidaySetup::GetHolidaySetupList($holidayFilter);

                        $filterEmployee = " WHERE status = 'active'";
                        $qry = EmployeeSetup::GetEmployeeSetupList($filterEmployee);
                        if ($qry) {
                            $numbering = 0;
                            $shift = "";
                            foreach ($qry AS $qery) {
                                $numbering++;
                                $lateCount = 0;
                                $absentCount = 0;
                                $holidayCount = 0;
                                $leavesCount = 0;
                                echo '<tr>';
                                echo '<td>' . $numbering . '</td>';
                                echo '<td style="text-align: left; padding: 2px 5px;">' . $qery->name . '</td>';
                                for ($d = 1; $d <= 31; $d++) {
                                    $getDate = date('Y-m-d', strtotime($year . '-' . $monthCheck . '-' . $d));

                                    $getDateNext = date('Y-m-d', strtotime('+1 day', strtotime($getDate)));


                                    $filterAtt = ' AND (STR_TO_DATE(time_in, "%Y-%m-%d") = "' . $getDate . '" )';
                                    $present = '';
                                    $color = '#000';
                                    $attendanceEmployee = '';
                                    $attendanceEmployee = Attendance::GetAttendanceByEmployeeId($qery->id, $filterAtt);
                                    if ($attendanceEmployee) {
                                        $shift = $attendanceEmployee[0]->shift;
                                    }
                                    $background = '';
                                    $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qery->category_id);
                                    if ((isset($attendanceEmployee[0]->shift) && $attendanceEmployee[0]->shift == 'day') || $shift == 'day') {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == $holidaysRow->ac_date || $getDateNext == $holidaysRow->ac_date) {
                                                    if($getDateNext != $holidaysRow->ac_date && $categ->shift_cat == 'a') {
                                                        $background = '#FFA500';
                                                        $holidayCount++;
                                                    }else if($getDateNext == $holidaysRow->ac_date && $categ->shift_cat == 'b') {
                                                        $background = '#FFA500';
                                                        $holidayCount++;
                                                    }
                                                }
                                            }
                                        }
                                    } else if ((isset($attendanceEmployee[0]->shift) && $attendanceEmployee[0]->shift == 'night') || $shift == 'night') {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == date("Y-m-d", strtotime('-1 day', strtotime($holidaysRow->ac_date)))) {
                                                    $background = '#FFA500';
                                                    $holidayCount++;
                                                }
                                            }
                                        }
                                    } else {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == $holidaysRow->ac_date) {
                                                    $background = '#FFA500';
                                                    $holidayCount++;
                                                }
                                            }
                                        }
                                    }
//                                    if($qery->id == "6" && $d == 10){
//                                        print_r($attendanceEmployee);
//                                    }
                                    //For Check Annual Leave
                                    $LeaveFilter = ' WHERE employee_id = "' . $qery->id . '" AND STR_TO_DATE(leave_date, "%Y-%m-%d") = "' . $getDate . '"';
                                    $Leaves = LeaveSetup::GetLeaveSetupList($LeaveFilter);
                                    $LeavesAvailed = '';
                                    if ($Leaves) {
                                        $LeavesAvailed = $Leaves[0]->leave_date;
                                    }
                                    if ($getDate == $LeavesAvailed) {
                                        $present = 'LE';
                                        $background = '#9F9';
                                        $leavesCount++;
                                    } else {
                                        if (!empty($attendanceEmployee[0]->time_in) && $attendanceEmployee[0]->time_in != '0000-00-00 00:00:00') {
                                            //echo date('Y-m-d', strtotime($attendanceEmployee[0]->time_in));
                                            //echo date('Y-m-d').'<br>';
                                            if ($attendanceEmployee[0]->shift == 'day') {
                                                if (!empty($attendanceEmployee[0]->late_grace_time)) {
                                                    $startTime = date("Y-m-d", strtotime('-' . $attendanceEmployee[0]->late_grace_time . ' min', strtotime($attendanceEmployee[0]->time_in)));
                                                } else {
                                                    $startTime = date('Y-m-d', strtotime($attendanceEmployee[0]->time_in));
                                                }
                                                if ($startTime <= date('Y-m-d')) {
                                                    if ($attendanceEmployee) {
                                                        //echo date('H:i:s', strtotime($attendanceEmployee[0]->time_in)) . '<br>';

                                                        if (date('H:i:s', strtotime($startTime)) <= $attendanceEmployee[0]->shift_start_time) {
                                                            $present = 'P';
                                                            $color = '#00FF00';
                                                        } else {
                                                            $present = 'L';
                                                            $color = '#996600';
                                                            $lateCount++;
                                                        }
                                                    } else {
                                                        if (!empty($background)) {
                                                            $present = 'H';
                                                        } else {
                                                            $color = '#FF0000';
                                                            $present = 'A';
                                                            $absentCount++;
                                                        }
                                                    }
                                                }
                                            } else if ($attendanceEmployee[0]->shift == 'night') {
                                                if (date("Y-m-d H:i:s", strtotime($attendanceEmployee[0]->time_in)) > date('Y-m-d 15:00:00') || (empty($attendanceEmployee[1]->time_in) && date("Y-m-d H:i:s", strtotime($attendanceEmployee[0]->time_in)) < date('Y-m-d 15:00:00'))) {
                                                    $param = 0;
                                                } else {
                                                    $param = 1;
                                                }
//                                                            if(date("Y-m-d H:i:s", strtotime($attendanceEmployee[1]->time_in)) > date('Y-m-d 19:00:00')){
//                                                                $param = 1;
//                                                            }else{
//
//                                                            }
//                                                            if($attendanceEmployee[0]->employee_id == '6' ) {
//                                                                echo '0'.$attendanceEmployee[0]->time_in."<br>";
//                                                                echo '1'.$attendanceEmployee[1]->time_in."<br><br><br>";
//                                                            }
//                                                        if($attendanceEmployee[0]->employee_id == '10') {
//                                                            $itrCheck = 0;
//                                                            for ($itr = 0; $itr <= count($attendanceEmployee); $itr++) {
//                                                                if (date('Y-m-d H:i:s', strtotime($attendanceEmployee[$itr]->time_in)) > date('Y-m-d 17:00:00', strtotime($attendanceEmployee[$itr]->time_in))) {
//                                                                    $param = $itrCheck;
//                                                                    $itrCheck++;
//                                                                } else {
//                                                                    echo date('Y-m-d H:i:s', strtotime($attendanceEmployee[$itr]->time_in));
//                                                                    echo date('Y-m-d 17:00:00', strtotime($attendanceEmployee[$itr]->time_in));
//                                                                    echo 'No Record Found <br>';
//                                                                }
//                                                            }
//                                                        }

                                                if (!empty($attendanceEmployee[$param]->late_grace_time)) {
                                                    $startTime = date("Y-m-d H:i:s", strtotime('-' . $attendanceEmployee[$param]->late_grace_time . ' min', strtotime($attendanceEmployee[$param]->time_in)));
                                                } else {
                                                    $startTime = date('Y-m-d H:i:s', strtotime($attendanceEmployee[$param]->time_in));
                                                }
//                                                            if($attendanceEmployee[0]->employee_id == '6') {
//                                                                echo $startTime." ".$param."<br>";
//                                                            }
                                                if ($startTime <= date('Y-m-d 19:00:00')) {
                                                    if ($attendanceEmployee) {
//                                                                if($attendanceEmployee[0]->employee_id == '10'){
//                                                                    echo '<pre>';
//                                                                    print_r($attendanceEmployee);
//                                                                    echo '</pre>';
////                                                                    echo $startTime.' = ';
////                                                                    echo date('H:i:s', strtotime($attendanceEmployee[1]->time_in)) . ' - ';
////                                                                    echo $attendanceEmployee[1]->shift_start_time."<br>";
//                                                                }
                                                        if (date('H:i:s', strtotime($startTime)) <= $attendanceEmployee[$param]->shift_start_time) {
                                                            $present = 'P';
                                                            $color = '#00FF00';
                                                        } else if (!empty($background)) {
                                                            $present = 'H';
                                                        } else {
                                                            $present = 'L';
                                                            $color = '#996600';
                                                            $lateCount++;
                                                        }
                                                    } else {
                                                        if (!empty($background)) {
                                                            $present = 'H';
                                                        } else {
                                                            $color = '#FF0000';
                                                            $present = 'A';
                                                            $absentCount++;
                                                        }
                                                    }
                                                }
                                            }
                                        } else if ($getDate <= date('Y-m-d')) {
//                                            if($qery->id == "6" && $d == 10){
//                                                echo "Fahads";
//                                                echo $shift;
//                                            }
                                            if (!empty($background)) {
                                                $present = 'H';
                                            } else {
                                                $present = 'A';
                                                $color = '#FF0000';
                                                $absentCount++;
                                            }
                                        } else {
                                            if (!empty($background)) {
                                                $present = 'H';
                                            } else {
                                                $present = '-';
                                            }
                                        }
                                    }

                                    $time = mktime(12, 0, 0, $monthCheck, $d, $year);
                                    if (!empty($background)) {
                                        $present = "H";
                                        $color = '#000';
                                    }
                                    if (date('m', $time) == $monthCheck) {
                                        echo '<td style="background-color:' . $background . '; font-weight:bold; color:' . $color . '; " >' . $present . '</td>';
                                        //echo '<td>' . date('d', $time) . 'd' . $present . '</td>';
                                    }
                                }
                                echo '<td>' . $lateCount . '</td>';
                                echo '<td>' . $absentCount . '</td>';
                                echo '<td>' . $leavesCount . '</td>';
                                echo '<td>' . $holidayCount . '</td>';
                                echo '</tr>';
                            }
                        }
                        ?>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th style="text-align: left;">Employee</th>
                            <?php
                            if ($year) {
                                $year = $year;
                            } else {
                                $year = date('Y');
                            }
                            for ($d = 1; $d <= 31; $d++) {
                                $time = mktime(12, 0, 0, $monthCheck, $d, $year);
                                if (date('m', $time) == $monthCheck)
                                    echo '<th>' . date('D', $time) . '</th>';
                            }
                            ?>
                            <th>Late</th>
                            <th>Absent</th>
                            <th>AL/CL</th>
                            <th>Holiday</th>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <?php

            } else if (isset($_GET['view']) && !empty($employee_id)) {
                $by_pass = 0;
                $sandwich = 0;

                $getYearMonthLast = date('Y-m-d', strtotime($year . '-' . $monthCheck . '-01'));
                if ($monthCheck == 12) {
                    $getYearMonthPlus = date('Y-m-d', strtotime(($year + 1) . '-01-01'));
                } else {
                    $getYearMonthPlus = date('Y-m-d', strtotime($year . '-' . ($monthCheck + 1) . '-01'));
                }

                $getYearMonth = date('Y-m-00', strtotime($year . '-' . $monthCheck . '-01'));

                //For Holidays
                $holidays = '';
                $holidayFilter = ' WHERE STR_TO_DATE(ac_date, "%Y-%m-%d") >= "' . $getYearMonthLast . '" AND STR_TO_DATE(ac_date, "%Y-%m-%d") <= "' . $getYearMonthPlus . '"';
                $holidays = HolidaySetup::GetHolidaySetupList($holidayFilter);

                //For Employee Detail
                $qry = EmployeeSetup::GetEmployeeSetupById($employee_id);
                $salary = $qry->salary;
                $cat = EmployeeCategorySetup::GetEmployeeCategorySetupById($qry->category_id);
                if (isset($cat) && $cat->by_pass == 1) {
                    $by_pass = 1;
                }

                //For Check Advance Salary
                $AdvSalaryFilter = ' WHERE employee_id = "' . $employee_id . '" AND advance = 1 AND STR_TO_DATE(date_time, "%Y-%m") = "' . $getYearMonth . '"';
                $advSalary = SalarySetup::GetSalarySetupList($AdvSalaryFilter);
                if ($advSalary) {
                    foreach ($advSalary AS $advSalaryRow) {
                        $advanceSalary += $advSalaryRow->amount;
                    }
                }

                //For Check Loan
                $LoanSalaryFilter = ' WHERE employee_id = "' . $employee_id . '" AND status = "active"';
                $loanSalary = LoanSetup::GetLoanList($LoanSalaryFilter);
                if ($loanSalary) {
                    $currentDate = date('Y-m', strtotime($year . '-' . $monthCheck));
                    foreach ($loanSalary AS $loanSalaryRow) {
                        $startDate = $loanSalaryRow->start_date;
                        $endDate = date("Y-m", strtotime('+' . $loanSalaryRow->installment . ' month', strtotime($loanSalaryRow->start_date)));
                        if ($currentDate >= $startDate && $currentDate <= $endDate) {
                            $loanPerMonth = $loanSalaryRow->amount / $loanSalaryRow->installment;
                        }
                    }
                }

                //For Check Annual Leave
                $LeaveFilter = ' WHERE employee_id = "' . $employee_id . '" AND STR_TO_DATE(leave_date, "%Y") = "' . $year . '-00-00"';
                $Leaves = LeaveSetup::GetLeaveSetupList($LeaveFilter);
                if ($Leaves) {
                    foreach ($Leaves AS $LeavesRow) {
                        $LeavesArray[] = $LeavesRow->leave_date;
                    }
                }
                ?>
                <div id="floatThead" class="section">
                    <h3 style="text-align: center;"><?= $qry->name ?></h3>
                    <table style="text-align:center;" class="striped demo1 bordered">
                        <?php
                        if ($qry) {
                            $countDays = 0;
                            for ($d = 1; $d <= 31; $d++) {
                                $getDate = date('Y-m-d', strtotime($year . '-' . $monthCheck . '-' . $d));
                                $time = mktime(12, 0, 0, $monthCheck, $d, $year);
                                if (date('m', $time) == $monthCheck) {
                                    if ($holidays) {
                                        foreach ($holidays AS $holidaysRow) {
                                            if ($getDate == $holidaysRow->ac_date) {
                                                $totalHoliday++;
                                            }
                                        }
                                    }
                                    $countDays++;
                                }
                            }
                            //$countDays -= $totalHoliday;
                            $salaryPerUnit = ($qry->salary / $countDays) / 9;
                            for ($d = 1; $d <= 31; $d++) {
                                $time = mktime(12, 0, 0, $monthCheck, $d, $year);
                                if (date('m', $time) == $monthCheck) {
                                    $getDate = date('Y-m-d', strtotime($year . '-' . $monthCheck . '-' . $d));
                                    $getDateNight = date('Y-m-d 19:00:00', strtotime($year . '-' . $monthCheck . '-' . $d));
                                    $getDateNightPlus = date('Y-m-d 18:59:59', strtotime('+1 day', strtotime($year . '-' . $monthCheck . '-' . $d)));
                                    $filterAttDay = ' AND STR_TO_DATE(time_in, "%Y-%m-%d") = "' . $getDate . '" AND shift = "day" ORDER BY time_in ';
                                    $filterAttNight = ' AND STR_TO_DATE(time_in, "%Y-%m-%d %H:%i:%s") >= "' . $getDateNight . '" AND STR_TO_DATE(time_in, "%Y-%m-%d %H:%i:%s") <= "' . $getDateNightPlus . '" AND shift = "night"  ORDER BY time_in ';
                                    $attendanceDay = Attendance::GetAttendanceByEmployeeId($qry->id, $filterAttDay);
                                    $attendanceNight = Attendance::GetAttendanceByEmployeeId($qry->id, $filterAttNight);
                                    if (empty($attendanceDay) && empty($attendanceNight)) {
                                        $filterInd = ' AND STR_TO_DATE(time_in, "%Y-%m-%d") >= "' . $getDate . '" AND STR_TO_DATE(time_in, "%Y-%m-%d") <= "' . $getDate . '" AND shift = "night"  ORDER BY time_in ';
                                        $attendancew = Attendance::GetAttendanceByEmployeeId($qry->id, $filterInd);
                                        if ($attendancew) {
                                            $shitEmployee = $attendancew[0]->shift;
                                            //echo $shitEmployee;
                                            //print_r($attendancew);
                                            //exit;
                                        }
                                    }

                                    if ($d == 1) {
                                        echo '<thead><tr style="border: 1px solid #666;">
                                                        <th style="width: 10px;">Days</th>
                                                        <th>Work Hours</th>
                                                        <th>Amount / Day</th>
                                                        <th>Attendance</th>
                                                        <th>AL/CL</th>
                                                    </tr></thead><tbody>';
                                    }

                                    $getDate = date('Y-m-d', strtotime($year . '-' . $monthCheck . '-' . $d));
                                    $getDateNext = date('Y-m-d', strtotime('+1 day', strtotime($getDate)));
                                    $background = '';

                                    if (!empty($attendanceDay)) {
                                        $shitEmployee = 'day';
                                    } else if (!empty($attendanceNight)) {
                                        $shitEmployee = 'night';
                                    }

                                    $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qry->category_id);

                                    if ($shitEmployee == 'day') {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == $holidaysRow->ac_date || $getDateNext == $holidaysRow->ac_date) {
                                                    if($getDateNext != $holidaysRow->ac_date && $categ->shift_cat == 'a') {
                                                        $holidaysac[] = $holidaysRow->ac_date;
                                                        $background = '#FFA500';
                                                        $holidayCount++;
                                                        $amountPerDay = 9 * $salaryPerUnit;
                                                    }else if($getDateNext == $holidaysRow->ac_date && $categ->shift_cat == 'b') {
                                                        $holidaysac[] = $holidaysRow->ac_date;
                                                        $background = '#FFA500';
                                                        $holidayCount++;
                                                        $amountPerDay = 9 * $salaryPerUnit;
                                                    }
                                                }
                                            }
                                        }
                                    } else if ($shitEmployee == 'night') {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == date("Y-m-d", strtotime('-1 day', strtotime($holidaysRow->ac_date)))) {
                                                    $holidaysac[] = $holidaysRow->ac_date;
                                                    $background = '#FFA500';
                                                    $holidayCount++;
                                                    $amountPerDay = 9 * $salaryPerUnit;
                                                }
                                            }
                                        }
                                    } else {
                                        if ($holidays) {
                                            foreach ($holidays AS $holidaysRow) {
                                                if ($getDate == $holidaysRow->ac_date) {
                                                    $holidaysac[] = $holidaysRow->ac_date;
                                                    $background = '#FFA500';
                                                    $holidayCount++;
                                                    $amountPerDay = 9 * $salaryPerUnit;
                                                }
                                            }
                                        }
                                    }
                                    if ($d == 6) {
                                        //print_r($attendanceDay);
                                        //echo 'asdasd';
                                        //print_r($attendanceNight);
                                        //echo 'asdasd';
                                        echo $background;
                                        //print_r($holidays);
                                        //print_r($LeavesArray);
                                    }


                                    $present = '';
                                    if ($attendanceDay || $attendanceNight) {
                                        if (!empty($attendanceDay)) {
                                            $count = 0;
                                            $counter = 0;
                                            $enddatetimes = 0;
                                            foreach ($attendanceDay AS $attendanceRow) {
                                                if ($attendanceRow->shift == 'day') {
                                                    $counter++;
                                                    if ($counter % 2 == 0) {
                                                        $timeEnd = '';
                                                        $timeEnd = $attendanceRow->time_in;

                                                        $diff = abs(strtotime($timeEnd) - strtotime($timeStart));

                                                        $totalworkminutes = number_format((($diff % 86400) / 3600), 2);
                                                        $amountPerDay = $totalworkminutes * $salaryPerUnit;
                                                        $totalPayamount += $amountPerDay;

                                                        $years = floor($diff / (365 * 60 * 60 * 24));
                                                        $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                                                        $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));

                                                        $hours = intval(($diff % 86400) / 3600);
                                                        $minutes = intval(($diff / 60) % 60);
                                                        $seconds = intval($diff % 60);
                                                        $timeTotal[] = date('H:i:s', strtotime($hours . ':' . $minutes . ':' . $seconds));
                                                    } else {
                                                        if (!empty($attendanceRow->late_grace_time)) {
                                                            $startTime = date("Y-m-d", strtotime('-' . $attendanceRow->late_grace_time . ' min', strtotime($attendanceRow->time_in)));
                                                        } else {
                                                            $startTime = date('Y-m-d', strtotime($attendanceRow->time_in));
                                                        }
                                                        if ($startTime <= date('Y-m-d')) {
                                                            if ($attendanceRow) {
                                                                //echo date('H:i:s', strtotime($attendanceEmployee[0]->time_in)) . '<br>';
                                                                $sandwich = 0;
                                                                if (date('H:i:s', strtotime($startTime)) <= $attendanceRow->shift_start_time) {
                                                                    $present = 'P';
                                                                } else {
                                                                    $present = 'L';
                                                                    $lateCount++;
                                                                }
                                                            }
                                                        }
                                                        $timeStart = $attendanceRow->time_in;
                                                    }
                                                }
                                                $count++;
                                            }
                                            if ($timeTotal) {
                                                $enddatetimes = 0;
                                                $enddatetime = 0;
                                                foreach ($timeTotal AS $timeTotalRow) {
                                                    $enddatetime = strtotime($timeTotalRow) + strtotime($enddatetime) - strtotime('00:00:00');
                                                    $enddatetimes = intval($enddatetime);
                                                }
                                            }
                                            $enddatetimes = intval($enddatetimes) + strtotime('00:00:00');
                                            $timeTotal = array();
                                        } else if (!empty($attendanceNight)) {
                                            $count = 0;
                                            $counter = 0;
                                            $enddatetimes = '';
                                            //print_r($attendanceNight);
                                            foreach ($attendanceNight AS $attendanceRow) {
                                                if ($attendanceRow->shift == 'night') {
                                                    $nightstarttime = date('Y-m-d 19:00:00', strtotime($year . '-' . $monthCheck . '-' . $d));
                                                    $nightendtime = date('Y-m-d 18:59:00', strtotime('+1 day', strtotime($year . '-' . $monthCheck . '-' . $d)));
                                                    if ($attendanceRow->time_in >= $nightstarttime && $attendanceRow->time_in <= $nightendtime) {
                                                        $counter++;
                                                        if ($counter % 2 == 0) {
                                                            $timeEnd = '';
                                                            $timeEnd = $attendanceRow->time_in;

                                                            $diff = abs(strtotime($timeEnd) - strtotime($timeStart));

                                                            $totalworkminutes = number_format((($diff % 86400) / 3600), 2);
                                                            $amountPerDay = $totalworkminutes * $salaryPerUnit;
                                                            $totalPayamount += $amountPerDay;
                                                            //echo $totalworkminutes.'<br>';

                                                            $years = floor($diff / (365 * 60 * 60 * 24));
                                                            $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                                                            $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));

                                                            $hours = intval(($diff % 86400) / 3600);
                                                            //echo $hours . ' - ';
                                                            $minutes = intval(($diff / 60) % 60);
                                                            //echo $minutes . '<br>';
                                                            $seconds = intval($diff % 60);
                                                            $timeTotal[] = date('H:i:s', strtotime($hours . ':' . $minutes . ':' . $seconds));
                                                        } else {
                                                            if (!empty($attendanceRow->late_grace_time)) {
                                                                $startTime = date("Y-m-d H:i:s", strtotime('-' . $attendanceRow->late_grace_time . ' min', strtotime($attendanceRow->time_in)));
                                                            } else {
                                                                $startTime = date('Y-m-d H:i:s', strtotime($attendanceRow->time_in));
                                                            }
                                                            if ($startTime <= date('Y-m-d 19:00:00')) {
                                                                if ($attendanceRow) {
                                                                    $sandwich = 0;
                                                                    if (date('H:i:s', strtotime($startTime)) <= $attendanceRow->shift_start_time) {
                                                                        $present = 'P';
                                                                    } else {
                                                                        $present = 'L';
                                                                        $lateCount++;
                                                                    }
                                                                }
                                                            }
                                                            $timeStart = $attendanceRow->time_in;
                                                        }
                                                    }
                                                }
                                                $count++;
                                            }
                                            if ($timeTotal) {
                                                $enddatetimes = '';
                                                $enddatetime = '';
                                                foreach ($timeTotal AS $timeTotalRow) {
                                                    $enddatetime = strtotime($timeTotalRow) + strtotime($enddatetime) - strtotime('00:00:00');
                                                    $enddatetimes = intval($enddatetime);
                                                }
                                            }
                                            $enddatetimes = $enddatetimes + strtotime('00:00:00');
                                            $timeTotal = array();
                                        }
                                    } else {
                                        if (!empty($background)) {
                                            $getDateNext = date('Y-m-d', strtotime('+1 day', strtotime($getDate)));
                                            $getDateNextnew = $getDateNext;
                                            $filterAt = ' AND STR_TO_DATE(time_in, "%Y-%m-%d") = "' . $getDateNextnew . '" ORDER BY time_in ';
                                            $attDay = Attendance::GetAttendanceByEmployeeId($_REQUEST['employee_id'], $filterAt);
                                            if (empty($attDay[0])) {
                                                foreach ($holidays AS $holidaysRow) {
                                                    if ($getDateNextnew == $holidaysRow->ac_date) {
                                                        $filterAt = ' AND STR_TO_DATE(time_in, "%Y-%m-%d") = "' . date('Y-m-d', strtotime('+1 day', strtotime($getDateNextnew))) . '" ORDER BY time_in ';
                                                        $attDay = Attendance::GetAttendanceByEmployeeId($_REQUEST['employee_id'], $filterAt);
                                                        if (empty($attDay[0])) {
                                                            $getDateNextnew = date('Y-m-d', strtotime('+1 day', strtotime($getDateNextnew)));
                                                        }
                                                    }
                                                }
                                            }
                                            //if($d == 4) {
                                            //    echo $sandwich . " san" . $d;
                                            //    print_r($attDay);
                                            //    echo "<br>";
                                            //	echo $getDateNextnew . " next";
                                            //    exit;
                                            //}
                                            if (empty($attDay[0]) || $sandwich > 0) {

                                                $present = 'A';
                                                //$totalPayamount += $amountPerDay;
                                                //$background = '';
                                                //$amountPerDay = '';
//                                                foreach ($holidays AS $holidaysRow) {
//                                                    if ($getDateNext == $holidaysRow->ac_date) {
//                                                        $present = 'H';
//                                                        $totalPayamount += $amountPerDay;
//                                                    }
//                                                }
                                                if ($present == 'A') {
                                                    $amountPerDay = "";
                                                    $absentCount++;
                                                }
                                                if ($d == 31) {
//                                                                print_r($attDay);
//                                                                exit;
                                                }
                                            } else {
                                                $present = 'H';
                                                $totalPayamount += $amountPerDay;
                                            }
                                            //$present = 'H';
                                        } else {
                                            if ($LeavesArray) {
                                                if (in_array($getDate, $LeavesArray)) {
                                                    $present = 'LE';
                                                    $background = '#9F6';
                                                } else {
                                                    $present = '';
                                                }
                                            } else if (date('Y-m-d') >= $getDate) {
                                                $present = 'A';
                                                $absentCount++;
                                                $sandwich++;
                                            } else {
                                                $present = '';
                                            }
                                        }
                                    }
                                    echo '<tr style="border: 1px solid #666;">';
                                    echo '<td style="background-color:' . $background . ';">' . $d . '</td>';
                                    echo '<td style="background-color:' . $background . ';">' . (!empty($enddatetimes) ? date("H:i:s", $enddatetimes) : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . ';">' . (!empty($amountPerDay) ? number_format($amountPerDay, 2) : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . ';">' . (!empty($present) ? $present : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . ';">';
                                    if ($present == 'A') {
                                        echo '<a style="display: block; cursor:pointer;font-size: 10px;padding: 1px;" data-toggle="modal" href="#myModal' . $d . '" title="Import"><button class="btn waves-effect waves-light">Add AL/CL</button></a>';
                                        echo '<!-- Modal -->
                                <div id="myModal' . $d . '" class="modal fade"
                                     role="dialog">
                                    <div class="modal-dialog">
                                        <form action="leaveupdate.php" method="post" name="leaveupdate"
                                              enctype="multipart/form-data">
                                            <!-- Modal content-->
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <button type="button" class="close"
                                                            data-dismiss="modal">&times;</button>
                                                    <h4 class="modal-title">Add Annual/Casual Leave</h4>
                                                </div>
                                                <div class="modal-body">
                                                    <h4 style="text-align:left;" class="col-lg-4">Date: </h4>
                                                    <h4 style="text-align:left;" class="col-lg-8">' . date('d-m-Y', strtotime($year . '-' . $monthCheck . '-' . $d)) . '<br>
                                                        <input class="form-control" type="hidden"
                                                               name="leave_date"
                                                               value="' . date('Y-m-d', strtotime($year . '-' . $monthCheck . '-' . $d)) . '"
                                                               id="leave_date"/>
                                                        <input class="form-control" type="hidden"
                                                               name="employee_id"
                                                               value="' . $employee_id . '"
                                                               id="employee_id"/>
                                                        <input type="hidden" name="url" value="' . $actual_link . '">
                                                    </h4>
                                                    <br>
                                                    <h5 style="text-align:left;" class="col-lg-4">Leave Type: </h5>
                                                    <span style="text-align:left;" class="col-lg-8">
                                                    <select class="form-control" name="type">
                                                    <option value="AL">Annual Leave</option>
                                                    <option value="CL">Casual Leave</option>
                                                    </select>
                                                    </span>
                                                    <div class="clearfix"></div>
                                                    <br>
                                                    <h5 style="text-align:left;" class="col-lg-4">Description: </h5>
                                                    <span style="text-align:left;" class="col-lg-8">
                                                    <textarea class="form-control" name="description" id="description"></textarea>
                                                    </span>
                                                    <br><br><br><br><br>
                                                </div>

                                                <div class="modal-footer">
                                                    <input type="submit" class="btn waves-effect waves-light" name="submit"
                                                           id="submit" value="Submit"/>
                                                    <button type="button"
                                                            class="btn waves-effect waves-light"
                                                            data-dismiss="modal">Close
                                                    </button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>';
                                    }
                                    echo '</td>';
                                    echo '</tr>';
                                    $enddatetimes = '';
                                    $amountPerDay = '';
                                }
                            }
                        }
                        ?>
                        </tbody>
                    </table>
                    <br>
                    <?php
                    $lateAbsent = floor($lateCount / 3);
                    $lateAdsentdeduction = $lateAbsent * 9 * $salaryPerUnit;
                    $totalPayamounts -= $lateAdsentdeduction;
                    if($by_pass == 1){
                        $totalPayamount = $salary;
                    }
                    $totalPayamounts = ($totalPayamount - $advanceSalary) - $loanPerMonth;
                    ?>
                    <table class="display table table-bordered table-striped">
                        <tr style="border: 1px solid #666;">
                            <th colspan="2">Total Salary</th>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <td>Holidays</td>
                            <td><?= $holidayCount ?></td>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <td>Absent</td>
                            <td><?= $absentCount ?></td>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <td>Late</td>
                            <td><?php
                                echo !empty($lateCount) ? $lateCount : '-';
                                if ($lateAdsentdeduction) {
                                    echo ' = ' . $lateAbsent . ' Absent (' . number_format($lateAdsentdeduction, 0) . ')';
                                } ?></td>
                        </tr>
                        <?php
                        $absentCount = intval($absentCount) + intval($lateAbsent);
                        //                                    if ($absentCount == 0 || $absentCount == '') {
                        //                                        $totalPayamounts += 1000;
                        //                                        ?>
                        <!--                                        <tr>-->
                        <!--                                            <td>Attendance Allowance</td>-->
                        <!--                                            <td>1000</td>-->
                        <!--                                        </tr>-->
                        <!--                                    --><?php //} ?>
						<tr style="border: 1px solid #666;">
                            <td>Salary</td>
                            <td><?= (!empty($totalPayamount) ? number_format(round($totalPayamount), 0) : "0") . ' / ' . (!empty($salary) ? number_format($salary, 0) : "0") ?></td>
                        </tr>
						<?php 
						$deduction = $absentCount * $salaryPerUnit * 9;
						$overtime = $totalPayamount - ($salary - $deduction);						?>
						<tr style="border: 1px solid #666;">
                            <td>Deduction</td>
							<td><?= number_format($deduction, 0) ; ?></td>
                        </tr>
						<tr style="border: 1px solid #666;">
                            <td>Overtime</td>
							<td><?= number_format($salaryPerUnit, 2); ?> x <?= number_format(($overtime / $salaryPerUnit), 2); ?> = <?= number_format($overtime, 0) ?></td>
                        </tr>
                        <?php
                        if ($advanceSalary) {
                            echo '<tr style="border: 1px solid #666;">
                                        <td>Advance Salary</td>
                                        <td>' . $advanceSalary . '</td>
                                    </tr>';
                        }
                        if ($loanPerMonth) {
                            echo '<tr style="border: 1px solid #666;">
                                        <td>Loan</td>
                                        <td>' . $loanPerMonth . '</td>
                                    </tr>';
                        }
                        ?>
                        <tr style="border: 1px solid #666;">
                            <td>Total Pay Amount</td>
                            <td><?= (!empty($totalPayamounts) ? number_format($totalPayamounts, 0) : "0") ?>
							<?php
							$description = "Automated from Monthly Attendance - ".$month;
							$filtersalary = " WHERE description = '$description' AND employee_id = '$employee_id'";
							$salaryDetails = SalarySetup::GetSalarySetupList($filtersalary);
							if(isset($salaryDetails[0]->id)){
								echo " - Paid ";
							}else{
								?>
								<button class="btn blue btn-paid">Paid</button>
								<?php
							}
							?>
							</td>
                        </tr>
						<script>
							$('.btn-paid').click(function () {
								swal({
										title: "Are you sure?",
										text: "Are you sure you want to add salary",
										type: "warning",
										showCancelButton: true,
										confirmButtonColor: '#DD6B55',
										confirmButtonText: 'Yes',
										closeOnConfirm: false
									},
									function () {
										swal("Successful!", "Salary has been paid", "success");
										window.location.href = 'attendance.php?month=<?=$month?>&view=&year=<?=$year?>&employee_id=<?=$employee_id?>&paid=1&amount=<?=intval($totalPayamounts)?>';
									});
							});
						</script>
                    </table>
                </div>
            <?php } ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript"
        src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>

<script type="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/attendance.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
        $('table.demo1').floatThead({
            position: 'fixed',
            top: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });
</script>
</body>
</html>