<?php
error_reporting('E_ALL');
ini_set('display_errors', '1');
try {

    if (!isset($_REQUEST['employee_id'])) {
        header('location: ../invoice.php');
        exit;
    } else {
        //$id = $_GET['print'];
    }

    $employee_id = $_GET['employee_id'];
    $year = $_GET['year'];
    $month = $_GET['month'];

    include_once('../../../classes/manager.class.php');
    include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
    include_once('../../../fpdf/fpdf1.php');


    $m = new Manager();
    extract($_REQUEST);
    $param_data = ControlConfifguration::GetConfiguration();
    define('PROJECT_NAME', $param_data->name);
    define('PROJECT_ADDRESS', $param_data->address);
    define('PROJECT_TEL', $param_data->contact);
    define('PROJECT_EMAIL', $param_data->email);
    define('PROJECT_WEBSITE', $param_data->website);
    define('PROJECT_COLOR', $param_data->color);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);

    //For Employee Detail
    $qry = EmployeeSetup::GetEmployeeSetupById($employee_id);
    $salary = $qry->salary;

    if (!empty($qry)) {

        $font = 10;
        $picx = 100;
        $setx = 5;
        $multi = 210;
        $picsetx = 150;
        $w = array(50, 80, 50, 80);
        $path = "../../../";

        $pdf = new FPDFWithOutWaterMark('P', 'mm', 'A4');
        $pdf->SetMargins(0, 0, 0);

        $pdf->SetTitle('Attendance Report');
        $pdf->AddPage();
        $pdf->Ln();
       // $pdf->SetFont('Arial', 'B', 14);
       // $pdf->Cell(0, 6, PROJECT_NAME, 0, 0, 'C');
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(0, 5, 'Attendance Report - '.$qry->name.' ('.$month.', '.$year.')', 0, 0, 'C');

        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        $header = array('Days', 'Time In', 'Time Out', 'Work Hours', 'Amount / Day', 'Attendance');

        //$header = array('S.No', 'Date', 'Invoice', 'Customer', 'Product', 'Status', 'Qty', 'Factory Rate', 'Factory Price', 'Dist. Rate', 'Net Pay.', 'Rate', 'Sale Price', 'Discount', 'Profit/Loss Dist.', 'Profit/Loss Fact.');

//        $filterProductInvoice = " WHERE invoice_id = '$invoice_id'";
//        $productData = Invoice::GetInvoiceProducts($filterProductInvoice);

        function FancyTable($header, $qry, $employee_id, $month, $year, $setx)
        {
            global $pdf;
            $by_pass = 0;
            $sandwich = 0;
            $advanceSalary = 0;

            if ($month) {
                $monthcount = $month;
            } else {
                $monthcount = date('F');
            }
            for ($m = 1; $m <= 12; ++$m) {
                if (date('F', mktime(0, 0, 0, $m, 1)) == trim($monthcount)) {
                    $monthCheck = $m;
                }
            }

            $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") = "' . $getYearMonth . '"';
            //$holidays = HolidaySetup::GetHolidaySetupList($holidayFilter);

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

            // Colors, line width and bold font
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetDrawColor(128, 0, 0);
            $pdf->SetLineWidth(.1);
            $pdf->SetFont('Arial', 'B', 12);
            // Header
            $wr = array(15, 35, 35, 40, 36, 40);

            for ($i = 0; $i < count($header); $i++)
                $pdf->Cell($wr[$i], 5, $header[$i], 1, 0, 'C', true);
            $pdf->Ln();
            // Color and font restoration
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetFont('');
            // Data
            $fill = false;

            $counter = 1;
            $counter_pagebreak = 1;
            $totalHoliday = 0;
            $holidayCount = 0;
            $totalPayamount = 0;
            $totalPayamounts = 0;
            $timeStart = '';
            $lateCount = 0;
            $absentCount = 0;

            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;
                            }
                        }
                        $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;
                                        }
                                    }
