<?php
include "../config.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>";
}

$id = mysqli_real_escape_string($db, base64_decode($_GET['id']));
$d = mysqli_query($db, "SELECT 
        t2.name, t1.issue_date, t2.joining_date, t2.working_status_date, t3.designation_name as designation, t1.added_by, t1.approved_by
    FROM relieving_letter t1
    INNER JOIN (
        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 (DATE_FORMAT(CURRENT_DATE, '%Y-%m') BETWEEN applicable_from AND applicable_to)
        ) p2 ON p1.employee_id=p2.employee_id
    ) t2 ON t1.employee_id=t2.employee_id 
    INNER JOIN designations t3 ON t2.new_designation=t3.id
    WHERE COALESCE(t2.working_status_date,'')<>'' AND t1.id='$id'
    ");

// print_r($data);
if(mysqli_num_rows($d)==0){
    echo "<script>location.href='../404';</script>";
}
$data = mysqli_fetch_assoc($d);

####################################################################
$approved_by = !empty($data['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>";
}


?>
<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>Relieving Letter</title>
    <style>
        * {
            font-size: 13px;
        }

        @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=" mt-0"><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:10rem" alt=""></span>
                            <div style="margin-left: 1rem;">
                                <h3 class="fw-bold text-right mb-0 mt-3">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>
                                <p class="text-right mb-0">CIN No: U72900DL2020PTC369688<br>

                                </p>
                            </div>
                        </div>
                    </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 $data['issue_date']; ?></td>

                            </tr>
                        </table>

                        <h2 class="mt-2 text-center mb-3">Relieving Letter</h2> <br>

                        <h3 class="mt-2 text-center mb-3" style="text-decoration: underline;">TO WHOMSOEVER IT MAY CONCERN</h3> <br>

                        <p style="font-size:16px;">This is to certify that <strong><?php echo $data['name']; ?></strong> has been an employee of Jobaaj Group (A wholly-owned brand of Nishtya Infotech Pvt. Ltd.) from <strong><?php echo date("M Y", strtotime($data['joining_date'])); ?></strong> to <strong><?php echo date("M Y", strtotime($data['working_status_date'])); ?></strong>. The request for resignation had been accepted, and the employee stands relieved from the services of the company. At the time of resignation, the employee was in the grade of <strong><?php echo $data['designation']; ?></strong>.
                        </p>
                        <br>
                        <p style="font-size:16px;">We wish the employee success in all future endeavors.</p>
                        <br>
                        <br>
                        <p style="font-size:16px;">Sincerely, <br> For Nishtya Infotech Pvt. Ltd.</p><br><br>
                        <div style="font-size:16px;">
                            <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>
                    </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>