<?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: 14px !important;
            text-align: center;
            padding: 15px 3px !important;
          font-weight: bold !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['extra_amount'] = $extraamount;
	$data['advance'] = 0;
	$data['description'] = "Automated from Monthly Attendance - ".$month." ".$year;
    $datePaid = $year.'-'.$month;
	$data['date_time'] = date('Y-m-28', strtotime($datePaid));
	$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: 'yyyy-mm-dd',
                        selectMonths: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'yyyy-mm-dd',
                        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
        // Fetch only ACTIVE employees, ordered by name
        $filterEmployee = " WHERE status = 'active' ORDER BY name";
        $qryEmployee = EmployeeSetup::GetEmployeeSetupList($filterEmployee);

        // Buckets
        $adminEmployees  = [];
        $labourEmployees = [];

        if ($qryEmployee) {
            // Split employees by category (anything not 'labour' goes to Admin)
            foreach ($qryEmployee as $qery) {
                $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qery->category_id);
                $catName = $categ && isset($categ->name) ? strtolower(trim($categ->name)) : '';
                if ($catName === 'labour' || $catName === 'labor') {
                    $labourEmployees[] = $qery;
                } else {
                    $adminEmployees[] = $qery;
                }
            }

            // Optional icons (remove data-icon attr if you don’t use these files)
            $adminIcon  = "../../images/admin.png";
            $labourIcon = "../../images/labour.png";

            echo '<select id="employee_id" name="employee_id" class="form-control">';
            echo '<option value="">All</option>';

            // Admin group
            if (!empty($adminEmployees)) {
                echo '<optgroup label="Admin">';
                foreach ($adminEmployees as $emp) {
                    echo '<option data-icon="' . $adminIcon . '" value="' . $emp->id . '"'
                        . (($emp->id == $employee_id) ? ' selected' : '') . '>'
                        . $emp->name . '</option>';
                }
                echo '</optgroup>';
            }

            // Labour group
            if (!empty($labourEmployees)) {
                echo '<optgroup label="Labour">';
                foreach ($labourEmployees as $emp) {
                    echo '<option data-icon="' . $labourIcon . '" value="' . $emp->id . '"'
                        . (($emp->id == $employee_id) ? ' selected' : '') . '>'
                        . $emp->name . '</option>';
                }
                echo '</optgroup>';
            }

            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 . '">';
