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

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

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

    $oldRevision = mysqli_fetch_assoc(mysqli_query($db, "select * from leave_policy where id='$_GET[delete]' "));
    $from_date = date('Y-m', strtotime("$oldRevision[applicable_from] -1 month"));

    $od = mysqli_query($db, "update leave_policy set applicable_to='' where applicable_to='$from_date' ");

    if ($od) {

        $q = mysqli_query($db, "DELETE FROM leave_policy WHERE id='$_GET[delete]' ");
        if ($q) {
            echo "<script>alert('Leave Policy Deleted Successfully !');</script>";
        }
    } else {
        echo mysqli_error($db);
    }

    echo "<script>location.href='leave_policy';</script>";
}

$edit = mysqli_fetch_assoc(mysqli_query($db, "select * from leave_policy where id='$_GET[edit]'"));

$leave_details = json_decode($edit['leave_details'], true)??[];

// $currentPageName = 'leave_policy';

?>

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-5"></div>

            <div class="row">
                <div class="col-lg-12">
                    <form id="form_submit" class="parsley-examples">
                        <div class="card mb-3">
                            <div class="card-body px-4 py-3">
                                <div class="w-100 d-flex justify-content-between align-items-center">
                                    <h4 class="header-title m-0">
                                        Add Leave Policy
                                    </h4>
                                    <div>
                                        <button type="button" class="btn btn-success add_section" style="height:fit-content; padding-top: 0.5rem; padding-bottom: 0.3rem;" title="Add More Leve Type"><i class="uil uil-plus"></i></button>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="duration">Duration<span class="text-danger">*</span></label>
                                            <select name="duration" id="duration" data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Duration" required>
                                                <option></option>
                                                <option <?php echo ($edit['duration']=='Monthly')?'selected':''; ?> value="Monthly">Monthly</option>
                                                <option <?php echo ($edit['duration']=='Yearly')?'selected':''; ?> value="Yearly">Yearly</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="department_id">Select Department<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="department_id" class="form-control custom-select-picker-ajax" data-search="departments" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Department" id="department_id" required>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="leave_format">Select Format<span class="text-danger">*</span></label>
                                            <select name="leave_format" class="form-control" id="leave_format" required>
                                                <option value="">Select Format</option>
                                                <option value="regular">Regular</option>
                                                <option value="adon">Adon</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                        <div class="all_sections row">

                            <?php 
                                if(sizeof($leave_details)>0){
                                    foreach ($leave_details as $key => $value) {
                            ?>
                                <div class="section col-12">
                                    <div class="card position-relative">
                                        <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Leave Type Section"><i class="uil uil-times text-white"></i></div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group m-0">
                                                        <label for="leave_type">Leave Type<span class="text-danger">*</span></label>
                                                        <input type="text" name="leave_type[]" required placeholder="Enter Leave Type" class="form-control"  value="<?php echo $value['leave_type']; ?>">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group m-0">
                                                        <label for="total_leave">Total Leave<span class="text-danger">*</span></label>
                                                        <input type="text" pattern="[0-9.]+" name="total_leave[]" required placeholder="Enter Total Leave" class="form-control"  value="<?php echo $value['total_leave']; ?>">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php } }else {?>

                                <div class="section col-12">
                                    <div class="card position-relative">
                                        <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Leave Type Section"><i class="uil uil-times text-white"></i></div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group m-0">
                                                        <label for="leave_type">Leave Type<span class="text-danger">*</span></label>
                                                        <input type="text" name="leave_type[]" required placeholder="Enter Leave Type" class="form-control"  value="">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group m-0">
                                                        <label for="total_leave">Total Leave<span class="text-danger">*</span></label>
                                                        <input type="text" pattern="[0-9.]+" name="total_leave[]" required placeholder="Enter Total Leave" class="form-control"  value="">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>

                        </div>

                        <div class="card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="max_leave_take">Maximum Leave Take (In Month)<span class="text-danger">*</span></label>
                                            <input type="text" name="max_leave_take" pattern="[0-9.]+" required placeholder="Enter Maximum Leave Take (In Month)" class="form-control" id="max_leave_take" value="<?php echo $edit['max_leave_take']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="carry_forward">Carry Forward<span class="text-danger">*</span></label>
                                            <div class="d-flex">
                                                <div class="form-check mr-3">
                                                    <input class="form-check-input" type="radio" name="carry_forward" id="carry_forward_yes" value="Yes" <?php echo ($edit['carry_forward']=='Yes')?'checked':''; ?>>
                                                    <label class="form-check-label" for="carry_forward_yes">Yes</label>
                                                </div>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="carry_forward" id="carry_forward_no" value="No" <?php echo isset($_GET['edit'])?(($edit['carry_forward']=='No')?'checked':''):'checked'; ?>>
                                                    <label class="form-check-label" for="carry_forward_no">No</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="max_carry_forward">Maximum Carry Forward<span class="text-danger">*</span></label>
                                            <input type="text" name="max_carry_forward" pattern="[0-9.]+" required placeholder="Enter Maximum Carry Forward" class="form-control" id="max_carry_forward" value="<?php echo $edit['max_carry_forward']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="applicable_from">Applicable From<span class="text-danger">*</span></label>
                                            <input type="month" name="applicable_from" required placeholder="Enter Asset Brand" class="form-control" id="applicable_from" value="<?php echo $edit['applicable_from']; ?>">
                                        </div>
                                    </div>

                                </div>

                                <?php if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="ex_employee_id" value="<?php echo $edit['employee_id']; ?>">
                                    <input type="hidden" name="old_applicable_from" value="<?php echo $edit['applicable_from']; ?>">
                                    <input type="hidden" name="edit_leave_id" value="<?php echo $edit['id']; ?>">
                                    <input class="btn btn-primary mr-1" name="update_leave_policy" id="update_leave_policy" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="add_leave_policy" id="add_leave_policy" type="hidden">
                                <?php } ?>
                                
                                <div class="form-group text-right mb-0 mt-4">
                                    <?php if (isset($edit['id'])) { ?>
                                        <button class="btn btn-primary mr-1" name="update_leave_policy" id="update_leave_policy" type="submit">Update Leave Policy</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="add_leave_policy" id="add_leave_policy" type="submit">Save Leave Policy</button>
                                    <?php } ?>
                                </div>
                            </div>

                        </div>

                    </form>
                </div>

            </div>


            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-0 mb-1 mb-4">
                                All Leave Types
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>Id</th>
                                        <th>Duration</th>
                                        <th>Leave Details</th>
                                        <th>Max Leave Take (In Month)</th>
                                        <th>Carry Forward</th>
                                        <th>Max Carry Forward</th>
                                        <th>Applicable From</th>
                                        <th>Applicable To</th>
                                        <th>Action</th>
                                </thead>

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

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



