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

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

// echo "<script>alert('$user_role');</script>";

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

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

    if ($id['issue_status'] == 1) {

        $from = $id['issue_date_start'];
        $to = $id['issue_date_end'];

        // #######################################################
        $rData = mysqli_query($db, "UPDATE attendance set attendance_change=0, attendance_change_reason=NULL where employee_id='$id[employee_id]' and attendance_status not in('Week Off','Holiday') and (str_to_date(which_month,'%M %d %Y') between '$from' and '$to') ");

        if ($rData) {
            // echo "<script>alert('attendance updated');</script>";
        }
    }


    $q = mysqli_query($db, "DELETE FROM issue_with_date WHERE id='$_GET[delete]' ");
    if ($q) {
        echo "<script>alert('Request Delete Successfully!');</script>";
        echo "<script>location.href='all_issueDate';</script>";
    } else {
        echo mysqli_error($db);
    }
}


?>


<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

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

            <div class="mt-5"></div>

            <?php if ($user_role > 0) { ?>

                <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">
                                    Your Issue with Date Request
                                </h4>

                                <table id="basic-datatable" class="table dt-responsive nowrap">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Date</th>
                                            <th>Note</th>
                                            <th>Request For Attendance</th>
                                            <th>Request Time</th>
                                            <th>Status</th>
                                            <th>Remark</th>
                                        </tr>
                                    </thead>

                                </table>
                                <!-- </div> -->

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

            <?php } ?>

            <?php if ($user_role < 2) { ?>

                <div class="row mb-3" id="filter_block">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="form-label" for="employee_id">User (Name, E-mail, Phone)</label>
                            <select required id="employee_id" name="employee_id" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select user">
                                <option></option>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="form-label" for="issue_status">Issue status</label>
                            <select required id="issue_status" name="issue_status" data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Issue status">
                                <option></option>
                                <option value="0" selected>Pending</option>
                                <option value="1">Approved</option>
                                <option value="2">Rejected</option>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="form-label" for="punch_in">Punch In (In 24 Hours Like 10:00)</label>
                            <div class="input-group">
                                <span class="">
                                    <select required id="punch_in_operator" name="punch_in_operator" class="form-control" data-isLGOperator="true" style="width:fit-content; border-right: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; -moz-appearance: none; -webkit-appearance: none;">
                                        <option value="<" selected><</option>
                                        <option value=">">></option>
                                        <option value="<="><=</option>
                                        <option value=">=">>=</option>
                                    </select>
                                </span>
                                <input type="text" class="form-control" style="border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0;" data-isLG="true" required name="punch_in" id="punch_in" placeholder="Punch In (In 24 Hours Like 10:00)">
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="form-label" for="punch_out">Punch Out (In 24 Hours Like 19:00)</label>
                            <div class="input-group">
                                <span class="">
                                    <select required id="punch_out_operator" name="punch_out_operator" class="form-control" data-isLGOperator="true" style="width:fit-content; border-right: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; -moz-appearance: none; -webkit-appearance: none;">
                                        <option value="<" selected><</option>
                                        <option value=">">></option>
                                        <option value="<="><=</option>
                                        <option value=">=">>=</option>
                                    </select>
                                </span>
                                <input type="text" class="form-control" style="border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0;" data-isLG="true" required name="punch_out" id="punch_out" placeholder="Punch Out (In 24 Hours Like 19:00)">
                            </div>
                        </div>
                    </div>

                
                    <div class="col-md-2">
                        <div class="d-flex flex-column mb-3">
                            <button type="button" class="btn btn-danger btn-padding mb-1" name="clear_filter" id="clear_filter">Clear</button>
                            <button class="btn btn-success btn-padding" type="button" name="search_filter" id="search_filter">Search</button>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <div id="filter_options" class="d-flex align-items-center flex-wrap" style="gap:0.25rem"></div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <h4>Bulk Status Approve</h4>

                        <div class="row">
                            <div class="col-sm-3">
                                <select name="bulk_status" id="bulk_status" required data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Bulk Status">
                                    <option></option>
                                    <option value="1">Approve</option>
                                    <option value="2">Reject</option>
                                </select>
                            </div>
                            <div class="col-sm-3">
                                <input type="text" id="bulk_remark" name="bulk_remark" class="form-control" placeholder="Enter Bulk Remark">
                            </div>
                            <div class="col-sm-3">
                                <select id="bulk_attendanceStatus" name="bulk_attendanceStatus" required data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Attendance Status">
                                    <option></option>
                                    <?php
                                        $att_status = mysqli_fetch_all(mysqli_query($db, "SELECT * FROM attendance_status"), MYSQLI_ASSOC);
                                        foreach ($att_status as $key => $att) {
                                            echo '<option value="'.$att['status'].'">'.$att['status'].'</option>';
                                        }
                                    ?>
                                </select>
                            </div>
                            <div class="col-sm-3">
                                <button class="btn btn-primary" id="set_bulk_status"><span>Set Status</span> <span class="spinner-border ms-2" style="width:1rem; height:1rem; display:none;" role="status"></span></button>
                            </div>
                        </div>

                    </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">
                                    Requests For Issue with Date
                                </h4>

                                <table id="basic-datatable2" class="table dt-responsive nowrap">
                                    <thead>
                                        <tr>
                                            <th><input id="checkAll" type="checkbox"></th>
                                            <th>Employee ID</th>
                                            <th>Name</th>
                                            <th>Previous Attendance</th>
                                            <th>Request For Attendance</th>
                                            <th>Request For Date</th>
                                            <th>Note</th>
                                            <th>Request Time</th>
                                            <th>Status</th>
                                            <th>Remark</th>
                                            <th>Attendance Status</th>
                                            <th>Change Status</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>

                                </table>
                                <!-- </div> -->

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

            <?php } ?>

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

