<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

if (isset($_GET['delete_profile'])) {

    // fetch old image for delete
    $oldFile = mysqli_fetch_assoc(mysqli_query($db, "select * from users where employee_id='$emp_id' "));
    $oldImage = $oldFile['image'];

    $q = mysqli_query($db, "update users set image='' where employee_id='$emp_id'");
    if ($q) {
        // delete old image
        // if ($oldImage != '') {
        //     unlink("images/$oldImage");
        // }
        unset($_SESSION['image']);
        echo "<script>location.href='myProfile';</script>";
    }
}

// use in => all_users_get.php, myProfile.php, exportEmployees.php
$users_sql = <<<EOT
SELECT * FROM
(
    SELECT
        t1.*,
        t2.name AS l_name,
        t3.department_name,
        t4.designation_name
    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 (DATE_FORMAT(CURRENT_DATE, '%Y-%m') BETWEEN applicable_from AND applicable_to)
        ) p2 ON p1.employee_id=p2.employee_id
    ) t1
    INNER JOIN users AS t2 ON t1.leader = t2.employee_id
    INNER JOIN departments AS t3 ON t3.id = t1.department
    LEFT JOIN designations AS t4 ON t4.id=t1.new_designation
) join_table
WHERE employee_id='$emp_id'
EOT;

$users = mysqli_fetch_assoc(mysqli_query($db, $users_sql));

?>


<style>
    /* profile file */
    .form-attachment-btn {
        position: relative;
        overflow: hidden;
        margin-bottom: 0;
        padding-top: 8px;
    }

    .form-attachment-btn-label {
        position: absolute;
        top: 0;
        right: 0;
        display: block;
        min-width: 100%;
        min-height: 100%;
        cursor: inherit;
        opacity: 0 !important;
    }

    [contenteditable="true"] {
        min-width: 50%;
        max-width: 100%;
        cursor: text;
    }

    [contenteditable="true"]:focus,
    [contenteditable="true"]:hover {
        outline: 1px dashed darkcyan;
        cursor: text;
    }

    [placeholder]:empty::before {
        content: attr(placeholder);
        color: #9197a3;
        font-weight: 100;
        padding: 3px;
    }
</style>