//                                    if ($getDate == $holidaysRow->ac_date) {
//                                        $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;
                                        $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;
                                    }
                                }
                            }
                        }

                        $present = '';
                        $timeInDisplay = "-";
                        $timeOutDisplay = "-";
                        $lateAfterFixedStart = false;
                        if ($attendanceDay || $attendanceNight) {
                            if (!empty($attendanceDay)) {
                                $count = 0;
                                $counter = 0;
                                $enddatetimes = '';
                                foreach ($attendanceDay AS $attendanceRow) {
                                    if ($attendanceRow->shift == 'day') {
                                        if ($counter == 0 && !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 = '';
                                            $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 = '';
                                    $enddatetime = '';
                                    foreach ($timeTotal AS $timeTotalRow) {
                                        $enddatetime = strtotime($timeTotalRow) + strtotime($enddatetime) - strtotime('00:00:00');
                                        $enddatetimes += intval($enddatetime);
                                    }
                                }
                                $enddatetimes = $enddatetimes + strtotime('00:00:00');
                                $timeTotal = [];
                            } else if (!empty($attendanceNight)) {
                                $count = 0;
                                $counter = 0;
                                $enddatetimes = '';
                                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 = '';
                                                $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 = [];
                            }
                        } 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(empty($attDay[0]) || $sandwich > 0){
                                //if(date('Y-m-d', strtotime($attendanceNight[$counter]->time_in)) != $getDate && $sandwich != 0){
                                    $present = 'A';
//                                    $background = '';
                                    //$amountPerDay = '';
                                    //$present = 'H';
                                    //$totalPayamount += $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++;
                                    }
                                }else{
                                    $present = 'H';
                                    $totalPayamount += $amountPerDay;
                                }
                            } 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') {
                            if ($present != 'L') {
                                $lateCount++;
                            }
                            $present = 'L';
                        }

                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 12);
                        $pdf->Cell($wr[0], 5, $d, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 5, $timeInDisplay, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 5, $timeOutDisplay, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[3], 5, (!empty($enddatetimes) ? date("H:i:s", $enddatetimes) : "-"), 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[4], 5, (!empty($amountPerDay) ? number_format($amountPerDay, 2) : "-"), 'LRBT', 0, 'L', $fill);
                        if($present == 'L'){
                            $presentValue = 'Late';
                        }else if($present == 'P'){
                            $presentValue = 'Present';
                        }else if($present == 'A'){
                            $presentValue = 'Absent';
                        }else if($present == 'H'){
                            $presentValue = 'Holiday';
                        }else if($present == 'LE'){
                            $presentValue = 'Leave';
                        }else{
                            $presentValue = '-';
                        }
                        if ($present == 'L') {
                            $pdf->SetTextColor(255, 0, 0);
                        } else if ($present == 'A') {
                            $pdf->SetTextColor(255, 165, 0);
                        } else {
                            $pdf->SetTextColor(0, 0, 0);
                        }

                        $pdf->Cell($wr[5], 5, $presentValue , 'LRBT', 0, 'L', $fill);
                        $pdf->SetTextColor(0, 0, 0);

                        $enddatetimes = '';
                        $amountPerDay = '';
                    }
                    if ($counter == 36 || ($counter != 36 && ($counter_pagebreak) % 40 == 0)) {
                        $counter_pagebreak = 1;
                        $pdf->AddPage();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', 'B', 12);
                        for ($i = 0; $i < count($header); $i++)
                            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    }


                    $pdf->Ln();
                  //  $fill = !$fill;
                    $counter++;
                    $counter_pagebreak++;
                }
            }
            //$pdf->SetFillColor(255, 204, 0);
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 12);
            $pdf->Cell($wr[0], 2, '', '', 0, 'L');
            $pdf->Cell($wr[1], 2, '', '', 0, 'L');
            $pdf->Cell($wr[2], 2, "", '', 0, 'R');
            $pdf->Cell($wr[3], 2, "", '', 0, 'R');
            $pdf->Cell($wr[4], 2, "", '', 0, 'R');
            $pdf->Cell($wr[5], 2, "", '', 0, 'R');

            $lateAbsent = 0;
            $lateAdsentdeduction = 0;
            $deduction = 0;
            $overtime = 0;
            $actualAbsentCount = intval($absentCount);
            $actualAbsentDeductionDays = 0;
            $actualAbsentDeductionAmount = 0;

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

            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 {

                $totalPayamount = $salary;
                $totalPayamounts = $salary;
            }

            $wr = array(100, 101, 70, 70);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 12);
            $pdf->Cell(201, 5, 'Total Salary', 1, 0, 'C', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Holidays', 1, 0, 'L', $fill);
            $pdf->Cell($wr[1], 5, $holidayCount, 1, 0, 'L', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Absent', 1, 0, 'L', $fill);

            if ($isLabourCategory) {
                if ($actualAbsentDeductionDays > 0) {
                    $absentDisplay = $actualAbsentCount . ' = ' . $actualAbsentDeductionDays . ' Days Salary Deduction (' . number_format($actualAbsentDeductionAmount, 0) . ')';
                } else {
                    $absentDisplay = $actualAbsentCount . ' - Allowed / No Deduction';
                }
            } else if ($isAdminCategory) {
                $absentDisplay = $actualAbsentCount . ' - No Deduction';
            } else {
                $absentDisplay = $actualAbsentCount . ' - No Deduction';
            }

            $pdf->Cell($wr[1], 5, $absentDisplay, 1, 0, 'L', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Late', 1, 0, 'L', $fill);

            if ($isLabourCategory || $isAdminCategory) {
                if ($lateAdsentdeduction) {
                    $pdf->Cell($wr[1], 5, (!empty($lateCount) ? $lateCount : '-') . ' = ' . $lateAbsent . ' Absent (' . number_format($lateAdsentdeduction, 0) . ')', 1, 0, 'L', $fill);
                } else {
                    $pdf->Cell($wr[1], 5, (!empty($lateCount) ? $lateCount : '-'), 1, 0, 'L', $fill);
                }
            } else {
                $pdf->Cell($wr[1], 5, (!empty($lateCount) ? $lateCount : '-') . ' - No Deduction', 1, 0, 'L', $fill);
            }

            if ($isLabourCategory) {
                $deduction = $actualAbsentDeductionAmount + $lateAdsentdeduction;
                $totalPayamount = $totalPayamount - $actualAbsentDeductionAmount;
                $totalPayamounts = $totalPayamounts - $actualAbsentDeductionAmount;
                $overtime = $totalPayamount - ($salary - $deduction);
            } else if ($isAdminCategory) {
                $deduction = $lateAdsentdeduction;
                $overtime = 0;
                $totalPayamount = $salary;
                $totalPayamounts = (($salary - $deduction) - $advanceSalary) - $loanPerMonth;
            } else {
                $deduction = 0;
                $overtime = 0;
                $totalPayamount = $salary;
                $totalPayamounts = $salary;
            }

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Salary', 1, 0, 'L', $fill);

            if ($isLabourCategory) {
                $salaryDisplay = (!empty($totalPayamount) ? number_format(round($totalPayamount), 0) : "0") . ' / ' . (!empty($salary) ? number_format($salary, 0) : "0");
            } else {
                $salaryDisplay = number_format($salary, 0);
            }

            $pdf->Cell($wr[1], 5, $salaryDisplay, 1, 0, 'L', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Deduction', 1, 0, 'L', $fill);
            $pdf->Cell($wr[1], 5, number_format($deduction, 0), 1, 0, 'L', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Overtime', 1, 0, 'L', $fill);

            if ($isLabourCategory) {
                $overtimeHours = ($salaryPerUnit > 0 ? ($overtime / $salaryPerUnit) : 0);
                $overtimeDisplay = number_format($salaryPerUnit, 2) . ' x ' . number_format($overtimeHours, 2) . ' = ' . number_format($overtime, 0);
            } else {
                $overtimeDisplay = '0';
            }

            $pdf->Cell($wr[1], 5, $overtimeDisplay, 1, 0, 'L', $fill);

            if ($advanceSalary) {
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->Cell($wr[0], 5, 'Advance Salary', 1, 0, 'L', $fill);
                $pdf->Cell($wr[1], 5, $advanceSalary, 1, 0, 'L', $fill);
            }

            if ($loanPerMonth) {
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->Cell($wr[0], 5, 'Loan', 1, 0, 'L', $fill);
                $pdf->Cell($wr[1], 5, $loanPerMonth, 1, 0, 'L', $fill);
            }

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 5, 'Total Pay Amount', 1, 0, 'L', $fill);
            $pdf->Cell($wr[1], 5, (!empty($totalPayamounts) ? number_format($totalPayamounts, 0) : "0"), 1, 0, 'L', $fill);

            $wr = array(80, 21, 20, 80);

            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 12);
            $pdf->Cell($wr[0], 7, "Company Signature's", 'T', 0, 'C');
            $pdf->Cell($wr[1], 7, "", '', 0, 'C');

            $pdf->Cell($wr[2], 7, "", '', 0, 'C');
            $pdf->Cell($wr[3], 7, "Employee Signature's", 'T', 0, 'C');
        }

        FancyTable($header, $qry, $employee_id, $month, $year, $setx);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

    $pdf->Output();
    ob_end_flush();
    exit;
} catch (Exception $e) {
    echo $e->getMessage();
}
?>