<?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'])) {

    $delete_key = mysqli_real_escape_string($db, $_GET['delete']);
    $q = mysqli_query($db, "DELETE FROM incash_leave WHERE id='$delete_key'");
    if ($q) {
        echo "<script>alert('Leave In cash Deleted Successfully !');</script>";
    }
    echo "<script>location.href='leave_incash';</script>";
}


$edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM incash_leave where id='$_GET[edit]'"));


?>

<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">
                                        In Cash Leave
                                    </h4>
                                </div>

                                <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-12">
                                        <h6>In Cash Leave</h6>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <input type="text" name="casual_inCash" pattern="[0-9.]+" required placeholder="Enter Casual incase Count" class="form-control" id="casual_inCash" value="<?php echo $edit['casual_inCash']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <input type="text" name="medical_inCash" pattern="[0-9.]+" required placeholder="Enter Medical incase Count" class="form-control" id="medical_inCash" value="<?php echo $edit['medical_inCash']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-12">
                                        <h6>Carry Forward Leave</h6>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <input type="text" name="casual_carryForward" pattern="[0-9.]+" required placeholder="Enter Casual Carry Forward Count" class="form-control" id="casual_carryForward" value="<?php echo $edit['casual_carryForward']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <input type="text" name="medical_carryForward" pattern="[0-9.]+" required placeholder="Enter Medical Carry Forward Count" class="form-control" id="medical_carryForward" value="<?php echo $edit['medical_carryForward']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="financial_year_start">Financial Year Start<span class="text-danger">*</span></label>
                                            <input type="month" name="financial_year_start" required placeholder="Enter Financial Year Start" class="form-control" id="financial_year_start" value="<?php echo !empty($edit['financial_year_start'])? date("Y-m", strtotime("$edit[financial_year_start]")):''; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="financial_year_end">Financial Year End<span class="text-danger">*</span></label>
                                            <input type="month" name="financial_year_end" required placeholder="Enter Financial Year End" class="form-control" id="financial_year_end" value="<?php echo !empty($edit['financial_year_end'])? date("Y-m", strtotime("$edit[financial_year_end]")):''; ?>">
                                        </div>
                                    </div>

                                    <?php if (isset($edit['id'])) { ?>
                                        <input type="hidden" name="edit_incash_leave" value="<?php echo $edit['id']; ?>">
                                        <input class="btn btn-primary mr-1" name="update_incash_leave" id="update_incash_leave" type="hidden">
                                    <?php } else { ?>
                                        <input class="btn btn-primary mr-1" name="add_incash_leave" id="add_incash_leave" type="hidden">
                                    <?php } ?>

                                    <div class="col-12">
                                        <div class="form-group text-right mb-0 mt-4">
                                            <?php if (isset($edit['id'])) { ?>
                                                <button class="btn btn-primary mr-1" name="update_incash_leave" id="update_incash_leave" type="submit">Update In Cash Leave</button>
                                            <?php } else { ?>
                                                <button class="btn btn-primary mr-1" name="add_incash_leave" id="add_incash_leave" type="submit">Save In Cash Leave</button>
                                            <?php } ?>
                                        </div>
                                    </div>

                                </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>In Cash</th>
                                        <th>Carry Forward</th>
                                        <th>Financial Year</th>
                                        <th>Action</th>
                                </thead>

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

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



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

    $(document).ready(function() {

        /// ############################### columns
        let columns = [{data: 'id'}, {data: 'employee_id'}, {data: 'name'}, {data: 'casual_inCash'}, {data: 'casual_carryForward'}, {data: 'financial_year_start'}, {data: 'financial_year_end'}];
        // ############################### 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_incash_get', columns, [0, "asc"], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/leave_incash_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_incash';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });
</script>