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

if (!isset($_SESSION['emp_id'])) {
    echo "<script>location.href='../index';</script>";
}
// if($_SESSION['user_role']!=0){
//     echo "<script>location.href='../404';</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;
}

$id = mysqli_real_escape_string($db, base64_decode($_GET['id']));
$sql = "SELECT 
    t1.employee_id,
    t1.approved_by, 
    t1.added_by,
    t1.issue_date,
    t1.level,
    t1.incentive_term,

    t2.name,
    t2.notice_period,
    t2.joining_date,

    t3.fixed,
    t3.add_on,
    t3.deduction,
    t3.ctc as new_ctc,
    t3.revision_start_date as revision_date,

    t4.designation_name as position
FROM appraisal_letter t1
INNER JOIN users t2 ON t2.employee_id=t1.employee_id
INNER JOIN employee_salary t3 ON t3.id=t1.salary_id
INNER JOIN designations t4 ON t4.id=t2.designation
WHERE t1.id='$id'";
$data = mysqli_fetch_assoc(mysqli_query($db, $sql));

$first_name = explode(' ', $data['name'])[0];
$last_name = explode(' ', $data['name'])[1];

####################################################################
$approved_by = json_decode($data['approved_by'], true);
$is_all_approved = false;

$approvals = !empty($data['approved_by']) ? json_decode($data['approved_by'], true) : [];
if (!empty($approvals)) {
    $lastSubarray = end($approvals);
    $lastStatuses = is_array($lastSubarray) ? array_column($lastSubarray, 'status') : [];
} else {
    $lastStatuses = [];
}
$is_all_approved = count(array_filter($lastStatuses, fn($val) => $val == 1)) === count($lastStatuses);
if ($user_role!=0 && (empty($lastStatuses) || !$is_all_approved)){
    // add watermark
    echo "<style>
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            width: fit-content;
            transform: translate(-50%, -50%) rotate(45deg);
            font-size: 60px;
            display: none;
            color: rgba(0, 0, 0, 0.2);
            pointer-events: none;
            display: none;
            mix-blend-mode: darken;
        }
    </style>

    <div class=\"watermark\"><img src='{$url}letters/unathorized.png'></div>

    <script>
        // JavaScript to control printing
        window.onload = function() {
            document.querySelector('.watermark').style.display = 'none'; // Hide watermark on the screen

            // Show watermark on every printed page
            window.onbeforeprint = function() {
                document.querySelector('.watermark').style.display = 'block';
            };

            // Hide watermark after printing is done
            window.onafterprint = function() {
                document.querySelector('.watermark').style.display = 'none';
            };
        };
    </script>";
}
####################################################################
if(($_SESSION['emp_id']=='NI406' && !$is_all_approved)){
    echo "<script>location.href='../404';</script>";
}

if ($_SESSION['emp_id']!='NI406' && ($_SESSION['user_role'] != 0 && $data['added_by']!=$_SESSION['emp_id'] && !isset($lastSubarray[$_SESSION['emp_id']]) )) {
    echo "<script>location.href='../404';</script>";
}

$fixed = json_decode($data['fixed'], true);

$total_per_annum = array_sum(array_column($fixed, 'yearly_amount'));
$total_per_month = $total_per_annum / 12;

$for_deduction_month = $total_per_month;
$for_deduction_annum = $total_per_annum;

$addOn = json_decode($data['add_on'],true);
$deduction = json_decode($data['deduction'],true);



// fetch old salary by revistion date
$old_salary = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM employee_salary WHERE employee_id='$data[employee_id]' AND revision_end_date='$data[revision_date]' ORDER BY id DESC LIMIT 1"));
$old_ctc = $old_salary['ctc'];
$new_ctc = $data['new_ctc'];


?>

<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="https://www.jobaaj.com/images/">

    <!-- 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">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css">
    <title>Appraisal Letter</title>
    <style>
        * {
            font-size: 14px;
        }

        @media print {
            @page {
                margin-left: 0.6in;
                margin-right: 0.6in;
                margin-top: 0.1in;
                margin-bottom: 0.2in;
            }
        }

        table.report-container {
            page-break-after: always;
        }

        thead.report-header {
            display: table-header-group;
        }

        tfoot.report-footer {
            display: table-footer-group;
        }
    </style>

</head>

