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

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


$month = isset($_GET['month']) ? $_GET['month'] : date("Y-m");
$eid = isset($_GET['emp_id']) ? $_GET['emp_id'] : $emp_id;

if ($user_role != 0) {
    if (isset($_GET['emp_id'])) {
        $ex = mysqli_num_rows(mysqli_query($db, "select * from users where employee_id='$_GET[emp_id]' and leader='$emp_id'"));
        if ($ex == 0 && $_GET['emp_id'] != $emp_id) {
            echo "<script>location.href='404'</script>";
        }
    }
}


?>

<!-- Plugin css -->
<link href="assets/libs/fullcalendar-core/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-daygrid/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-bootstrap/main.min.css" rel="stylesheet" type="text/css" />


<style>
    .fc-toolbar {
        flex-wrap: wrap;
    }
    .fc-toolbar > div{
        margin: 0 !important;
    }
   

    .fc-highlight {
        background: #bce8f1 !important;
        opacity: 1 !important;
    }
    .alert-info {
        color: #000 !important;
        background-color: #7cefd273 !important;
        border-color: #7cefd273 !important;
    }
    .fc-event,
    td {
        cursor: pointer;
    }
</style>


<div class="content-page" style="position:relative;">

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

            <div class="row align-items-start">
                <div class="col-md-4 mb-3">
                    <h4 class="m-0">Daily Work <span class="text-primary" id="current_selected_emp"></span></h4>
                </div>
                <div class="col-md-4 mb-3"></div>
                <div class="col-md-4 mb-3">
                <?php if ($user_role < 2) { ?>
                        <div class="form-group mb-1">
                            <select data-plugin="customselect" name="employee_id" class="form-control custom-select-picker" data-placeholder="Select Employee" id="employee_id">
                                <option></option>
                            </select>
                        </div>
                    <?php } ?>
                    <div class="form-group">
                        <input type="month" class="form-control" id="attendanceMonth" value="<?php echo $month; ?>">
                    </div>
                </div>

            </div>

            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <div id="calendar"></div>
                        </div> <!-- end card body-->
                    </div> <!-- end card -->
                </div>
                <!-- end col-12 -->
            </div> <!-- end row -->

            <?php if ($user_role < 2) { ?>
                <div class="row">
                    <div class="col-sm-3"></div>
                    <div class="col-sm-3"></div>
                    <div class="col-sm-3">
                        <div class="form-group mb-3">
                            <label for="start_date">Start: </label>
                            <input type="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" id="start_date">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group mb-3">
                            <label for="end_date">End:</label>
                            <input type="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" id="end_date">
                        </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">
                                    Your <?php echo ($user_role < 2) ? 'and <span class="text-danger">Your Team</span>' : ''; ?> Daily Work
                                </h4>

                                <table id="basic-datatable" class="table dt-responsive nowrap">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Employee Id</th>
                                            <th>Employee Name</th>
                                            <th>Date</th>
                                            <th>Work</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div> <!-- end card body-->
                        </div> <!-- end card -->
                    </div><!-- end col-->
                </div>
                <!-- end row-->
            <?php } ?>

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



<?php
include "pin/footer.php";
?>
<!-- plugin js -->
<script src="assets/libs/fullcalendar-core/main.min.js"></script>
<script src="assets/libs/fullcalendar-bootstrap/main.min.js"></script>
<script src="assets/libs/fullcalendar-daygrid/main.min.js"></script>
<script src="assets/libs/fullcalendar-interaction/main.min.js"></script>

<!-- Calendar init -->
<!-- <script src="assets/js/pages/calendar.init.js"></script> -->