<div class="content-page">
    <div class="content">
        <div class="container-fluid">

            <div class="my-3 d-flex justify-content-end">
                <a href="<?php echo $url; ?>emp/qr?code=<?php echo $_SESSION['hash_email']; ?>" target="_blank" class="nav-link">
                            <button class="btn btn-secondary">
                                <i class="uil uil-eye mr-1"></i>
                                <span class="">Virtual Id Card</span>
                            </button>
                        </a>
            </div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body py-4 px-sm-5 px-4">

                            <h4 class="header-title mt-1 mb-1"><i class="uil uil-user-circle mr-2 text-primary"></i>Employee Details</h4>
                            <p class="mb-4 text-danger" style="font-size:0.75rem;">You can edit your Details Like:- `Name`, `Email`, `Phone`</p>

                            <div class="row">
                                <div class="col-lg-4 col-sm-12 ">
                                    <form id="profileImg">
                                        <!-- Media -->
                                        <div class="d-flex flex-column align-items-center mb-3" style="gap:1rem;">
                                            <!-- Avatar -->
                                            <label class="form-label" for="logoUploader">
                                                <img id="logoImg" onerror="this.onerror=null;this.src='<?php echo $cdn_url; ?>content/employee/images/avatar.png';" src="<?php echo $cdn_url; ?>content/employee/images/<?php echo $users['image']; ?>" alt="Image Description" style="width:73px; height:73px; border-radius:50%;">
                                            </label>

                                            <div class="d-flex" style="gap:0.5rem;">
                                                <div class="btn btn-primary form-attachment-btn">
                                                    <?php if($users['image'] == '' || $users['image'] == 'NULL'){ ?>    
                                                        Upload Photo
                                                            <input type="file" name="myProfileAvatar" class="form-control form-attachment-btn-label" id="logoUploader" title="Upload Photo" placeholder="Upload Photo">
                                                    <?php }else{ ?>
                                                        <a href="<?php echo $cdn_url; ?>content/employee/images/<?php echo $users['image']; ?>" download="<?php echo $users['image']; ?>" class="text-white">Download</a>
                                                    <?php } ?>    
                                                </div>
                                                <button type="button" <?php echo ($users['image'] == '' || $users['image'] == 'NULL') ? "style='display:none'" : ""; ?> id="deleteLogo" class="btn btn-outline-danger" onclick="location.href='?delete_profile=1'">Delete</button>
                                            </div>
                                        </div>
                                        <!-- End Media -->

                                    </form>
                                </div>

                                <div class="col-lg-4 col-sm-6">
                                    <p class="text-dark mb-1"><strong>Employee Id:</strong> <span><?php echo $users['employee_id']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Name:</strong> <span contenteditable="true" data-name="name" placeholder="Full Name" class="d-inline-block editable-value"><?php echo $users['name']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Email:</strong> <span contenteditable="true" data-name="email" placeholder="contact@gmail.com" class="d-inline-block editable-value"><?php echo $users['email']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Phone:</strong> <span contenteditable="true" data-name="phone" placeholder="987-654-4321" class="d-inline-block editable-value"><?php echo $users['phone']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Gender:</strong> <span contenteditable="true" data-name="gender" placeholder="Male/Female" class="d-inline-block editable-value"><?php echo $users['gender']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Date of Birth:</strong> <span contenteditable="true" data-name="dob" placeholder="01-01-2000" class="d-inline-block editable-value"><?php echo (!empty($users['dob'])) ? date('d M Y', strtotime($users['dob'])) : ''; ?></span></p>

                                    <p class="text-dark mb-1"><strong>PAN No:</strong> <span contenteditable="true" data-name="pan_no" placeholder="MDHSG8738623" class="d-inline-block editable-value"><?php echo $users['pan_no']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Bank Account No:</strong> <span contenteditable="true" data-name="account_no" placeholder="98765432113" class="d-inline-block editable-value"><?php echo $users['account_no']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>IFSC Code:</strong> <span contenteditable="true" data-name="ifsc_code" placeholder="BANK836345" class="d-inline-block editable-value"><?php echo $users['ifsc_code']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>EPF No:</strong> <span contenteditable="true" data-name="epf_no" placeholder="9876544562" class="d-inline-block editable-value"><?php echo $users['uan_no']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>ESIC No:</strong> <span contenteditable="true" data-name="esic_no" placeholder="4356783876" class="d-inline-block editable-value"><?php echo $users['esi_no']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Blood Group:</strong> <span contenteditable="true" data-name="blood_group" placeholder="B+" class="d-inline-block editable-value"><?php echo $users['blood_group']; ?></span></p>
                                </div>

                                <div class="col-lg-4 col-sm-6">
                                    <p class="text-dark mb-1"><strong>Joining Date:</strong> <span><?php echo (!empty($users['joining_date'])) ? date('d M Y', strtotime($users['joining_date'])) : ''; ?></span></p>

                                    <p class="text-dark mb-1"><strong>Probation Date:</strong> <span><?php echo (!empty($users['probation_date'])) ? date('d M Y', strtotime($users['probation_date'])) : ''; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Notice Period:</strong> <span><?php echo (!empty($users['notice_period'])) ? ($users['notice_period'].' Days') : ''; ?></span></p>

                                    <p class="text-dark mb-1"><strong>Department:</strong> <span><?php echo $users['department_name']; ?></span></p>
                                    <p class="text-dark mb-1"><strong>Designation:</strong> <span><?php echo $users['designation_name']; ?></span></p>
                                    <p class="text-dark mb-1">
                                        <strong>Role:</strong>
                                        <span>
                                            <?php
                                            if ($users['role'] == 0 && $users['role'] != NULL) {
                                                echo 'Boss';
                                            } else if ($users['role'] == 1) {
                                                echo 'Manager';
                                            } else if ($users['role'] == 2) {
                                                echo 'Employee';
                                            } else {
                                            }
                                            ?>
                                        </span>
                                    </p>
                                    <p class="text-dark mb-1">
                                        <strong>Leader:</strong>
                                        <span><?php echo $users['l_name']; ?></span>
                                    </p>
                                </div>

                            </div>
                            <div class="d-flex align-items-end justify-content-end mt-4">
                                <button type="button" class="btn btn-primary" id="editable-changes-save">Save Changes</button>
                            </div>

                        </div>
                    </div> <!-- end card -->
                </div>
                <!-- end col -->

            </div>
            <!-- end row -->

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body py-4 px-sm-5 px-4">

                            <h4 class="header-title mt-1 mb-4"><i class="uil uil-money-stack mr-2 text-primary"></i>Employee Salary Details</h4>
                            <div class="d-flex justify-content-end mb-4">
                                <button type="button" class="btn btn-primary" id="showSalary">Show Salary</button>
                                <button type="button" class="btn btn-primary" id="hideSalary" style="display:none;">Hide Salary</button>
                            </div>
                            <div class="row">
                                <?php
                                    $salary = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `employee_salary` WHERE `employee_id`='$emp_id' ORDER BY `id` DESC LIMIT 1"));
                                    $fixed = json_decode($salary['fixed'], true);
                                    $add_on = json_decode($salary['add_on'], true);
                                    $total = 0;
                                ?>
                                <?php foreach($fixed as $value){ $total += $value['yearly_amount']; ?>
                                    <div class="col-lg-4 col-sm-6">
                                        <p class="text-dark mb-1"><strong><?php echo $value['title']; ?>:</strong> &#8377; <span class="salary_amount" data-amount="<?php echo $value['yearly_amount']; ?>">XXXX</span></p>
                                    </div>
                                <?php } ?>
                                <?php foreach($add_on as $key => $value){ $total += $value['yearly_amount']; ?>
                                    <div class="col-lg-4 col-sm-6">
                                        <p class="text-dark mb-1"><strong><?php echo $value['title']; ?>:</strong> &#8377; <span class="salary_amount" data-amount="<?php echo $value['yearly_amount']; ?>">XXXX</span></p>
                                    </div>
                                <?php } ?>
                                <div class="col-lg-4 col-sm-6">
                                    <p class="text-dark mb-1"><strong>Total Salary:</strong> &#8377; <span class="salary_amount" data-amount="<?php echo $total; ?>">XXXX</span></p>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
            <!-- end row -->

        </div>
    </div> <!-- content -->

