<?php
if (!isset($_GET['userId'])) {
    header('Location: 505');
    exit;
}
include_once "global.php";
$employeeId = $functions->decode($_GET['userId']);
$employeeName = $functions->webUserName($employeeId, 'acc_name');

if (empty($employeeName)) {
    header('Location: 505');
    exit;
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Meta Tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description"
        content="Login to access your dashboard at <?php echo $functions->ibms_setting('Site Name'); ?>">
    <meta name="author" content="Interactive Media Pakistan">

    <!-- Page Title -->
    <title>Salary Slip - <?php echo $functions->ibms_setting('Site Name'); ?></title>

    <!-- Favicon -->
    <link rel="icon" href="webImages/favicon.ico" type="image/x-icon">

    <!-- Preconnect for Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Material+Icons+Outlined" rel="stylesheet">

    <!-- Loader -->
    <link href="css/pace.min.css" rel="stylesheet">
    <script src="js/pace.min.js" defer></script>

    <!-- Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-extended.css" rel="stylesheet">

    <!-- Plugins (if actually used on login page) -->
    <link href="plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="plugins/metismenu/metisMenu.min.css">
    <link rel="stylesheet" type="text/css" href="plugins/metismenu/mm-vertical.css">

    <!-- Custom Styles with Cache Busting -->
    <link href="sass/main.css?ver=<?php echo filemtime(__DIR__ . '/sass/main.css'); ?>" rel="stylesheet">
    <link href="sass/dark-theme.css?ver=<?php echo filemtime(__DIR__ . '/sass/dark-theme.css'); ?>" rel="stylesheet">
</head>

<body>
    <style>
        @media print {
            body {
                max-width: 812px !important;
                margin: 0 auto !important;
                width: 100% !important;
                background-color: #ffffff !important;
            }

            table {
                max-width: 700px !important;
                width: 100% !important;
                margin: 0 auto !important;
            }

            .card {
                margin-bottom: 0 !important;
                box-shadow: none !important;
            }

            .card-header {
                border: none !important;
            }
        }
    </style>
    <?php
    if ($_GET["action"] == "generate") {
    ?>
        <style>
            body {
                max-width: 812px !important;
                margin: 0 auto !important;
                width: 100% !important;
                background-color: #ffffff !important;
            }

            table {
                max-width: 700px !important;
                width: 100% !important;
                margin: 0 auto !important;
            }

            .card {
                margin-bottom: 0 !important;
                box-shadow: none !important;
            }

            .card-header {
                border: none !important;
            }
        </style>
    <?php
    }

    if ($_GET["action"] == "print") {
    ?>
        <style>
            body {
                max-width: 812px !important;
                margin: 0 auto !important;
                width: 100% !important;
                background-color: #ffffff !important;
            }

            img {
                display: none !important;
            }

            .heightDiv {
                height: 125px;
            }

            table {
                max-width: 700px !important;
                width: 100% !important;
                margin: 0 auto !important;
            }

            .card {
                margin-bottom: 0 !important;
                box-shadow: none !important;
            }

            .card-header {
                border: none !important;
            }
        </style>
    <?php
    }
    function dateRange($startDate, $endDate, $format = "Y-m-d")
    {
        $datesArray = [];
        $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
        for ($day = 0; $day < $total_days; $day++) {
            $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
        }
        return $datesArray;
    }

    
    
    $payMonth = $_GET['month'];
    $salary = floatval($_GET['salary']);
    $incentive = floatval($_GET['incentive']);
    $bonus = floatval($_GET['bonus']);
    $increment = floatval($_GET['increment']);
    $loan = floatval($_GET['loan']);
    $deduction = floatval($_GET['deduction']);
    $curdate = date("F d, Y", strtotime($_GET['curdate']));
    $note = $_GET['note'];
    $designation = $productClass->getUserDesignation($employeeId);
    $calculateTimeArray = [];
    $count_half = [];
    $totalWorkingHours = 0;
    $totalWorkingDays = 0;
    $total_apsent_allow = 0;
    $total_late = 0;
    $total_absent = 0;
    $user_working_hours = 0;
    $calculateTimeArray = [
        'Presents' => [],
        'Late' => [],
        'Time' => [],
        'id' => [],
        'Hours' => []
    ];

    $salary_from = date('Y-m-01', strtotime("$payMonth"));
    $salary_to = date('Y-m-t', strtotime("$payMonth"));

    $userDetail = $productClass->getUserDetailsById($employeeId);
    $country = $webClass->webUserInfoArray($userDetail, 'country');

    $dr = dateRange($salary_from, $salary_to);
    foreach ($dr as $date) {
        if ($webUserType === 1) {
            $sql = "SELECT au.acc_id, au.acc_name, s.checkintime, s.checkouttime, dl.in_time, dl.out_time, dl.date, dl.msg FROM staffs s JOIN daily_reports dl On dl.emp_id = s.userId JOIN accounts_user au ON au.acc_id = s.userId WHERE dl.date = '$date' AND au.acc_id = dl.emp_id GROUP BY au.acc_id ORDER BY au.acc_name";
        } else {
            $sql = "SELECT au.acc_id, au.acc_name, s.checkintime, s.checkouttime, dl.in_time, dl.out_time, dl.date, dl.msg FROM staffs s JOIN daily_reports dl On dl.emp_id = s.userId JOIN accounts_user au ON au.acc_id = s.userId JOIN accounts_user_detail aud ON au.acc_id = aud.id_user WHERE dl.date = '$date' AND au.acc_id = dl.emp_id AND aud.setting_name = 'country' AND aud.setting_val = '$country' GROUP BY au.acc_id ORDER BY au.acc_name";
        }

        $countDays = true;

        $da = date("D", strtotime($date));
        $date_e = explode(' ', $da);
        $date_sun = $date_e[0];
        $rows = $dbF->getRows($sql);
        foreach ($rows as $data) {

            $name = $data['acc_name'];
            $id = $data['acc_id'];

            if ($countDays) {
                if ($date_sun == 'Sat') {
                    $totalWorkingHours += 7;
                } else {
                    $totalWorkingHours += 9;
                }
                $totalWorkingDays++;
                $countDays = false;
            }

            $half = "";
            if (empty($data['out_time'])) {
                $data['out_time'] = "02:00 pm";
                $half = "<span style=\"color: red;\">**Missing!!</span>";
                $count_half[$name] = isset($count_half[$name]) ? $count_half[$name] + 1 : 1;
            }

            $data['in_time'] = !empty($data['in_time']) ? date("h:i a", strtotime($data['in_time'])) : null;
            $data['out_time'] = !empty($data['out_time']) ? date("h:i a", strtotime($data['out_time'])) : null;

            $morning_time = ($date_sun == 'Sat') ? '11:15 am' : "$data[checkintime]";
            $mor_time = date("H:i", strtotime($morning_time));
            $date3_morning = new DateTime($mor_time);
            $date3_hr = date("H", strtotime($morning_time));
            $date3_min = date("i", strtotime($morning_time));

            $morning_timeIn = $data["in_time"];
            $mor_timeIn = !empty($morning_timeIn) ? date("H:i", strtotime($morning_timeIn)) : "00:00";
            $date3_morningIn = new DateTime($mor_timeIn);
            if (!empty($morning_timeIn)) {
                $date3_hrIn = date("H", strtotime($morning_timeIn));
                $date3_minIn = date("i", strtotime($morning_timeIn));
            } else {
                $date3_hrIn = "00";
                $date3_minIn = "00";
            }

            $late_check = $date3_morningIn->diff($date3_morning);
            $late_hour = ($late_check->h < 10) ? '0' . $late_check->h : $late_check->h;
            $late_min = ($late_check->i < 10) ? '0' . $late_check->i : $late_check->i;
            $late_min_invert = $late_check->invert;

            if ($late_min_invert == 1) {
                if (!isset($calculateTimeArray['Late'][$name])) {
                    $calculateTimeArray['Late'][$name] = 0;
                }
                $calculateTimeArray['Late'][$name] += 1;
                $highlight = 'higlight';
            }

            $calculateTimeArray['id'][$name] = $id;

            $minutesT = (strtotime($date . " " . $data["out_time"]) - strtotime($date . " " . $data["in_time"])) / 60;
            $hours = floor($minutesT / 60);
            $minutes = $minutesT % 60;
            if ($minutesT > 0) {
                if (isset($calculateTimeArray['Time'][$name])) {
                    $tempM = $minutesT;
                    $tempH = intval($hours);
                    $tempC = floatval($tempH . '.' . $tempM);
                    $calculateTimeArray['Time'][$name] = $calculateTimeArray['Time'][$name] + $tempM;
                } else {
                    $tempM = $minutesT;
                    $tempH = intval($hours);
                    $tempC = floatval($tempH . '.' . $tempM);
                    $calculateTimeArray['Time'][$name] = $tempM;
                }
            } else {
                $calculateTimeArray['Hours'][$name] = 'NOT';
            }

            if (isset($calculateTimeArray['Presents'][$name])) {
                $calculateTimeArray['Presents'][$name] += 1;
            } else {
                $calculateTimeArray['Presents'][$name] = 1;
            }

            $name_time[$name][] = "<tr><td width=150>" . $name . "</td>
                <td width=200> $data[date]</td>
                <td width=200> &nbsp; $data[in_time] &nbsp; - &nbsp; $data[out_time]</td>
                <td width=150>" . $hours . ":" . $minutes . " Hrs $half </td>
                <td> &nbsp; &nbsp; $data[msg]</td>
        </tr>";
        }
    }

    $from = new DateTime($salary_from);
    $to = new DateTime($salary_to);
    $diff = $to->diff($from);

    $month = $diff->m;
    $day = $diff->d;
    $year = $diff->y;
    if ($year >= 1) {
        $temp = $year * 12;
        $month = $month + $temp;
    }

    if ($day > 10) {
        $month++;
    }

    if ($month <= 0) {
        $month = 1;
    }
    $_abset_days = 2 * $month;
    if (isset($calculateTimeArray['Presents']) && is_array($calculateTimeArray['Presents'])) {
        foreach ($calculateTimeArray['Presents'] as $key => $val) {
            $absent = $totalWorkingDays - $val;
            if ($absent >= $_abset_days) {
                $absent_hour = $_abset_days * 9;
            } else {
                $absent_hour = $absent * 9;
            }
            if (!isset($calculateTimeArray['Late'][$key])) {
                $calculateTimeArray['Late'][$key] = 0;
            }
            $late = $calculateTimeArray['Late'][$key];

            $time = isset($calculateTimeArray['Time'][$key]) ? $calculateTimeArray['Time'][$key] : 0;
            $hours = floor($time / 60);

            $pay_hours = $hours + $absent_hour;

            $minutes = $time % 60;
            if (isset($calculateTimeArray['Hours'][$key])) {
                $status = 'Not OK';
            } else {
                $status = "OK";
            }
            if (isset($count_half[$key])) {
                $half_count = $count_half[$key];
                $half_count = "<span style=\"color: red;\">**Missing = $half_count </span>";
            } else {
                $half_count = "";
            }

            $sql1 = "SELECT * FROM `accounts_user` WHERE `acc_id` = ?";
            $data1 = $dbF->getRow($sql1, [$employeeId]);

            if ($key == $data1['acc_name']) {
                $user_name = $key;
                $total_absent = $absent;
                $total_late = $late;
                $user_working_hours = $hours . ':' . $minutes;
            }
        }
    }
    $late_criteria = floor(($total_late / 3));
    $per_day_sal = $salary / 30;
    $late_absent = $late_criteria + $total_absent;
    $late_deduct = $late_absent * $per_day_sal;

    $total_late_deduct = number_format($late_criteria * $per_day_sal);
    $total_absent_deduct = number_format($total_absent * $per_day_sal);


    $total_earning = (int) $salary + (int) $incentive + (int) $bonus + (int) $increment;
    $total_deduct = (int) $loan + (int) $late_deduct + (int) $deduction;

    $net_sallary = $total_earning - $total_deduct;

    $f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
    ?>

    <div class="card rounded-0">
        <div class="heightDiv"></div>
        <img src="webImages/1.jpg" alt="" style="width: 100%;">
        <div class="card-header py-3">
            <div class="row align-items-center g-3">
                <div class="col-12 text-center">
                    <h4 class="mb-0 text-dark">Pay Salary Slip</h4>
                </div>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered border-dark my-4">
                <tr>
                    <th>Employee Name</th>
                    <td><?php echo $employeeName; ?></td>
                    <th>Total Working Days</th>
                    <td><?php echo $totalWorkingDays; ?></td>
                </tr>
                <tr>
                    <th>Employee ID</th>
                    <td><?php echo $employeeId; ?></td>
                    <th>Total Month Hours</th>
                    <td><?php echo $user_working_hours . ' / ' . $totalWorkingHours ?></td>
                </tr>
                <tr>
                    <th>Designation</th>
                    <td><?php echo $designation; ?></td>
                    <th>Total Late</th>
                    <td><?php echo $total_late; ?></td>
                </tr>
                <tr>
                    <th>Pay Month</th>
                    <td><?php echo $payMonth; ?></td>
                    <th>Total Absents</th>
                    <td><?php echo $total_absent; ?></td>
                </tr>
            </table>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered border-dark mb-4">
                <tr>
                    <th colspan="2">Earnings</th>
                    <th colspan="2">Deductions</th>
                </tr>
                <tr>
                    <td>Salary</td>
                    <td><?php echo number_format($salary); ?></td>
                    <td>Loan</td>
                    <td><?php echo number_format($loan); ?></td>
                </tr>
                <tr>
                    <td>Incentive Pay</td>
                    <td><?php echo number_format($incentive); ?></td>
                    <td>Total Late</td>
                    <td><?php echo $total_late_deduct; ?></td>
                </tr>
                <tr>
                    <td>Bonus</td>
                    <td><?php echo number_format($bonus); ?></td>
                    <td>Total Absents</td>
                    <td><?php echo $total_absent_deduct; ?></td>
                </tr>
                <tr>
                    <th>Total Earnings</th>
                    <td><?php echo number_format($total_earning); ?></td>
                    <th>Total Deduction(N/A)</th>
                    <td><?php echo number_format($total_deduct); ?></td>
                </tr>
                <?php $amnt_words = (int) $net_sallary; ?>
                <tr>
                    <th class="text-end" colspan="3">NET Salary</th>
                    <td colspan="2">Rs. <?php echo number_format($amnt_words); ?>/-</td>
                </tr>
                <tr>
                    <th class="text-end" colspan="2">Current NET Salary (In Words)</th>
                    <td colspan="2"><?php echo ucwords($f->format($amnt_words)) . ' Rupees Only'; ?></td>
                </tr>
            </table>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered border-dark mb-4">
                <tr>
                    <th colspan="2">Payment Information</th>
                    <th colspan="2">Notes</th>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="d-flex justify-content-between align-items-center"><span>Cash: </span><span>Rs.
                                <?php echo number_format($net_sallary); ?>/-</span></div>
                    </td>
                    <th rowspan="2"><?php echo $note; ?></th>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="d-flex justify-content-between align-items-center"><span>Date:
                            </span><span><?php echo $curdate; ?></span></div>
                    </td>
                </tr>
            </table>
        </div>

        <img src="webImages/2.jpg" alt="" style="width: 100%;">
    </div>
</body>

</html>