<?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 work_policy where id='$_GET[delete]' "));
    $from_date = date('Y-m', strtotime("$oldRevision[applicable_from] -1 month"));

    $od = mysqli_query($db, "update work_policy set applicable_to='' where employee_id='$oldRevision[employee_id]' and applicable_to='$from_date' ");

    if ($od) {

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

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

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

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

?>

<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="needs-validation" novalidate>
                        <div class="card mb-3">
                            <div class="card-body px-4 py-3">
                                <h4 class="header-title mb-3">
                                    Add Work Policy
                                </h4>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="employee_id">Select Employee<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="employee_id" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>$edit['employee_id'], 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Employee" id="employee_id" required  <?php echo isset($_GET['edit'])?'disabled':''; ?>>
                                            </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="working_days">Select Working Days<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="working_days[]" class="form-control custom-select-picker" data-placeholder="Select Working Days" id="working_days" multiple required>
                                                <option <?php echo in_array('Monday',$working_days)?'selected':''; ?> value="Monday">Mon</option>
                                                <option <?php echo in_array('Tuesday',$working_days)?'selected':''; ?> value="Tuesday">Tue</option>
                                                <option <?php echo in_array('Wednesday',$working_days)?'selected':''; ?> value="Wednesday">Wed</option>
                                                <option <?php echo in_array('Thursday',$working_days)?'selected':''; ?> value="Thursday">Thu</option>
                                                <option <?php echo in_array('Friday',$working_days)?'selected':''; ?> value="Friday">Fri</option>
                                                <option <?php echo in_array('Saturday',$working_days)?'selected':''; ?> value="Saturday">Sat</option>
                                                <option <?php echo in_array('Sunday',$working_days)?'selected':''; ?> value="Sunday">Sun</option>
                                            </select>
                                        </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 Applicable From" class="form-control" id="applicable_from" value="<?php echo $edit['applicable_from']; ?>">
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="punch_in">Punch In<span class="text-danger">*</span></label>
                                            <input type="time" name="punch_in" required placeholder="Enter Punch In" class="form-control" id="punch_in" value="<?php echo $edit['punch_in']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="punch_out">Punch Out<span class="text-danger">*</span></label>
                                            <input type="time" name="punch_out" required placeholder="Enter Punth Out" class="form-control" id="punch_out" value="<?php echo $edit['punch_out']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="relaxation_from">Relaxation From<span class="text-danger">*</span></label>
                                            <input type="time" name="relaxation_from" required placeholder="Enter Relaxation From" class="form-control" id="relaxation_from" value="<?php echo $edit['relaxation_from']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="relaxation_to">Relaxation To<span class="text-danger">*</span></label>
                                            <input type="time" name="relaxation_to" required placeholder="Enter Relaxation To" class="form-control" id="relaxation_to" value="<?php echo $edit['relaxation_to']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="auto_approve_from">Auto Approve From<span class="text-danger">*</span></label>
                                            <input type="time" name="auto_approve_from" required placeholder="Enter Auto_approve From" class="form-control" id="auto_approve_from" value="<?php echo $edit['auto_approve_from']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="auto_approve_to">Auto Approve To<span class="text-danger">*</span></label>
                                            <input type="time" name="auto_approve_to" required placeholder="Enter Auto_approve To" class="form-control" id="auto_approve_to" value="<?php echo $edit['auto_approve_to']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="not_request_after">Not Request After<span class="text-danger">*</span></label>
                                            <input type="time" name="not_request_after" required placeholder="Enter Not Request After" class="form-control" id="not_request_after" value="<?php echo $edit['not_request_after']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="half_day_hours">Half Day Hours<span class="text-danger">*</span></label>
                                            <input type="text" placeholder="HH:MM (e.g. 04:02)" pattern="^\d{1,2}:[0-5]\d$" name="half_day_hours" required class="form-control" id="half_day_hours" value="<?php echo $edit['half_day_hours']; ?>">
                                        </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_work_id" value="<?php echo $edit['id']; ?>">
                                    <input class="btn btn-primary mr-1" name="update_work_policy" id="update_work_policy" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="add_work_policy" id="add_work_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_work_policy" id="update_work_policy" type="submit">Update Work Policy</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="add_work_policy" id="add_work_policy" type="submit">Save Work 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>Employee Id</th>
                                        <th>Name</th>
                                        <th>Working Days</th>
                                        <th>Punch In</th>
                                        <th>Punch Out</th>
                                        <th>Applicable From</th>
                                        <th>Applicable To</th>
                                        <th>Relaxation From</th>
                                        <th>Relaxation To</th>
                                        <th>Auto Approve From</th>
                                        <th>Auto Approve To</th>
                                        <th>Not Request After</th>
                                        <th>Half Day Hours</th>
                                        <th>Action</th>
                                </thead>

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

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



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

    $('#employee_id').on('change', function(e) {
        $('#department_id').prop({
            disabled: true,
            required: false
        });
    });
    $('#department_id').on('change', function(e) {
        $('#employee_id').prop({
            disabled: true,
            required: false
        });
    });

    $(document).ready(function() {

        // ############################### columns
        let columns = [{data: 'row_num'}, {data: 'employee_id'}, {data: 'name'}, {data: 'working_days'}, {data: 'punch_in'}, {data: 'punch_out'}, {data: 'applicable_from'}, {data: 'applicable_to'}, {data: 'relaxation_from'}, {data: 'relaxation_to'}, {data: 'auto_approve_from'}, {data: 'auto_approve_to'}, {data: 'not_request_after'}, {data: "half_day_hours"}, {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/work_policy_get', columns, [0, "asc"], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/work_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');

        if (!form.checkValidity()) {
            form.classList.add('was-validated');
            failedMessage("Fill All the Fields", "<?php echo $_SESSION['user_name']; ?>");
            return false;
        }
        
        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.reload();
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });
</script>