</div>

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



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

<script>
    <?php if ($user_role < 2) { ?>

        async function send_request(req_status, remark, issue_id, attendance_status, onDate){
            await $.ajax({
                url: "fun/function",
                type: "POST",
                data: {
                    req_status,
                    remark,
                    issue_id,
                    attendance_status,
                    onDate
                },
                success: function(res) {
                    // console.log(res);
                    if (res == 1) {
                        if(req_status==1){
                            $("#requestButton" + issue_id).html('<button type="button" class="btn btn-sm btn-soft-success" title="Approved"><i class="uil uil-check-circle mb-0" style="font-size:20px;"></i></button>');
                            $("#requestStatus" + issue_id).html('<span class="text-success">Approved</span>')
                            successMessage('Request Approved Successfully !');
                        }else{
                            $("#requestButton" + issue_id).html('<button type="button" class="btn btn-sm btn-soft-danger" title="Rejected"><i class="uil uil-times-circle mb-0" style="font-size:20px;"></i></button>');
                            $("#requestStatus" + issue_id).html('<span class="text-danger">Rejected</span>')
                            successMessage('Request Rejected Successfully !');
                        }
                    } else {
                        failedMessage('Some Error Occured !');
                    }

                }
            });
        }

        function changeStatus(id, status, date) {

            let remark = $("#remark" + id).val();
            let attendance = $("#AppAttendanceStatus" + id).val();

            // alert(attendance);
            if (remark == '') {
                failedMessage("Please Enter Remark !");
                return false;
            } 
            if (status == 1) {
                if (attendance == '') {
                    failedMessage("Please Select Attendance Status !");
                    return false
                }
                send_request(status, remark, id, attendance, date);
            } else {
                send_request(status, remark, id, '', '');
            }

        }


        $('#bulk_status').change(function(){
            if(this.value==1){
                $('#bulk_attendanceStatus').parent().show();
                $('#set_bulk_status').text('Set Approve Status');
            }else if(this.value==2){
                $('#bulk_attendanceStatus').parent().hide();
                $('#set_bulk_status').text('Set Reject Status');
            }
        });
        
        $('#set_bulk_status').click(async function(){
            let values = $('input.checkboxes:checked').map(function() {
                return [[
                    $(this).attr('data-id'),
                    $(this).attr('data-issueDate')
                ]]; // wrap in extra array to keep them grouped
            }).get();
            let status = $('#bulk_status').val();
            let remark = $('#bulk_remark').val();
            let attendance = $('#bulk_attendanceStatus').val();
            console.log(status, remark, attendance, values);

            if(status == ''){
                failedMessage('Please Select Status.');
                return false;
            } 
            if(values.length <= 0 ){
                failedMessage('Please Select Minimum single Employee.');
                return false;
            }

            if(status==1 && attendance == '') {
                failedMessage("Please Select Attendance Status !");
                return false
            }

            $('#set_bulk_status').prop('disabled', true);
            $('#set_bulk_status span:last-child').show();
            for (const [id, issueDate] of values) {
                // console.log(status, remark, id, attendance, issueDate);
                await send_request(status, remark, id, attendance, issueDate);
            }
            $('#set_bulk_status span:last-child').hide();
            $('#set_bulk_status').prop('disabled', false);

            $('#bulk_status').val(null).trigger('change');
            $('#bulk_remark').val('');
            $('#bulk_attendanceStatus').val(null).trigger('change');
            show_hierarchy_data();
        });


        function show_hierarchy_data() {
            columns =[{data: 'id'}, {data: 'employee_id'}, {data: 'name'}, {data: 'attendance_status'}, {data: 'request_for'}, {data: 'issue_date'}, {data: 'issue_note'}, {data: 'created_at'}, {data: 'issue_status'}, {data: 'remark'}, {data: 'issue_type'}, {data: 'punch_in'}, {data: 'punch_out'}];

            // ############################### setArray

            // ############################### setArray

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

            const matchedValues = setArray.filter(item => item.startsWith("punch_"));
            setArray = setArray.filter(item => !item.startsWith("punch_"));
            console.log(matchedValues);

            // console.log("🚀 ~ show_hierarchy_data ~ setArray:", setArray)
            loadTable(`#basic-datatable2`, `get_from_server/all_issueDate_employee_get`, columns, [0, 'asc'], setArray, matchedValues);
            setArray = [];
            // console.log("🚀 ~ show_hierarchy_data ~ setArray:", setArray)
        }
        $("#search_filter").click(show_hierarchy_data);
        $(document).ready(function(){
            show_hierarchy_data();
        });
    <?php } ?>

    <?php if ($user_role > 0) { ?>
        function show_hierarchy_data1() {
            columns = [{data: 'id'}, {data: 'issue_date'}, {data: 'issue_note'}, {data: 'request_for'}, {data: 'created_at'}, {data: 'issue_status'}, {data: 'remark'}];
            // ############################### setArray
            // ############################### setArray

            loadTable(`#basic-datatable`, `get_from_server/all_issueDate_self_get`, columns, [0, 'asc']);
        }
        $(document).ready(function() {
            // show_hierarchy_data1();
        });
    <?php } ?>

</script>