</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->


<?php
include "pin/footer.php";
?>


<script>
    $("#editable-changes-save").click(function() {

        let eData = {};
        $(".editable-value").each((index, value) => {
            let val = $(value).text();
            let name = $(value).attr("data-name");
            eData[name] = val.trim();
        });
        console.log(eData);

        $.ajax({
            url: "fun/function",
            type: "POST",
            data: {
                editableChangeEmployee: JSON.stringify(eData)
            },
            success: function(response) {
                console.log(response);
                if (response == 1) {
                    successMessage('Your Changes Saved Succesfully.', '<?php echo $user_name; ?>');
                } else {
                    failedMessage('Some Error eccuired On Saving Your Changes.', '<?php echo $user_name; ?>')
                }

            }
        });

    });

    $("#showSalary").click(function() {

        $(".salary_amount").each((index, value) => {
            let amount = $(value).attr("data-amount");
            $(value).text(Math.round(amount / 12));
        });

        $("#hideSalary").show();
        $("#showSalary").hide();
    });

    $("#hideSalary").click(function() {
        $(".salary_amount").each((index, value) => {
            $(value).text('XXXX');
        });

        $("#hideSalary").hide();
        $("#showSalary").show();
    })


    $("#logoUploader").change(function() {
        try{
            console.log('ENTER');
            var fileInput = document.getElementById('logoUploader');
            var filePath = fileInput.value;
            // Allowing file type
            var allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i;
    
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type !');
                fileInput.value = '';
                return false;
            }
    
            var maxKB = 1024;
            var fileSizeInBytes = filePath.size;
            // Convert file size to kilobytes
            var fileSizeInKB = fileSizeInBytes / 1024;
            if (fileSizeInKB <= maxKB) {
                alert('Upload file upto 1 MB!');
                fileInput.value = '';
                return false;
            }
    
            let myForm = document.getElementById("profileImg");
            let fd = new FormData(myForm);
            fd.append('user_name','<?php echo $_SESSION['user_name']; ?>');
            fd.append('emp_id','<?php echo $_SESSION['emp_id']; ?>');
            $("#logoImg").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/loading.png');
            $("#sidebarImage").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/loading.png');
            $.ajax({
                url: "https://emp3.jobaaj.com/fun/function",
                data: fd,
                cache: false,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function(response) {
                    console.log(response);
                    response = JSON.parse(response);
                    console.log(response);
                    if(response.status==200) {
                        // console.log(response);
                        
                        $.ajax({
                            url:'fun/function',
                            type:'POST',
                            data:{update_image_file: response.filename},
                            success:function(res){
                                console.log(res);
                                res = JSON.parse(res);
                                console.log(res);
                                if(res.status==200){
                
                                    $("#logoUploader").val('');
                                    setTimeout(() => {
                                        $("#logoImg").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/' + response.filename);
                                        $("#sidebarImage").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/' + response.filename);
                                        $("#logoUploader").parent().html(`<a href="<?php echo $cdn_url; ?>content/employee/images/${response.filename}" download="${response.filename}" class="text-white">Download</a>`);
                                    }, 1500);
                                    $('#deleteLogo').show();
                                }else{
                                    failedMessage('Something Went Wrong','<?php echo $_SESSION['user_name']; ?>')
                                    $("#logoImg").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/avatar.png');
                                    $("#sidebarImage").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/avatar.png');
                                }
                            }
                        });

                    }else{
                        failedMessage('Something Went Wrong','<?php echo $_SESSION['user_name']; ?>')
                        $("#logoImg").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/avatar.png');
                        $("#sidebarImage").removeAttr("src").attr('src', '<?php echo $cdn_url; ?>content/employee/images/avatar.png');
                    }
                }
            });
        }catch(error){
            console.log(error)
        }
    });
</script>