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

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

$lAD = mysqli_fetch_assoc(mysqli_query($db, "select max(str_to_date(which_month,'%M %d %Y')) as max_date from attendance "));

$get_month = date("Y-m", strtotime("$lAD[max_date]"));
$freeze_month = mysqli_num_rows(mysqli_query($db, "SELECT * FROM attendance_freeze WHERE `month`='$get_month'"));

if($freeze_month>0){
    echo "<script>alert('This Page is Restricted Now!');</script>";
    echo "<script>location.href='404';</script>";
}


$minDate = date('01 M Y', strtotime("$lAD[max_date] -1 month"));
$maxDate = date("d M Y", strtotime("$lAD[max_date]"));
if (isset($_GET['isDate'])) {
    $firstDate = date("d M Y", strtotime($_GET['isDate']));
    $secondDate = '';

    $attendanceDate = date("M d Y", strtotime($_GET['isDate']));
    $getWorkingHours = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM attendance WHERE employee_id='$emp_id' AND which_month='$attendanceDate'"));
    $punch_in = $getWorkingHours['punch_in'];
    $punch_out = $getWorkingHours['punch_out'];

    // calculate the total working hours
    $startTime = new DateTime($punch_in);
    $endTime = new DateTime($punch_out);
    $interval = $startTime->diff($endTime);
    $totalHours = $interval->h + ($interval->i / 60);

    // put condition if total working hours is less than 08:30 hrs then they do not eligible for present status

    $presentStatusOption = true;
    if ($totalHours < 8.5) {
        $presentStatusOption = false;
    }
    
} else {
    // $firstDate = date("d M Y");
    // $secondDate = date("d M Y", strtotime("today +1 day"));
    $firstDate = date("d M Y", strtotime("$maxDate -1 day"));
    $secondDate = date("d M Y", strtotime("$maxDate"));
}

?>


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

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

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

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-1 mb-4">
                                Request Issue With Dates
                            </h4>

                            <form id="form_submit" enctype="multipart/form-data" class="parsley-examples">
                                <div class="row">

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="issueDate">Select Date<span class="text-danger">*</span></label>
                                            <input type="text" name="issueDate" parsley-trigger="change" required class="form-control" id="dash-daterange">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="request_for_attendance">Request for Attendance<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="request_for_attendance" class="form-control custom-select-picker" data-placeholder="Select Leave Type" id="request_for_attendance" required>
                                                <option></option>
                                                <?php
                                                    $att_status = mysqli_query($db, "SELECT * FROM attendance_status WHERE `status` IN ('Present', 'Half Day', 'Work From Home', 'Holiday')");
                                                    while($row = mysqli_fetch_assoc($att_status)){
                                                        if($row['status']=='Present' && !$presentStatusOption){
                                                            continue; // Skip the "Present" option if the employee is not eligible
                                                        }
                                                ?>
                                                <option value="<?php echo $row['status']; ?>"><?php echo $row['status']; ?></option>
                                                <?php } ?>

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


                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="issueNote">Issue Note<span class="text-danger">*</span></label>
                                            <textarea name="issueNote" id="issueNote" class="form-control" cols="30" rows="5" placeholder="Enter Your Issue" required></textarea>
                                        </div>
                                    </div>
                                </div>

                                <input type="hidden" name="issueRequest" value="">

                                <div class="form-group text-right mb-0 mt-4">
                                    <button class="btn btn-primary mr-1" name="issueRequest" type="submit">Send Request</button>
                                </div>

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

            </div>

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

</div>

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



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

<script>
    flatpickr("#dash-daterange", {
        mode: "range",
        dateFormat: "d M Y",
        minDate: "<?php echo $minDate; ?>",
        maxDate: "<?php echo $maxDate; ?>",
        defaultDate: [
            "<?php echo $firstDate; ?>",
            "<?php echo $secondDate; ?>"
        ]
    });


    $(document).on('change','input[name="issueDate"]', function(e){
        let issue_date_freeze = $(this).val();
        $.ajax({
            url:'fun/function',
            type:'POST',
            data:{issue_date_freeze},
            success:function(res){
                // console.log(res);
                if(res==1){
                    alert('This Page is Restricted for selected date!');
                    location.href='404';
                }
            }
        })

    });


    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.reload();
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

</script>