<body>



    <table class="report-container container">

        <thead class="report-header">
            <tr>
                <th class="report-header-cell p-1 mb-0">
                    <div class="header-info m-3 mb-0">
                        <div class="d-flex justify-content-between mb-0">
                            <!-- <div class=""> <i class="fa-solid fa-phone"></i>&nbsp;+91 73035 12500</div> -->
                            <div class=""><i class="fa-sharp fa-solid fa-globe"></i>&nbsp;www.jobaajgroup.com</div>
                            <div class=""><i class="fa-solid fa-envelope"></i>&nbsp;contact@jobaaj.com</div>
                        </div>
                        <div class="d-flex flex-row">
                            <span><img src="<?php echo $url; ?>letters/jobaaj_transparent.png" style="width:8rem" alt=""></span>
                            <div style="margin-left: 1rem;">
                            <h3 class="fw-bold mb-1">NISHTYA INFOTECH PVT. LTD </h3>
                                <p class="text-right mb-0 mt-1"><i class="bi bi-geo-alt-fill"></i>&nbsp; Reg: 379, Vardhman Grand Plaza, Plot No.7, Manglam Place, Sector-3, Rohini New Delhi- 110085 <br></p>
                                <p class="text-right mb-0 mt-1"><i class="bi bi-geo-alt-fill"></i>&nbsp; Corp Office: Office no. 810 & 811, 8th Floor, Corporate Park, Sanjay Palace, Civil Lines, Agra, Uttar Pradesh 282002<br></p>
                            </div>
                            <!-- <span><img src="<?php echo $url; ?>letters/1.png" style="width:6rem;margin-left:8rem;" alt=""></span> -->
                        </div>
                    </div>
                </th>
            </tr>
        </thead>

        <tbody class="report-content">
            <tr>
                <td class="report-content-cell">
                    <div class="main p-3 pt-0">

                        <table class="mt-3">

                            <tr>
                                <td><strong>Date:</strong> <?php echo date("d M Y", strtotime($data['issue_date'])); ?></td>

                            </tr>
                        </table>

                        <h1 class="mt-2 text-center mb-3"><u>Letter Of Appraisal</u></h1> <br>


                        <p>Dear <?php echo $first_name; ?>, <br><br>
                            We would like to extend this appraisal letter for your dedication and contribution to the organization, Your
                            performance for this year has exceeded the company's expectations, It proves your commitment towards Nishtya
                            Infotech. We are pleased to appraise your annual CTC from <strong>Rs. <?php echo IND_money_format($old_ctc); ?></strong> to <strong>Rs. <?php echo IND_money_format($new_ctc); ?></strong> (i.e <strong><?php echo round((($new_ctc-$old_ctc)/$old_ctc)*100,2); ?>%</strong> Increment to CTC), please refer to the attached Annexure I for detailed CTC computation. This revision is effective from <strong><?php echo date("d M Y",strtotime($data['revision_date'])); ?></strong>. 
                            <br><br>
                            The revised compensation package has been customized for you taking into consideration your performance,
                            company policies, and related factors. <br>Your compensation package is unique to you and not for comparison with other employees of the company.<br><br>
                            Note: After this appraisal in case you decide to leave the service of the organization, you will be required to give
                            notice as per company policy. As per the revised policy, your notice period is <strong><?php echo $data['notice_period']; ?> days</strong>. All the other terms and
                            conditions of your employment remain unchanged. <br><br>We at Nishtya Infotech hope that you will continue your work with the same dedication and meet all the challenges
                            in the upcoming year. We have the privilege to have you with us and personally congratulate you on your
                            contribution and look forward to your participation in the growth of the company. <br><br>
                            Best wishes for a long, happy, and rewarding career with us. <br><br>
                        </p> <br>
                        Sincerely, <br>
                        For Nishtya Infotech Pvt. Ltd. <br>


                        <span><img src="<?php echo $url; ?>letters/akhilesh_sign.jpeg" style="width:8rem; mix-blend-mode: hard-light;" alt=""></span><br>
                        Akhilesh Kumar Saha <br>
                        Authorized Signatory <br>
                        Snr. Finance Manager <br>
                        <strong>Nishtya Infotech Pvt. Ltd.</strong>
                    </div>
                </td>
            </tr>
        </tbody>
        
    </table>
    
    <table class="report-container container">
        <thead class="report-header">
            <tr>
                <th class="report-header-cell p-1 mb-0">
                    <div class="header-info m-3 mb-0">
                        <div class="d-flex justify-content-between mb-0">
                            <!-- <div class=""> <i class="fa-solid fa-phone"></i>&nbsp;+91 73035 12500</div> -->
                            <div class=""><i class="fa-sharp fa-solid fa-globe"></i>&nbsp;www.jobaajgroup.com</div>
                            <div class=""><i class="fa-solid fa-envelope"></i>&nbsp;contact@jobaaj.com</div>
                        </div>
                        <div class="d-flex flex-row">
                            <span><img src="<?php echo $url; ?>letters/jobaaj_transparent.png" style="width:8rem" alt=""></span>
                            <div style="margin-left: 1rem;">
                            <p class="h1 fw-bold mb-1">NISHTYA INFOTECH PVT. LTD </p>
                                <p class="text-right mb-0 mt-1"><i class="bi bi-geo-alt-fill"></i>&nbsp; Reg: 379, Vardhman Grand Plaza, Plot No.7, Manglam Place, Sector-3, Rohini New Delhi- 110085 <br></p>
                                <p class="text-right mb-0 mt-1"><i class="bi bi-geo-alt-fill"></i>&nbsp; Corp Office: Office no. 810 & 811, 8th Floor, Corporate Park, Sanjay Palace, Civil Lines, Agra, Uttar Pradesh 282002<br></p>
                            </div>
                            <!-- <span><img src="<?php echo $url; ?>letters/1.png" style="width:6rem;margin-left:8rem;" alt=""></span> -->
                        </div>
                    </div>
                </th>
            </tr>
        </thead>
        
        <tbody class="report-content">
            <tr>
                <td class="report-content-cell">
                <div class="main p-3 pt-0">
                        <h6 style="text-align: center;">Annexure I</h6>
                        <table>
                            <tr>
                                <th>Name of Employee</th>
                                <td> : <?php echo $data['name']; ?></td>

                            </tr>
                            <tr>
                                <th>Designation</th>
                                <td> : <?php echo $data['position']; ?></td>
                            </tr>
                            <tr>
                                <th>Date of Joining</th>
                                <td class="mb-0"> : <?php echo date("d-M-Y", strtotime($data['joining_date'])); ?></td>
                            </tr>
                            <tr>
                                <th>Location</th>
                                <td> : Agra</td>

                            </tr>
                            <tr>
                                <th>Level</th>
                                <td> : <?php echo $data['level']; ?></td>
                            </tr>
                        </table>

                        <table class="mt-2" style="width:100%; border: 1px solid black;">

                            <tr>
                                <th style="border: 1px solid black;border-collapse: collapse;text-align: center;">Particular/Component</th>
                                <th style="border: 1px solid black;border-collapse: collapse;text-align: center;">Per Month &#8377;</th>
                                <th style="border: 1px solid black;border-collapse: collapse;text-align: center;">Per Annum &#8377;</th>
                            </tr>

                            <tr>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: left;font-weight:bold;">Fixed Pay</td>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"></td>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"></td>
                            </tr>
                            <?php foreach ($fixed as $key => $value) { ?>
                                <tr>
                                    <td style="border: 1px solid black;border-collapse: collapse;text-align: left;">&nbsp;&nbsp;<?php echo $value['title'] ?></td>
                                    <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"><?php echo IND_money_format(round($value['yearly_amount'] / 12)); ?> </td>
                                    <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"><?php echo IND_money_format($value['yearly_amount']); ?></td>
                                </tr>
                            <?php } ?>

                           
                            <tr>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: left;font-weight:bold;">Total Fixed Salary (A)</td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"><?php echo IND_money_format($total_per_month); ?></td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"><?php echo IND_money_format($total_per_annum); ?></td>
                            </tr>
                            <?php
                            $addOn_month = 0;
                            $addOn_annum = 0;
                            foreach ($addOn as $key => $value) {
                            ?>
                                <tr>
                                <?php if (strtolower($value['title']) == "variable pay") { ?>
                                    <td style="border: 1px solid black;border-collapse: collapse; text-align: left; font-weight:bold;"><?php echo $value['title']; ?></td>
                                <?php } else { ?>
                                    <td style="border: 1px solid black;border-collapse: collapse; text-align: left;">&nbsp;&nbsp;<?php echo $value['title']; ?></td>
                                <?php } ?>

                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"> 
                                    <?php echo IND_money_format(round($value['yearly_amount']/12)); ?>
                                </td>

                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;">
                                <?php echo IND_money_format(round($value['yearly_amount'])); ?>
                                </td>
                                </tr>
                            <?php 
                                $total_per_month += round($value['yearly_amount']/12);
                                $total_per_annum += round($value['yearly_amount']);
                        } ?>

                            <tr>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: left;font-weight:bold;">Total Gross CTC* (Excluding Incentives)</td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"> <?php echo IND_money_format($total_per_month); ?></td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"><?php  echo IND_money_format($total_per_annum); ?></td>
                            </tr>

                            <?php if(count($deduction)>0){ ?>
                            <tr>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: left;font-weight:bold;">Deduction (B)</td>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"></td>
                                <td style="border: 1px solid black;border-collapse: collapse;text-align: center;"></td>
                            </tr>
                            <?php
                            }
                            $deduction_month = 0;
                            $deduction_annum = 0;
                            foreach($deduction as $key => $value){
                            ?>
                                <tr>
                                    <td style="border: 1px solid black;border-collapse: collapse; text-align: left;">&nbsp;&nbsp;<?php echo $value['title']; ?></td>
                                    <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"> <?php echo IND_money_format(round($value['yearly_amount']/12)); ?></td>
                                    <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"><?php echo IND_money_format($value['yearly_amount']); ?></td>

                                    <?php 
                                        $deduction_month += round($value['yearly_amount']/12);
                                        $deduction_annum += $value['yearly_amount'];
                                    ?>
                                </tr>
                            <?php } ?>

                            <tr>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: left;font-weight:bold">
                                <?php if($deduction_month!=0)  {?>
                                    Net Pay (A-B)
                                <?php } else { ?>
                                    Net Pay (A)
                                <?php } ?>
                                </td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"> <?php echo IND_money_format($for_deduction_month -  $deduction_month); ?></td>
                                <td style="border: 1px solid black;border-collapse: collapse; text-align: center;"><?php echo IND_money_format($for_deduction_annum -  $deduction_annum); ?></td>
                            </tr>
                        </table>

                        <?php if (!empty($data['incentive_term'])) { ?>
                            <h6 class="mt-2 mb-0">Performance Incentive^^</h6>
                            <span class="mb-0" id="spaceDIV"><?php echo $data['incentive_term']; ?></span>
                        <?php } ?>

                        
                        <h6 class="mt-2 mb-0">Total CTC*</h6>
                        <ul>
                            <li> Total Cost to Company is a total of Gross Annual Fixed and Annual Variable Pay plus Annual Bonus at 100%
                                payout as per the clause mentioned above.</li>
                            <li> PF,ESI, Income Tax, and Local Tax will be deducted as per the prevailing rules.(If applicable) <br>
                                For Nishtya Infotech Pvt. Ltd.</li>
                        </ul>

                        <span><img src="<?php echo $url; ?>letters/akhilesh_sign.jpeg" style="width:8rem; mix-blend-mode: hard-light;" alt=""></span><br>
                        Akhilesh Kumar Saha <br>
                        Authorized Signatory <br>
                        Snr. Finance Manager <br>
                        <strong>Nishtya Infotech Pvt. Ltd.</strong>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>

</body>
<script>
    window.print();
</script>
<script>
    document.addEventListener("contextmenu", (event) => {
        event.preventDefault();
    });
    document.addEventListener('keydown', function(e) {
        // F12
        if (e.keyCode === 123) {
            e.preventDefault();
        }

        // Block Ctrl+Shift+I / J / C
        if (e.ctrlKey && e.shiftKey && ['I', 'i', 'J', 'j', 'C', 'c'].includes(e.key)) {
            e.preventDefault();
            return false;
        }

        // Block Ctrl+U
        if (e.ctrlKey && ['U', 'u'].includes(e.key)) {
            e.preventDefault();
            return false;
        }
    });

    setInterval(() => {
        const before = new Date().getTime();
        debugger;
        const after = new Date().getTime();
        if (after - before > 100) {
            document.body.innerHTML = "<h1 style='color:red;text-align:center;margin-top:20%'>Unauthorized Access Detected. Closing Page...</h1>";
            setTimeout(() => {
                window.location.href = "about:blank"; // or just hang the page
            }, 2000);
        }
    }, 100);
</script>
</html>