//                                    }
                                    $maxEmpFilter = " WHERE status = 'active'";
                                    $maxEmp = EmployeeSetup::GetEmployeeSetupList($maxEmpFilter);
                                    foreach($maxEmp AS $maxEmpRow){
                                        echo '<input type="hidden" checked="" name="uid" value="' . $maxEmpRow->machine_uid . '">';
                                    }
                                    ?>
                                </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">
        <?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);

        $adminEmployees = [];
        $labourEmployees = [];

        if ($qry) {
            foreach ($qry as $qery) {
                $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qery->category_id);
                if (strtolower(trim($categ->name)) == 'labour') {
                    $labourEmployees[] = $qery;
                } else {
                    $adminEmployees[] = $qery;
                }
            }
        }

        // First Part: Admin Employees
        ?>
        <h4 style="text-align: center;">Admin Employees</h4>
        <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; letter-spacing: 3px;">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
            $numbering = 0;
            foreach ($adminEmployees as $qery) {
                $numbering++;
                $lateCount = 0;
                $absentCount = 0;
                $holidayCount = 0;
                $leavesCount = 0;
                $shift = "";

                echo '<tr>';
                echo '<td>' . $numbering . '</td>';
                echo '<td style="text-align: left; padding: 2px 5px; letter-spacing: 3px;">' . $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 = Attendance::GetAttendanceByEmployeeId($qery->id, $filterAtt);

                    if ($attendanceEmployee) {
                        $shift = $attendanceEmployee[0]->shift;
                    }
                    $background = '';
                    $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qery->category_id);

                    // Holiday logic
                    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++;
                                    } elseif ($getDateNext == $holidaysRow->ac_date && $categ->shift_cat == 'b') {
                                        $background = '#FFA500';
                                        $holidayCount++;
                                    }
                                }
                            }
                        }
                    } elseif ((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++;
                                }
                            }
                        }
                    }

                    // Leave logic
                    $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') {
                            if ($attendanceEmployee[0]->shift == 'day') {
                                if (date('H:i:s', strtotime($attendanceEmployee[0]->time_in)) <= '10:00:00') {
                                    $present = 'P';
                                    $color = '#00FF00';
                                } else {
                                    $present = 'L';
                                    $color = '#FF0000';
                                    $lateCount++;
                                }
                            } elseif ($attendanceEmployee[0]->shift == 'night') {
                                if (!empty($attendanceEmployee[0]->late_grace_time)) {
                                    $startTime = date("Y-m-d H:i:s", strtotime('-' . $attendanceEmployee[0]->late_grace_time . ' min', strtotime($attendanceEmployee[0]->time_in)));
                                } else {
                                    $startTime = date('Y-m-d H:i:s', strtotime($attendanceEmployee[0]->time_in));
                                }
                                if ($startTime <= date('Y-m-d 19:00:00')) {
                                    if (date('H:i:s', strtotime($startTime)) <= $attendanceEmployee[0]->shift_start_time) {
                                        $present = 'P';
                                        $color = '#00FF00';
                                    } else {
                                        $present = 'L';
                                        $color = '#996600';
                                        $lateCount++;
                                    }
                                }
                            }
                        } elseif ($getDate <= date('Y-m-d')) {
                            if (!empty($background)) {
                                $present = 'H';
                            } else {
                                $present = 'A';
                                $color = '#FF0000';
                                $absentCount++;
                            }
                        } 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>' . $lateCount . '</td>';
                echo '<td>' . $absentCount . '</td>';
                echo '<td>' . $leavesCount . '</td>';
                echo '<td>' . $holidayCount . '</td>';
                echo '</tr>';
            }
            ?>
            
            </tbody>
        </table>

        <br><br>

        <?php
        // Now Second Part: Labour Employees
        ?>
        <!-- Labour Employees Table -->
   <h4 style="text-align: center;">Labour Employees</h4>
        <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; letter-spacing: 3px;">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
            $numbering = 0;
            foreach ($labourEmployees as $qery) {
                $numbering++;
                $lateCount = 0;
                $absentCount = 0;
                $holidayCount = 0;
                $leavesCount = 0;
                $shift = "";

                echo '<tr>';
                echo '<td>' . $numbering . '</td>';
                echo '<td style="text-align: left; padding: 2px 5px; letter-spacing: 3px;">' . $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 = Attendance::GetAttendanceByEmployeeId($qery->id, $filterAtt);

                    if ($attendanceEmployee) {
                        $shift = $attendanceEmployee[0]->shift;
                    }
                    $background = '';
                    $categ = EmployeeCategorySetup::GetEmployeeCategorySetupById($qery->category_id);

                    // Holiday logic
                    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++;
                                    } elseif ($getDateNext == $holidaysRow->ac_date && $categ->shift_cat == 'b') {
                                        $background = '#FFA500';
                                        $holidayCount++;
                                    }
                                }
                            }
                        }
                    } elseif ((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++;
                                }
                            }
                        }
                    }

                    // Leave logic
                    $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') {
                            if ($attendanceEmployee[0]->shift == 'day') {
                                if (date('H:i:s', strtotime($attendanceEmployee[0]->time_in)) <= '08:00:00') {
                                    $present = 'P';
                                    $color = '#00FF00';
                                } else {
                                    $present = 'L';
                                    $color = '#FF0000';
                                    $lateCount++;
                                }
                            } elseif ($attendanceEmployee[0]->shift == 'night') {
                                if (!empty($attendanceEmployee[0]->late_grace_time)) {
                                    $startTime = date("Y-m-d H:i:s", strtotime('-' . $attendanceEmployee[0]->late_grace_time . ' min', strtotime($attendanceEmployee[0]->time_in)));
                                } else {
                                    $startTime = date('Y-m-d H:i:s', strtotime($attendanceEmployee[0]->time_in));
                                }
                                if ($startTime <= date('Y-m-d 19:00:00')) {
                                    if (date('H:i:s', strtotime($startTime)) <= $attendanceEmployee[0]->shift_start_time) {
                                        $present = 'P';
                                        $color = '#00FF00';
                                    } else {
                                        $present = 'L';
                                        $color = '#996600';
                                        $lateCount++;
                                    }
                                }
                            }
                        } elseif ($getDate <= date('Y-m-d')) {
                            if (!empty($background)) {
                                $present = 'H';
                            } else {
                                $present = 'A';
                                $color = '#FF0000';
                                $absentCount++;
                            }
                        } 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>' . $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
                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>

        <br><br>


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

                    $categoryName = '';
                    $isLabourCategory = false;
                    $isAdminCategory = false;

                    if (isset($cat) && isset($cat->name)) {
                        $categoryName = strtolower(trim($cat->name));

                        if ($categoryName == 'labour' || $categoryName == 'labor') {
                            $isLabourCategory = true;
                        }
                    }

                    if (!$isLabourCategory) {
                        $isAdminCategory = true;
                    }

                    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 = date('Y-m', strtotime($loanSalaryRow->start_date));
                        $endDate = date("Y-m", strtotime('+' . ($loanSalaryRow->installment -1) . ' 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>Time In</th>
                   										<th>Time Out</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;
                                                        $holidaysday[] = date('d', strtotime($holidaysRow->ac_date));
                                                        $background = '#FFA500';
                                                        $holidayCount++;
                                                        $amountPerDay = 9 * $salaryPerUnit;
                                                    }else if($getDateNext == $holidaysRow->ac_date && $categ->shift_cat == 'b') {
                                                        $holidaysac[] = $holidaysRow->ac_date;
                                                        $holidaysday[] = date('d', strtotime($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;
                                                    $holidaysday[] = date('d', strtotime($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;
                                                    $holidaysday[] = date('d', strtotime($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 = '';
                                  	$timeInDisplay = "-";
									$timeOutDisplay = "-";
                                    $lateAfterFixedStart = false;
                                    $rowTextColor = '';
                                    if ($attendanceDay || $attendanceNight) {
                                        if (!empty($attendanceDay)) {
                                            $count = 0;
                                            $counter = 0;
                                            $enddatetimes = 0;
                                            foreach ($attendanceDay AS $attendanceRow) {
                                                if ($attendanceRow->shift == 'day') {
                                                    if ($timeInDisplay == "-" && !empty($attendanceRow->time_in) && $attendanceRow->time_in != '0000-00-00 00:00:00') {
                                                          $timeInDisplay = date('h:i A', strtotime($attendanceRow->time_in));

                                                          $employeeStartTime = $isLabourCategory ? '08:00:00' : '10:00:00';

                                                          if (date('H:i:s', strtotime($attendanceRow->time_in)) > $employeeStartTime) {
                                                              $lateAfterFixedStart = true;
                                                          }
                                                      }

                                                      $counter++;
                                                      if ($counter % 2 == 0) {
                                                          $timeEnd = '';

                                                          if (!empty($attendanceRow->time_out) && $attendanceRow->time_out != '0000-00-00 00:00:00') {
                                                              $timeEnd = $attendanceRow->time_out;
                                                          } else {
                                                              $timeEnd = $attendanceRow->time_in;
                                                          }

                                                          if (!empty($timeEnd) && $timeEnd != '0000-00-00 00:00:00') {
                                                              $timeOutDisplay = date('h:i A', strtotime($timeEnd));
                                                          }

                                                        $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 ($attendanceRow) {
                                                            $sandwich = 0;
                                                            $employeeStartTime = $isLabourCategory ? '08:00:00' : '10:00:00';

                                                            if (date('H:i:s', strtotime($attendanceRow->time_in)) <= $employeeStartTime) {
                                                                $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) {

                                                            if ($timeInDisplay == "-" && !empty($attendanceRow->time_in) && $attendanceRow->time_in != '0000-00-00 00:00:00') {
                                                                $timeInDisplay = date('h:i A', strtotime($attendanceRow->time_in));
                                                            }

                                                            $counter++;
                                                            if ($counter % 2 == 0) {
                                                                $timeEnd = '';

                                                                if (!empty($attendanceRow->time_out) && $attendanceRow->time_out != '0000-00-00 00:00:00') {
                                                                    $timeEnd = $attendanceRow->time_out;
                                                                } else {
                                                                    $timeEnd = $attendanceRow->time_in;
                                                                }

                                                                if (!empty($timeEnd) && $timeEnd != '0000-00-00 00:00:00') {
                                                                    $timeOutDisplay = date('h:i A', strtotime($timeEnd));
                                                                }

                                                            $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 (in_array($d, $holidaysday) && $sandwich == 0) {
                                                    $present = 'H';
                                                    $totalPayamount += $amountPerDay;
                                                }else if ($present == 'A') {
                                                    $amountPerDay = "";
                                                    $absentCount++;
                                                }
//                                                if ($d == 21) {
//                                                    print_r($holidaysday);
//                                                    exit;
//                                                }
//                                                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 = '';
                                            }
                                        }
                                    }
                                    if (($isAdminCategory || $isLabourCategory) && $lateAfterFixedStart && $present != 'LE' && $present != 'H') {
                                        $background = '#FF0000';
                                        $rowTextColor = 'color:#FFFFFF;';
                                        if ($present != 'L') {
                                            $lateCount++;
                                        }
                                        $present = 'L';
                                    }
                                    echo '<tr style="border: 1px solid #666;">';
                                    echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . $d . '</td>';
                                  	echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . $timeInDisplay . '</td>';
									echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . $timeOutDisplay . '</td>';
                                    echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . (!empty($enddatetimes) ? date("H:i:s", $enddatetimes) : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . (!empty($amountPerDay) ? number_format($amountPerDay, 2) : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">' . (!empty($present) ? $present : "-") . '</td>';
                                    echo '<td style="background-color:' . $background . '; ' . $rowTextColor . '">';
                                    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 = 0;
                        $lateAdsentdeduction = 0;
                        $deduction = 0;
                        $overtime = 0;
                        $actualAbsentCount = intval($absentCount);
                        $actualAbsentDeductionDays = 0;
                        $actualAbsentDeductionAmount = 0;

                        if ($actualAbsentCount >= 2) {
                            $actualAbsentDeductionDays = ($actualAbsentCount * 2) - 1;
                            $actualAbsentDeductionAmount = $actualAbsentDeductionDays * 9 * $salaryPerUnit;
                        }

                        /*
                         * Salary Logic:
                         * Labour: attendance-based salary, overtime, absent deduction, late deduction
                         * Admin: base salary, but every 3 late arrivals after 10:05 AM count as 1 absent deduction
                         * Other categories: base salary only
                         */
                        if ($isLabourCategory) {

                            $lateAbsent = floor($lateCount / 3);
                            $lateAdsentdeduction = $lateAbsent * 9 * $salaryPerUnit;

                            if ($by_pass == 1) {
                                $totalPayamount = $salary;
                            }

                            $totalPayamounts = ($totalPayamount - $advanceSalary) - $loanPerMonth;

                        } else if ($isAdminCategory) {

                            $lateAbsent = floor($lateCount / 3);
                            $lateAdsentdeduction = $lateAbsent * 9 * $salaryPerUnit;
                            $totalPayamount = $salary;
                            $totalPayamounts = (($salary - $lateAdsentdeduction) - $advanceSalary) - $loanPerMonth;

                        } else {

                            // Non-labour employees should only get base salary
                            $totalPayamount = $salary;
                            $totalPayamounts = $salary;
                        }
                        ?>
                        <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><?php
                              echo $actualAbsentCount;

                              if ($isLabourCategory || $isAdminCategory) {
                                  if ($actualAbsentDeductionDays > 0) {
                                      echo ' = ' . $actualAbsentDeductionDays . ' Days Salary Deduction (' . number_format($actualAbsentDeductionAmount, 0) . ')';
                                  } else {
                                      echo ' - Allowed / No Deduction';
                                  }
                              } else {
                                  echo ' - No Deduction';
                              }
                              ?></td>
                      </tr>
                        <tr style="border: 1px solid #666;">
                            <td>Late</td>
                            <td><?php
                                echo !empty($lateCount) ? $lateCount : '-';

                                if ($isLabourCategory || $isAdminCategory) {
                                    if ($lateAdsentdeduction) {
                                        echo ' = ' . $lateAbsent . ' Absent (' . number_format($lateAdsentdeduction, 0) . ')';
                                    }
                                } else {
                                    echo ' - No Deduction';
                                }
                                ?></td>
                        </tr>
                        <?php
                            if ($isLabourCategory) {
                                $deduction = $actualAbsentDeductionAmount + $lateAdsentdeduction;
                                $totalPayamount = $totalPayamount - $actualAbsentDeductionAmount;
                                $totalPayamounts = $totalPayamounts - $actualAbsentDeductionAmount;
                                $overtime = $totalPayamount - ($salary - $deduction);
                            } else if ($isAdminCategory) {
                                $deduction = $actualAbsentDeductionAmount + $lateAdsentdeduction;
                                $overtime = 0;
                                $totalPayamount = $salary;
                                $totalPayamounts = (($salary - $deduction) - $advanceSalary) - $loanPerMonth;
                            } else {
                                $deduction = 0;
                                $overtime = 0;
                                $totalPayamount = $salary;
                                $totalPayamounts = $salary;
                            }
                            ?>

                            <tr style="border: 1px solid #666;">
                                <td>Salary</td>
                                <td>
                                    <?php
                                    if ($isLabourCategory) {
                                        echo (!empty($totalPayamount) ? number_format(round($totalPayamount), 0) : "0") . ' / ' . (!empty($salary) ? number_format($salary, 0) : "0");
                                    } else {
                                        echo number_format($salary, 0);
                                    }
                                    ?>
                                </td>
                            </tr>

                            <tr style="border: 1px solid #666;">
                                <td>Deduction</td>
                                <td>
                                    <?php
                                    if ($isLabourCategory || $isAdminCategory) {
                                        echo number_format($deduction, 0);
                                    } else {
                                        echo '0';
                                    }
                                    ?>
                                </td>
                            </tr>

<tr style="border: 1px solid #666;">
    <td>Overtime</td>
    <td>
        <?php
        if ($isLabourCategory) {
            echo number_format($salaryPerUnit, 2) . ' x ' . number_format(($salaryPerUnit > 0 ? ($overtime / $salaryPerUnit) : 0), 2) . ' = ' . number_format($overtime, 0);
        } else {
            echo '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>Extra Pay Amount</td>
                            <?php
                            $salaryInd = "";
                            $description = "Automated from Monthly Attendance - ".$month." ".$year;
                            $filtersalary = " WHERE description = '$description' AND employee_id = '$employee_id'";
                            $salaryDetails = SalarySetup::GetSalarySetupList($filtersalary);
                            if($salaryDetails[0]->extra_amount != 0){
                                $salaryInd = $salaryDetails[0]->extra_amount;
                                $totalPayamounts += $salaryDetails[0]->extra_amount;
                            }
                            ?>
                            <td>
                                <input type="number" name="extra_amount" <?=($salaryInd!=0?'disabled':'')?> id="extra_amount" value="<?=$salaryInd?>" />
                            </td>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <td>Total Pay Amount</td>
                            <td><span id="totalAmountSalary"><?= (!empty($totalPayamounts) ? number_format($totalPayamounts, 0) : "0") ?></span>
							<?php

							if(isset($salaryDetails[0]->id)){
								echo " - Paid ";
							}else{
								?>
								<button class="btn blue btn-paid">Paid</button>
								<?php
							}
							?>
							</td>
                        </tr>
						<script>
                            $('#extra_amount').on('change', function(){
                                var amount = parseInt(<?=intval($totalPayamounts)?>);
                                if(!isNaN(parseInt($(this).val()))){
                                    amount += parseInt($(this).val());
                                }
                                $('#totalAmountSalary').text(amount);
                            })
							$('.btn-paid').click(function () {
                                var totalAmount = parseInt(<?=intval($totalPayamounts)?>);
                                var extraAmount = 0;
                                if(!isNaN(parseInt($('#extra_amount').val()))){
                                    extraAmount = parseInt($('#extra_amount').val());
                                    totalAmount += parseInt($('#extra_amount').val());
                                }
                                console.log(totalAmount);
								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='+totalAmount+'&extraamount='+extraAmount;
									});
							});
						</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');
    });
  
  document.addEventListener('DOMContentLoaded', function () {

    // ===== Helper: Sort table rows alphabetically by Employee Name =====
    function sortTableByEmployeeName(table) {
        const tbody = table.querySelector('tbody');
        if (!tbody) return;

        const rows = Array.from(tbody.querySelectorAll('tr')).filter(r => r.querySelector('td:nth-child(2)'));
        rows.sort((a, b) => {
            const nameA = a.querySelector('td:nth-child(2)').innerText.trim().toLowerCase();
            const nameB = b.querySelector('td:nth-child(2)').innerText.trim().toLowerCase();
            return nameA.localeCompare(nameB);
        });

        // Re-append sorted rows
        rows.forEach((row, i) => {
            row.querySelector('td:first-child').innerText = i + 1; // update S.No
            tbody.appendChild(row);
        });
    }

    // ===== Apply sorting for Admin and Labour tables =====
    document.querySelectorAll('h4').forEach(h => {
        const title = h.textContent.toLowerCase();
        if (title.includes('admin employees') || title.includes('labour employees')) {
            const nextTable = h.nextElementSibling;
            if (nextTable && nextTable.tagName === 'TABLE') {
                sortTableByEmployeeName(nextTable);
            }
        }
    });

});
</script>
</body>
</html>