<?php
include "../config.php";
require_once "../fun/money_format.php";
$user_name = $_SESSION['user_name'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];

if (!isset($_SESSION['emp_id'])) {
    echo "<script>location.href='../index';</script>";
}

if ($user_role != 0) {
    if (isset($_GET['slip_id'])) {
        $ex = mysqli_num_rows(mysqli_query($db, "select * from users where employee_id='$_GET[slip_id]' and leader='$emp_id'"));
        if ($ex == 0 && $_GET['slip_id'] != $emp_id) {
            echo "<script>location.href = '../404'</script>";
        }
    }
}

$id = $_GET['slip_id'];
$firstDayLast = $_GET['from'];
$lastDayLast = $_GET['to'];

$month = date("Y-m", strtotime($firstDayLast));
$vDate = date("Y-m-d");
$slipRequest = mysqli_fetch_assoc(mysqli_query($db, "select * from request_slip where request_id='$emp_id' and slip_id='$id' and month='$month' order by id desc limit 1 "));
if(empty($slipRequest)){
    echo "<script>alert('Please Request First for Pay Slip!');</script>";
    $wm = date("Y-m", strtotime($firstDayLast));
    echo "<script>location.href='../salary?which_month=$wm';</script>";
}

// if ((!empty($slipRequest) && $slipRequest['status'] == 1 && $slipRequest['validity'] >= $vDate) || ($user_role == 0)) {
// } else if (!empty($slipRequest) && $slipRequest['status'] == 0) {
//     echo "<script>alert('Your Request Send Yet but not accepted for Pay Slip!');</script>";
//     $wm = date("Y-m", strtotime($firstDayLast));
//     echo "<script>location.href='../salary?which_month=$wm';</script>";
// } else if (!empty($slipRequest) && $slipRequest['status'] == 2 && $slipRequest['validity'] >= $vDate) {
//     echo "<script>alert('Your Request Rejected for Pay Slip!');</script>";
//     $wm = date("Y-m", strtotime($firstDayLast));
//     echo "<script>location.href='../salary?which_month=$wm';</script>";
// } else {
//     echo "<script>alert('Please Request First for Pay Slip!');</script>";
//     $wm = date("Y-m", strtotime($firstDayLast));
//     echo "<script>location.href='../salary?which_month=$wm';</script>";
// }