<script>
    fetch_employees('employee_id', '<?php echo isset($_GET['emp_id']) ? $_GET['emp_id'] : $emp_id; ?>', '<?php echo $currentPageName; ?>');

    var final_employee_id = `${($('#employee_id').val()=='' || $('#employee_id').val()==undefined || $('#employee_id').val()==null)?'<?php echo $eid; ?>':$('#employee_id').val()}`;
    function get_final_employee_id() {
        final_employee_id = `${($('#employee_id').val()=='' || $('#employee_id').val()==undefined || $('#employee_id').val()==null)?'<?php echo $eid; ?>':$('#employee_id').val()}`;
        return final_employee_id;
    }

    var final_month_date = `${($("#attendanceMonth").val()=='' || $("#attendanceMonth").val()==undefined || $("#attendanceMonth").val()==null)?'<?php echo $month; ?>':$("#attendanceMonth").val()}`;
    function get_final_month_date() {
        final_month_date = `${($("#attendanceMonth").val()=='' || $("#attendanceMonth").val()==undefined || $("#attendanceMonth").val()==null)?'<?php echo $month; ?>':$("#attendanceMonth").val()}`;
        return final_month_date;
    }

    function createDate(date) {
        return date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, 0) + "-" + String(date.getDate()).padStart(2, 0);
    }

    function createMonth(date) {
        return date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, 0);
    }

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    
    var events = [];
    let calendarObj = null;
    function loadCalender() {
        if(calendarObj!==null){
            calendarObj.destroy();
        }

        let calendar = $("#calendar");
        calendarObj = new FullCalendar.Calendar(calendar[0], {
            plugins: ["bootstrap", "interaction", "dayGrid"],
            defaultView: "dayGridMonth",
            themeSystem: "bootstrap",
            bootstrapFontAwesome: true,
            defaultDate: '<?php echo date("Y-m-01", strtotime($month)); ?>',
            header: {
                left: "title",
                center: "",
                right: "prev,next custom_today",
            },
            customButtons: {
                custom_today: {
                    text: 'Today'
                }
            },
            buttonText: {
                prev: "Prev",
                next: "Next",
                today: "Today"
            },
            weekNumbers: true,
            handleWindowResize: true,
            height: $(window).height() - 200,
            selectable: true,
            dayMaxEvents: true,
            dayMaxEventRows: 1,
            events: events,

            
        });
        calendarObj.render()

        calendarObj.on('eventClick', async function(e) {
            let event_info = e.event;
            // console.log(event_info);
            let ecDate = new Date(event_info.start);
            let fecDate = ecDate.toDateString();

            let response = await fetch('fun/getEmployeeWork.php', {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    employeeWorkId: get_final_employee_id(),
                    timeDate: fecDate,
                    eventClickId: event_info.id
                }),
            });
            let data = await response.json();
            // console.log(data);
            if (data.noData == undefined) {
                let wDiv = `
                <h5 class="mb-3"><i class="uil uil-stopwatch text-danger"></i>&nbsp;<span id="currentEventDate">${fecDate}</span></h5>
                <div class="mb-3"><h5 class="mb-0 text-dark"><span>${data.name}</span></h5>`;

                let wk = JSON.parse(data.work);
                for (const timeText of wk) {
                    wDiv += `<p class="mb-3 text-dark"><span class="text-danger">${timeText.time} - </span><span>${timeText.text}</span></p>`;
                }
                wDiv += `</div>`;
                $('#right_sidebar_details').html(wDiv);
                show_hide_right_bar();
            }
        });

        calendarObj.on('dateClick',async function(e) {
            if('<?php echo $emp_id; ?>'==get_final_employee_id()){

                // console.log(e);
                let fdcDate = e.dateStr;

                let response = await fetch('fun/getEmployeeWork', {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        employeeClickWorkId: get_final_employee_id(),
                        clickDate: fdcDate,
                    }),
                });
                let data = await response.json();
                // console.log(data);
                
                let work_form = `
                <form id="workAddForm">
                    <div class="form-group mb-3">
                        <label for="workDate">Select Date<span class="text-danger">*</span></label>
                        <input type="date" name="workDate" value="${fdcDate}" required class="form-control" id="workDate">
                    </div>`;
                    
                if (data.noData != undefined && data.noData == 1) {
                    $('#right_sidebar_title').html('Add Work');
                    work_form += `
                        <div class="form-group mb-3" id="addRemoveWork">
                            <div class="d-flex justify-content-between mb-2" style="gap:0.5rem;">
                                <label for="work">Enter Work<span class="text-danger">*</span></label>
                                <button type="button" class="btn btn-sm btn-success addWorkDiv" onclick="addWorkDiv('addRemoveWork');" style="height:fit-content"><i class="uil-plus"></i></button>
                            </div>
                            <div class="addRemoveWorkDiv mb-3">
                                <div class="d-flex mb-2" style="gap:0.5rem;">
                                    <input type="number" step="any" name="workDayTime[]" id="workDayTimeStart" class="form-control" placeholder="Enter Time" required>
                                    <select name="hm[]" id="hm" class="form-select form-control" required>
                                        <option value="Hours">Hours</option>
                                        <option value="Minutes">Minutes</option>
                                    </select>
                                </div>
                                <textarea name="work[]" id="work" rows="3" class="form-control" required placeholder="Enter Your Work."></textarea>
                            </div>
                        </div>
                        <input type="hidden" name="addWork">
                        <div class="d-flex justify-content-center">
                            <button class="btn btn-primary" type="submit" name="" id="addWork" style="width:50%;">Add Work</button>
                        </div>
                    </form>
                    `;
                }else{
                    $('#right_sidebar_title').html('Update Work');
                    work_form += `
                    <div class="form-group mb-3" id="addRemoveWork">
                        <div class="d-flex justify-content-between mb-2" style="gap:0.5rem;">
                            <label for="work">Enter Work<span class="text-danger">*</span></label>
                            <button type="button" class="btn btn-sm btn-success addWorkDiv"  onclick="addWorkDiv('addRemoveWork');" style="height:fit-content"><i class="uil-plus"></i></button>
                        </div>`;
                    let wk = JSON.parse(data.work);
                    let i = 1;
                    for (const timeText of wk) {
                        let num = ((timeText.time).split(" ")[0]).trim();
                        let hm = ((timeText.time).split(" ")[1]).trim();
                        work_form += `
                            <div class="addRemoveWorkDiv mb-3">
                                <div class="d-flex mb-2" style="gap:0.5rem;">
                                    <input type="number" step="any" name="workDayTime[]" id="workDayTimeStart" class="form-control" placeholder="Enter Time" value="${num}" required>
                                    <select name="hm[]" id="hm" class="form-select form-control" required>
                                        <option ${(hm=='Hours')?'selected':''} value="Hours">Hours</option>
                                        <option ${(hm=='Minutes')?'selected':''} value="Minutes">Minutes</option>
                                    </select>
                                    `;
                                    if (i > 1) {
                                        work_form += `<button type="button" class="btn btn-sm btn-danger removeWorkDiv" style="height:fit-content"><i class="uil-minus"></i></button>`;
                                    }
                        work_form += `</div>
                        <textarea name="work[]" id="work" rows="3" class="form-control" required placeholder="Enter Your Work.">${timeText.text}</textarea>
                            </div>`;
                        i++;
                    }
                    work_form += `
                    </div>
                    <input type="hidden" name="updateWork">
                        <div class="d-flex justify-content-center">
                                <button class="btn btn-primary" type="submit" name="" id="updateWork" style="width:50%;">Update Work</button>
                            </div>
                        </form>
                    `;

                }

                $('#right_sidebar_details').html(work_form);
                show_hide_right_bar();
            }
        });
    }

    async function getData(eid, month) {
        // $("#loader-wrapper").show();

        let response = await fetch('fun/getEmployeeWork.php', {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                employee_id: get_final_employee_id(),
                selectedMonth: get_final_month_date()
            })
        });
        let data = await response.json();
        // console.log(data)
        $("#current_selected_emp").html(`(${data.name})`);
        events = data.events;
        if(calendarObj===null){
            loadCalender();
            $('button.fc-custom_today-button').attr('disabled',true);
        }
    }
    $(document).ready(async function(){
        getData();
    });
    async function reloadCalender(){
        calendarObj.gotoDate(`${get_final_month_date()}-01`);
        await getData();
        // Update the defaultDate option of the calendar
        // Update the events in the calendar without reinitializing it
        calendarObj.removeAllEvents();
        calendarObj.addEventSource(events);
    }
    $(document).on("change", "#employee_id, #attendanceMonth", function() {
        reloadCalender();
    });
    function calendar_buttons_events() {
        let cal_date = createMonth(calendarObj.getDate());
        $('#attendanceMonth').val(cal_date);
        reloadCalender();
    }

    $(document).on('click', 'button.fc-prev-button, button.fc-next-button', function() {
        $('button.fc-custom_today-button').attr('disabled',false);
        calendar_buttons_events()
    });

    $(document).on('click', 'button.fc-custom_today-button', function() {
        calendarObj.today();
        $(this).attr('disabled',true);
        calendar_buttons_events()
    });

    // ########################################################
    function addWorkDiv(id) {

        $("#" + id).append(`<div class="addRemoveWorkDiv mb-3">
                            <div class="d-flex mb-2" style="gap:0.5rem;">
                                <input type="number" step="any" name="workDayTime[]" id="workDayTimeStart" class="form-control" placeholder="Enter Time" required>
                                <select name="hm[]" id="hm" class="form-select form-control" required>
                                    <option value="Hours">Hours</option>
                                    <option value="Minutes">Minutes</option>
                                </select>
                                <button type="button" class="btn btn-sm btn-danger removeWorkDiv" style="height:fit-content"><i class="uil-minus"></i></button>
                            </div>
                            <textarea name="work[]" id="work" rows="3" class="form-control" required placeholder="Enter Your Work."></textarea>
                        </div>`);
    }

    $(document).on("click", ".removeWorkDiv", function() {
        $(this).parent().parent().remove();
    });
    // ########################################################

    $(document).on('submit',"#workAddForm",function(e){
        e.preventDefault();
        let form_data = $(this).serialize();
        // console.log(form_date);
        $.ajax({
            url:'fun/function',
            type:'post',
            data:form_data,
            success:function(res){
                // console.log(res);
                if(res==1){
                    successMessage('Work Added Successfully!','<?php echo $_SESSION['user_name']; ?>');
                }else if(res==2){
                    successMessage('Work Updated Successfully!','<?php echo $_SESSION['user_name']; ?>');
                }else{
                    failedMessage('Some Error Occurred, Please Try Again after some time.','<?php echo $_SESSION['user_name']; ?>');
                }
                show_hide_right_bar();
                $("#workAddForm")[0].reset();
                calendar_buttons_events();
            }
        });
    });


    $(document).ready(function() {

        let columns =[{data: 'row_num'}, {data: 'employee_id'}, {data: 'name'}, {data: 'work_date'}, {data: 'work'}];
        
        function show_hierarchy_data() {

            <?php if ($user_role == 0) { ?>
                setArray.push(`(COALESCE(working_status_date,'')='' OR working_status_date>='${$("#end_date").val()}')`);
            <?php } else if ($user_role == 1) { ?>
                setArray.push(`(employee_id='<?php echo $emp_id; ?>' or leader='<?php echo $emp_id; ?>')`, `(COALESCE(working_status_date,'')='' OR working_status_date>='${$("#end_date").val()}')`);
            <?php } ?>


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

            if (setArray.length > 0) {
                loadTable(`#basic-datatable`, `get_from_server/dailyWork_get`, columns, [0, "asc"], setArray, `work_date between '${$("#start_date").val()}' and '${$("#end_date").val()}'`);
            } else {
                loadTable(`#basic-datatable`, `get_from_server/dailyWork_get`, columns, [0, "asc"], setArray, `work_date between '${$("#start_date").val()}' and '${$("#end_date").val()}'`);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

        show_hierarchy_data();
        $("#start_date, #end_date").change(function(){
            show_hierarchy_data();
        });

    });


</script>