<?php
include "pin/footer.php";
?>
<script>
    function set_based_on_duration(){
        if($('#duration').val()=='Monthly'){
            $('#max_leave_take').prop({'disabled':true, 'required':false}).val('');
        }else{
            $('#max_leave_take').prop({'disabled':false, 'required':true});
        }

        if($('#duration').val()=='Yearly' && $('input[name="carry_forward"]:checked').val()=='Yes'){
            $('#max_carry_forward').prop({'disabled':false, 'required':true});
        }else{
            $('#max_carry_forward').prop({'disabled':true, 'required':false}).val('');
        }
    }
    set_based_on_duration();
    $('#duration, input[name="carry_forward"]').change(function(){
        set_based_on_duration();
    });

    $(document).on("click", ".add_section", function() {
        let body = $(".all_sections");
        let section_count = $(body).children().length+1;
        $(body).append(`<div class="section col-12">
                                <div class="card position-relative">
                                    <div class="bg-danger rounded-circle position-absolute remove_section" style="padding: 4px 5px 1px 5px; top:-5px; right:-5px; cursor:pointer;" title="Remove Leave Type Section"><i class="uil uil-times text-white"></i></div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group m-0">
                                                    <label for="leave_type">Leave Type<span class="text-danger">*</span></label>
                                                    <input type="text" name="leave_type[]" required placeholder="Enter Leave Type" class="form-control"  value="">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group m-0">
                                                    <label for="total_leave">Total Leave<span class="text-danger">*</span></label>
                                                    <input type="text" pattern="[0-9.]+" name="total_leave[]" required placeholder="Enter Total Leave" class="form-control"  value="">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>`);
    });
    $(document).on("click", ".remove_section", function() {
        let body = $(this).parent().parent().remove();
        let section_count = $(".all_sections").children().length;
        for (let i=0; i<section_count; i++) {
            $(".all_sections").children().eq(i).find('.asset_count_heading').text(`Leave Type ${i+1}`);
        }
    });


    $(document).ready(function() {

        // ############################### columns
        let columns = [{data: 'row_num'}, {data: 'duration'}, {data: 'leave_details'}, {data: 'max_leave_take'}, {data: 'carry_forward'}, {data: 'max_carry_forward'}, {data: 'applicable_from'}, {data: 'applicable_to'}, {data: 'id'}];
        // ############################### columns

        function show_hierarchy_data() {

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });

            if (setArray.length > 0) {
                loadTable('#basic-datatable', 'get_from_server/leave_policy_get', columns, [0, "asc"], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/leave_policy_get', columns, [0, "asc"]);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }
        show_hierarchy_data();
    });


    function hasEmptyFields(form) {
        // Get all input elements within the form
        const inputs = form.querySelectorAll('input, select, textarea');

        // Check if any input is empty or null
        return Array.from(inputs).some(input => {
                // console.log(input.required, input.value.trim(), input.id);
                return input.required && input.value.trim() === ''
            }
        );
    }

    $('#form_submit').submit(function (e) {
        e.preventDefault();
        let form = document.getElementById('form_submit');
        // let form_data = new FormData(form);
        let form_data = $('#form_submit').serialize();
        console.log(form_data);

        if(hasEmptyFields(form)){
            failedMessage('Please, Fill all the Fields.','<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        $.ajax({
            url: 'fun/function',
            type: 'POST',
            data: form_data,
            dataType: 'json',
            success: function(res) {
                console.log(res);
                if (res.status === 200) {
                    successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    setTimeout(() => {
                        location.href='leave_policy';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

</script>