function AmountInWords(float $amount)
{
    $amount_after_decimal = round($amount - ($num = floor($amount)), 2) * 100;
    // Check if there is any number after decimal
    $amt_hundred = null;
    $count_length = strlen($num);
    $x = 0;
    $string = array();
    $change_words = array(
        0 => '', 1 => 'One', 2 => 'Two',
        3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six',
        7 => 'Seven', 8 => 'Eight', 9 => 'Nine',
        10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve',
        13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen',
        16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen',
        19 => 'Nineteen', 20 => 'Twenty', 30 => 'Thirty',
        40 => 'Forty', 50 => 'Fifty', 60 => 'Sixty',
        70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninety'
    );
    $here_digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');

    while ($x < $count_length) {
        $get_divider = ($x == 2) ? 10 : 100;
        $amount = floor($num % $get_divider);
        $num = floor($num / $get_divider);
        $x += $get_divider == 10 ? 1 : 2;
        if ($amount) {
            $add_plural = (($counter = count($string)) && $amount > 9) ? 's' : null;
            $amt_hundred = ($counter == 1 && $string[0]) ? ' and ' : null;
            $string[] = ($amount < 21) ? $change_words[$amount] . ' ' . $here_digits[$counter] . $add_plural . ' 
                ' . $amt_hundred : $change_words[floor($amount / 10) * 10] . ' ' . $change_words[$amount % 10] . ' 
                ' . $here_digits[$counter] . $add_plural . ' ' . $amt_hundred;
        } else {
            $string[] = null;
        }
    }
    $implode_to_Rupees = implode('', array_reverse($string));
    $get_paise = ($amount_after_decimal > 0) ? "And " . ($change_words[$amount_after_decimal / 10] . "
            " . $change_words[$amount_after_decimal % 10]) . ' Paise' : '';
    return ($implode_to_Rupees ? $implode_to_Rupees . 'Rupees ' : '') . $get_paise;
}

// $user = mysqli_fetch_assoc(mysqli_query($db, "select u.employee_id, u.name, u.designation, u.department, u.joining_date, u.working_status_date, u.pan_no, u.account_no, u.esi_no, u.uan_no from users as u JOIN attendance as a on u.employee_id=a.employee_id where u.employee_id='$id' and (str_to_date(a.which_month,'%M %d %Y')>='$firstDayLast' and str_to_date(a.which_month,'%M %d %Y')<='$lastDayLast') group by u.id "));

$join_month = date("Y-m", strtotime($firstDayLast));
$wsDate = date("Y-m", strtotime($lastDayLast));
$getMonth = date("Y-m", strtotime($firstDayLast));
$query = "SELECT u.employee_id, u.name, d.designation_name, u.department, u.joining_date, u.working_status_date, u.pan_no, u.account_no, u.esi_no, u.uan_no, '$firstDayLast' as firstDayLast, '$lastDayLast' as lastDayLast
        FROM (
            SELECT 
                p1.*,
                (CASE
                    WHEN COALESCE(p2.promote_to,'')<>'' THEN p2.promote_to
                    ELSE p1.designation
                END) AS new_designation
            FROM users p1
            LEFT JOIN (
                SELECT
                    *
                FROM (
                    SELECT 
                        id,
                        employee_id, 
                        promote_to, 
                        applicable_from, 
                        (CASE 
                        WHEN COALESCE(applicable_to,'')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m')
                        ELSE applicable_to
                        END) as applicable_to 
                    FROM promotions
                ) final_promotions
                WHERE ('$getMonth' BETWEEN applicable_from AND applicable_to)
            ) p2 ON p1.employee_id=p2.employee_id
        ) as u 
        LEFT JOIN designations AS d ON d.id=u.new_designation
        JOIN attendance AS a ON u.employee_id = a.employee_id 
        WHERE u.employee_id='$id' 
        AND (STR_TO_DATE(a.which_month, '%M %d %Y') BETWEEN '$firstDayLast' AND '$lastDayLast')
        AND (COALESCE(u.joining_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(u.joining_date, '%Y-%m-%d'),'%Y-%m') <= '$join_month')
        AND (COALESCE(u.working_status_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(u.working_status_date, '%Y-%m-%d'),'%Y-%m') >= '$wsDate')
        GROUP BY u.id, d.designation_name
        ORDER BY u.id ASC";

$user = mysqli_fetch_assoc(mysqli_query($db, $query));

$newFirstDayLast = $firstDayLast;
$newLastDayLast = $lastDayLast;

require_once "../salaryCodeCalculate.php";
require_once('../salaryCode.php');

$s_code = salaryCode($user, $firstDayLast, $firstDayLast);

$netCTC = $s_code['monthSalaryDetails'];
$leaves = $s_code['leaves'];
// echo "<pre>";
// print_r($s_code);
$netPayable = array_filter(
        $s_code['working_salary'],
        function ($key) {
            return !in_array($key, ['ESIC Employer Share @ 3.25% of (A)', 'EPF Employer Share']);
        },
        ARRAY_FILTER_USE_KEY
    );
$deduction = $s_code['deduction'];
$final_salary = $s_code['final_salary'];
$total_netPayable = array_sum($netPayable);
$total_deduction = array_sum($deduction);

$totalLeave = $leaves['Total Leaves']??'0';
$totalWorkingDay = $leaves['Total Working Days'];
$payableSalary = $final_salary['Payable Salary'];
$bonus = $final_salary['Bonus'];
$incentive = $final_salary['Incentive'];
$working_day_salary = $total_netPayable + $bonus + $incentive;

$payableSalary = $payableSalary + $bonus + $incentive;


?>
<!doctype html>
<html lang=" en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Favicon -->
    <link rel="shortcut icon" href="https://cdn.nishtyainfotech.com/content/jobaaj/assets/img/jobaaj-favicon.ico">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Salary Slip - Jobaaj</title>
    <style>
        body {
            -webkit-print-color-adjust: exact;
        }

        .font-size-14 {
            font-size: 14px;
        }

        .font-size-12 {
            font-size: 12px;
        }
    </style>
</head>

<body>
    <div>

        <div class="border border-1 p-0 m-0">

            <div class="row py-0 align-items-center">
                <div class="col-6 p-0 m-0" style="padding:0px 20px !important;">
                    <h4>Nishtya Infotech Pvt. Ltd.</h4>
                    <p class="font-size-12 m-0" style="line-height:0.875rem;margin-bottom:0;">
                        CIN No- U72900DL2020PTC369688<br>
                        379, Vardhman Grand Plaza, Plot No.7 Manglam Place,<br>
                        Sector-3, Rohini, New Delhi- 110085 <br>
                    </p>
                </div>
                <div class="col-6 p-0 m-0 text-end">
                    <img src="nishtya_transparent.png" alt="" style="width:160px;">
                </div>
            </div>
            <div class="border-top border-bottom p-0 m-0">
                <h4 class="text-center" style="padding: 10px 0px 10px 0px;font-weight: bold;">Payslip for the month of <?php echo date("F", strtotime($firstDayLast)); ?>, <?php echo date("Y", strtotime($firstDayLast)); ?></h4>
            </div>
            <div class="border-top border-bottom p-0 m-0">
                <div class="row py-0 pb-3">
                    <h5 class="mb-3">EMPLOYEE PAY SUMMARY</h5>
                    <div class="col-6 font-size-12 pe-0 mt-2">
                        <table width="100%" border="0" cellpadding="0" cellspacing="0">

                            <tr>
                                <td class="ps-1">Employee Name</td>
                                <td class="fw-bold">: <?php echo $user['name']; ?></td>
                            </tr>
                            <tr>
                                <td class="ps-1">Employee No.</td>
                                <td class="fw-bold">: <?php echo $user['employee_id']; ?> </td>
                            </tr>
                            <tr>
                                <td class="ps-1">Date of Joining</td>
                                <td class="fw-bold">: <?php echo (!empty($user['joining_date'])) ? date("d M Y", strtotime($user['joining_date'])) : ''; ?></td>
                            </tr>
                            <tr>
                                <td class="ps-1">Designation</td>
                                <td class="fw-bold">: <?php echo $user['designation_name'] ?></td>
                            </tr>

                            <tr>
                                <td class="ps-1">Paid Days</td>
                                <td class="fw-bold">: <?php echo $totalWorkingDay; ?></td>
                            </tr>
                            <tr>
                                <td class="ps-1">Loss Of Pay</td>
                                <td class="fw-bold">: <?php echo $totalLeave; ?> Days</td>
                            </tr>

                        </table>
                    </div>
                    <div class="col-6 font-size-12 ps-0">
                        <table width="100%" border="0" cellpadding="0" cellspacing="0">
                            <tr>
                                <td class="ps-1">Location</td>
                                <td class="fw-bold">: Agra-UP</td>
                            </tr>
                            <?php if(!empty($user['pan_no'])){ ?>
                            <tr>
                                <td class="ps-1">PAN No.</td>
                                <td class="fw-bold">: <?php echo $user['pan_no']; ?> </td>
                            </tr>
                            <?php } ?>
                            <?php if(!empty($user['account_no'])){ ?>
                            <tr>
                                <td class="ps-1">Bank A/C No.</td>
                                <td class="fw-bold">: <?php echo $user['account_no']; ?> </td>
                            </tr>
                            <?php } ?>
                            <?php if(!empty($user['esi_no'])){ ?>
                            <tr>
                                <td class="ps-1">ESIC No.</td>
                                <td class="fw-bold">: <?php echo $user['esi_no']; ?> </td>
                            </tr>
                            <?php } ?>
                            <?php if(!empty($user['uan_no'])){ ?>
                            <tr>
                                <td class="ps-1">UAN No.</td>
                                <td class="fw-bold">: <?php echo $user['uan_no']; ?> </td>
                            </tr>
                            <?php } ?>


                        </table>
                    </div>
                </div>
            </div>

            <div class="border-top border-bottom p-0">
                <div class="row py-0">
                    <!-- salary detail -->
                    <div class="col-3 font-size-12 pe-0" style="position: relative;">
                        <div class="border-top border-bottom p-0 m-0" style="background-color:#f2f2f3; height:37px;">
                            <p class="m-0 py-1 ps-1 fw-bolder">Earnings</p>
                        </div>

                        <div class="pt-1 pb-5">
                            <p class="font-size-12 py-1 ps-1">
                                <?php
                                    $keys = array_keys($netPayable);
                                    foreach($keys as $k){
                                        echo $k."<br>";
                                    }
                                    if(!empty($bonus))
                                        echo "Bonus<br>";
                                    if(!empty($incentive))
                                        echo "Incentive<br>";
                                ?>
                            </p>
                        </div>
                        <div class="border-top border-bottom p-0 mt-3" style="position: absolute;bottom: 0;width: 100%;">
                            <p class="font-size-12 py-1 ps-1 fw-bolder">Gross Earnings</p>
                        </div>
                    </div>
                    <div class="col-3 font-size-12 border-end px-0" style="position: relative;">
                        <div class="border-top border-bottom p-0 m-0" style="background-color:#f2f2f3; height:37px;">
                            <p class="m-0 py-1 ps-1 fw-bolder">Amount</p>
                        </div>

                        <div class="ps-1 pt-1 pb-5">
                            <p class="font-size-12 ps-1 py-1">
                                <?php
                                    foreach($netPayable as $k => $np){
                                        echo "&#8377;&nbsp;".IND_money_format($np)."<br>";
                                    }
                                    if(!empty($bonus))
                                        echo "&#8377;&nbsp;".IND_money_format($bonus)."<br>";
                                    if(!empty($incentive))
                                        echo "&#8377;&nbsp;".IND_money_format($incentive)."<br>";
                                ?>
                               
                            </p>
                        </div>
                        <div class="border-top border-bottom p-0 mt-3" style="position: absolute;bottom: 0;width: 100%;">
                            <p class="font-size-12 py-1 ps-1 fw-bolder">&#8377;&nbsp;<?php echo IND_money_format($working_day_salary) ?></p>
                        </div>
                    </div>

                    <!-- deduction -->
                    <div class="col-3 font-size-12 px-0" style="position: relative;">
                        <div class="border-top border-bottom p-0 m-0" style="background-color:#f2f2f3; height:37px;">
                            <p class="m-0 py-1 ps-1 fw-bolder">Deduction</p>
                        </div>

                        <div class="pt-1 pb-5">
                            <p class="font-size-12 py-1 ps-1">
                                <?php
                                    if(!empty($netPayable['EPF Employer Share'])){
                                        echo "EPF Employer Share<br>";
                                    }
                                    $keys = array_keys($deduction);
                                    foreach($keys as $k){
                                        echo $k."<br>";
                                    }
                                ?>
                            </p>
                        </div>
                        <div class="border-top border-bottom p-0 mt-3" style="position: absolute;bottom: 0;width: 100%;">
                            <p class="font-size-12 py-1 ps-1" style="font-weight:bold;">Total Deductions</p>
                        </div>
                    </div>
                    <div class="col-3 font-size-12 border-end px-0" style="position: relative;">
                        <div class="border-top border-bottom p-0 m-0" style="background-color:#f2f2f3; height:37px;">
                            <p class="m-0 py-1 ps-1 fw-bolder">Amount</p>
                        </div>

                        <div class="pt-1 pb-5">
                            <p class="font-size-12 py-1 ps-1">
                                <?php
                                    if(!empty($netPayable['EPF Employer Share'])){
                                        echo "&#8377;&nbsp;".IND_money_format($netPayable['EPF Employer Share'])."<br>";
                                    }
                                    foreach($deduction as $d){
                                        echo "&#8377;&nbsp;".IND_money_format($d)."<br>";
                                    }
                                ?>
                            </p>
                        </div>
                        <div class="border-top border-bottom p-0 mt-3" style="position: absolute;bottom: 0;width: 100%;">
                            <p class="font-size-12 py-1 ps-1" style="font-weight:bold;">&#8377;&nbsp;<?php echo IND_money_format($total_deduction); ?></p>
                        </div>
                    </div>

                </div>
            </div>

            <div class="border-top border-bottom p-0">
                <div class="row py-0">
                    <div class="col-6 font-size-12 pe-0" style="height:10rem;">
                        <div class="border-top border-start border-end border-bottom p-0 m-0" style="height:30%;">
                        </div>
                        <div class="border-start border-end border-bottom p-0 m-0" style="height:70%;">
                        </div>
                    </div>
                    <div class="col-6 border-start border-end font-size-12 pe-0" style="height:10rem;">
                    </div>
                </div>
            </div>

            <div class="border-top border-bottom p-0" style="background-color:#f2f2f3">
                <p class="text-center fw-bolder fs-4"><span>Total Net Payable &#8377;&nbsp;<?php echo IND_money_format($payableSalary) ?></span> <span>(<?php echo AmountInWords($payableSalary); ?>)</span></p>
                <p class="text-center fw-bold" style="color:gray;">Total Net Payable = (Gross Earnings - Total Deductions)</p>
            </div>
            <p class="text-center font-size-14" style="color:gray;">-This is Computer Generated slip does not Required Any Signature.-</p>

        </div>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script>
        window.print();
    </script>
</body>

</html>