@extends('includes/layout')
@section('main-page-content')
    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="card mb-4">
            <div class="card-body">
              <div>
                <div class="h4 pb-0 mb-0">Attendance Logs</div>
              </div>
                <div class="border-bottom  py-2 justify-content-between align-items-center">
                    <div class="row p-3">
                         <div class="col-lg-3 col-sm-4 mb-3">
                         <input type="text" class="filter-form filter form-control" name="first_name" id="" placeholder="Employee" autocomplete="off">
                        <input type="text" style="display:none" name="fake-first_name" autocomplete="false">
                        </div>
                        <div class="col-lg-3 col-sm-4 mb-3">
                        <input type="text" class="filter-form filter form-control" name="title" id="" placeholder="Site" autocomplete="off">
                        <input type="text" style="display:none" name="title" autocomplete="false">
                        </div>
                       <div class="col-lg-3 col-sm-4 mb-3">
                        <input type="date" class="filter filter form-control" name="date" id="" placeholder="Date" autocomplete="off">
                        <input type="text" style="display:none" name="fake-date" autocomplete="false">
                      </div>
                     
                      <div class="col-lg-3 col-sm-4 mb-3">
                        <div style="display:block;">
                          <button class="btn btn-success btn-sm p-2 waves-effect waves-light filter-btn" onclick="_filter(1); _get(0);">submit</button>
                          <button class="btn btn-danger btn-sm p-2 waves-effect waves-light filter-btn-close" onclick="_filter(0);  _get(0);">x</button>
                        </div>
                      </div>
                    
                    </div>
                </div>
                <div>
                    <div class="table-responsive text-nowrap border-bottom">
                        <table class="table">
                            <thead class="table-head-color bg-primary">
                                <tr>
                                    <th style="width: 13%;">
                                      Employee
                                    </th>
                                    <th style="min-width: 100px;">
                                      Site
                                    </th>
                                    <th style="min-width: 150px;">
                                      Check-In
                                    </th>
                                    <th style="min-width: 150px;">
                                      Check Out
                                    </th>
                                    <th style="width: 17%;">
                                      Date
                                    </th>
                                    <th style="width: 17%;">
                                      Longitude
                                    </th>
                                    <th style="width: 17%;">
                                      Latitude
                                    </th>
                                    <th style="width: 17%;">
                                      Message
                                    </th>
                                    <th style="width: 17%;">
                                      Error Type
                                    </th>
                                    <th style="width: 17%;">
                                      Request Type
                                    </th> 
                                    <th style="width: 17%;">
                                      Map
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="table-border-bottom-0 table-body">

                            </tbody>
                        </table>
                    </div>
                    <nav aria-label="Page navigation" class="mt-3">
                        <ul class="pagination justify-content-md-end justify-content-center pages_btn">

                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="DeleteEmp" tabindex="-1" aria-labelledby="deletePreLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger px-4 py-2">
                    <h5 class="modal-title text-white" id="deletePreLabel">Delete</h5>
                </div>
                <div class="modal-body">
                    Are you sure you want to delete this record?<br><br>
                    <b class="text-warning">Warning:</b> This record will no longer be available. Please ensure you
                    genuinely want to delete it before clicking the delete button.
                </div>
                <div class="modal-footer border-top py-2">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-danger" id="attendance-id" data-id=""
                        onclick="_delete(this)">Delete</button>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('css-js')

<script>
    $(document).ready(function() {
        _filter(0);
        _get(0);
    });

    function formatDate(dateString) {
        const parts = dateString.split('-');
        const formattedDate = `${parts[2]}-${parts[1]}-${parts[0]}`;
        return formattedDate;
    }

    function _filter(filter_on) {
        var collection = document.getElementsByClassName("filter");
        var arr = {};

        for (let i = 0; i < collection.length; i++) {
            arr[collection[i].name] = filter_on == 1 ? collection[i].value : '';
        }

        if (filter_on == 0) {
            $('.filter').val('');
        }

        localStorage.setItem('filter', JSON.stringify(arr));
    }

    function _get(from) {
        loader(true);
    $.ajax({
        type: "GET",
        url: `{{ url('get-attendance-logs') }}?from=${from}&filter=${localStorage.getItem('filter')}`,
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        success: function(response) {
            var attendances = response.data.attendances;
            var allSites = response.data.all_sites; // Fetch all sites data
            var html = ``;
            var count = parseInt(response.count) < 10 ? 1 : Math.ceil(parseInt(response.count) / 10);
            var pages_btn = ``;

            pages_btn += `
                <li class="page-item prev ${response.count == 0 ? 'd-none' : ''}" onclick="_get(0);">
                    <a class="page-link waves-effect" href="javascript:void(0);"><i class="tf-icon mdi mdi-chevron-double-left"></i></a>
                </li>
                <li class="page-item prev ${response.count == 0 ? 'd-none' : ''}" onclick="$('.active').prev('.p-btn').trigger('onclick');">
                    <a class="page-link waves-effect" href="javascript:void(0);"><i class="tf-icon mdi mdi-chevron-left"></i></a>
                </li>`;

            $('.p-btn').removeClass('active');

            for (var c = 0; c < count; c++) {
                if (
                    (from == (c - 3) * 10) ||
                    (from == (c - 2) * 10) ||
                    (from == (c - 1) * 10) ||
                    (from == (c - 0) * 10) ||
                    (from == (c + 1) * 10) ||
                    (from == (c + 2) * 10) ||
                    (from == (c + 3) * 10)
                ) {
                    pages_btn += `
                        <li class="page-item p-btn ${from == c*10 ? 'active' : '' } ${response.count == 0 ? 'd-none' : '' }" onclick="_get(${c*10});">
                            <a class="page-link waves-effect" href="javascript:void(0);">${c+1}</a>
                        </li>`;
                }
            }

            pages_btn += `
                <li class="page-item next ${response.count == 0 ? 'd-none' : ''}" onclick="$('.active').next('.p-btn').trigger('onclick');">
                    <a class="page-link waves-effect" href="javascript:void(0);"><i class="tf-icon mdi mdi-chevron-right"></i></a>
                </li>
                <li class="page-item next ${response.count == 0 ? 'd-none' : ''}" onclick="_get(${(c-1)*10});">
                    <a class="page-link waves-effect" href="javascript:void(0);"><i class="tf-icon mdi mdi-chevron-double-right"></i></a>
                </li>`;

            $('.pages_btn').html(pages_btn);

            for (var i = 0; i < attendances.length; i++) {
                var totalMinutes = attendances[i].working_hours || 0;
                var hours = Math.floor(totalMinutes / 60);
                var minutes = totalMinutes % 60;
                var formattedHours = hours + ':' + (minutes < 10 ? '0' : '') + minutes;

                var emp_teams_members = attendances[i]?.emp_teams_members ?? [];
                var teams_list = '';
                for (j = 0; j < emp_teams_members.length; j++) {
                    teams_list += emp_teams_members[j].emp_teams_list.title + ',';
                }

                let checkoutType = attendances[i].checkout_type;
                let checkOutTime = attendances[i].check_out ? _24_to_12_time(attendances[i].check_out) : '';
                let textColor = checkoutType == 1 ? 'style="color:red !important"' : '';

                html += `
                <tr style="background-color: ${attendances[i].error_type === 'success' ? 'white' : '#e7c6d1'};">
                    <td>
                        <div class="d-flex align-items-center">
                            <div class="border h-px-40 w-px-40 rounded-circle" style="background-image: url('${attendances[i].emp_personal_details.image}'); background-size: cover; background-repeat:no-repeat"></div>
                            <div class="ms-1">
                                ${attendances[i].emp_personal_details.first_name ? attendances[i].emp_personal_details.first_name : ''}
                                ${attendances[i].emp_personal_details.middle_name ? attendances[i].emp_personal_details.middle_name : ''}
                                ${attendances[i].emp_personal_details.last_name ? attendances[i].emp_personal_details.last_name : ''}
                            </div>
                        </div>
                    </td>
                    <td>${attendances[i].sites?.title ?? ''}</td>
                    <td>${attendances[i].check_in ? _24_to_12_time(attendances[i].check_in) : ''}</td>
                    <td>${attendances[i].check_out ? _24_to_12_time(attendances[i].check_out) : ''}</td>
                    <td>${attendances[i].date}</td>
                    <td>${attendances[i].longitude}</td>
                    <td>${attendances[i].latitude}</td>
                    <td>${attendances[i].message}</td>
                    <td>${attendances[i].error_type}</td>
                    <td>${attendances[i].request_type}</td>
                    <td>
                        <button class="btn btn-primary mb-3 viewOnMapBtn" data-lat="${attendances[i].latitude}" data-lng="${attendances[i].longitude}" data-sites='${JSON.stringify(allSites)}'>View on Map</button>
                    </td>
                </tr>`;
            }

            $('.table-body').html(html);

            if (html == ``) {
                $('.table-body').html(
                    `<tr><td colspan="11" class="text-center">No record found</td></tr>`);
            }

            loader(false);
        },
        error: function(response) {
            loader(false);
            if (response.status == 422) {
                var errors = response.responseJSON.data;
                $.each(errors, function(field, messages) {
                    error_msg = messages[0];
                    toastr.error(error_msg);
                });
            } else if (response.status == 500) {
                toastr.error("Something went wrong")
            } else {
                toastr.error(response.responseJSON.message)
            }
        }
    });
}

// Handle the View on Map button click
$(document).on('click', '.viewOnMapBtn', function() {
    const lat = parseFloat($(this).data('lat'));
    const lng = parseFloat($(this).data('lng'));
    const sites = $(this).data('sites');
    openMapInNewTab(lat, lng, sites);
    console.log();
});

function openMapInNewTab(lat, lng, sites) {
    const mapWindow = window.open('', '_blank');

    const mapContent = `
    <div id="map" style="height: 100vh; width: 100%;"></div>
    <script>
        function initMap() {
            const map = new google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: { lat: ${lat}, lng: ${lng} }
            });

            const attendanceLocation = { lat: ${lat}, lng: ${lng} };

            // Add a green marker for the attendance location with increased size
            new google.maps.Marker({
                position: attendanceLocation,
                map: map,
                title: 'Attendance Location',
                icon: {
                    url: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', // Green marker
                    scaledSize: new google.maps.Size(40, 40) // Increased marker size
                }
            });

            const sites = ${JSON.stringify(sites)};

            sites.forEach(site => {
                const position = {
                    lat: parseFloat(site.latitude),
                    lng: parseFloat(site.longitude),
                    site_title: site.title
                };

                // Create an InfoWindow for showing the title
                const infoWindow = new google.maps.InfoWindow({
                    content: '<div style="font-size:14px; font-weight:bold;">' + site.title + '</div>'
                });

                // Add markers for sites with titles and standard size
                const siteMarker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: site.title,
                    icon: {
                        url: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png', // Red marker
                        scaledSize: new google.maps.Size(30, 30) // Standard marker size
                    }
                });

                // Bind the InfoWindow to the marker, showing the popup when the marker is clicked
                siteMarker.addListener('click', () => {
                    infoWindow.open({
                        anchor: siteMarker,
                        map,
                        shouldFocus: false,
                    });
                });

                // Highlight the attendance location with a green circle if it matches
                if (site.latitude == ${lat} && site.longitude == ${lng}) {
                    new google.maps.Circle({
                        strokeColor: '#008000', // Green border for attendance location
                        strokeOpacity: 0.8,
                        strokeWeight: 2,
                        fillColor: '#008000', // Green fill for attendance location
                        fillOpacity: 0.35,
                        map: map,
                        center: position,
                        radius: parseFloat(site.area_radius) * 1000
                    });
                } else {
                    // Normal red circle for other sites
                    new google.maps.Circle({
                        strokeColor: '#FF0000', // Red border for normal sites
                        strokeOpacity: 0.8,
                        strokeWeight: 2,
                        fillColor: '#FF0000', // Red fill for normal sites
                        fillOpacity: 0.35,
                        map: map,
                        center: position,
                        radius: parseFloat(site.area_radius) * 1000
                    });
                }
            });
        }
        window.onload = initMap;
    <\/script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7aLtWqhztn7r4Fcce7WqQT-Qdlpl7MnQ&callback=initMap&v=weekly" async defer><\/script>
    `;

    mapWindow.document.write(mapContent);
    mapWindow.document.close();
}


</script>


    <style>
        .filter {
            width: 100%;
            height: 33px;
            outline: none;
            background: white;
        }

        .filter-form {
            width: 100%;
            height: 33px;
            outline: none;
            background: white;
        }

        .select-color {
            color: #787878;
            font-size: 0.9375rem;
            font-weight: 400;
            line-height: 1.47;
            background-size: 9px 5px;
            border: 1px solid #d4d3d5;
            border-radius: 0.375rem;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
            padding-left: 5px;
        }

        .list_color:hover {
            color: #15A7F5;
        }

        .bg-primary th {
            color: white;
        }

        .dashboard {
            display: flex;
        }

        .dashboard-btn {
            display: flex;
        }

        @media only screen and (min-width: 320px) and (max-width: 520px) {
            .dashboard {
                display: block;
            }

            .dashboard-btn {
                display: block;
            }

            .dashboard-btn .btn {
                margin-top: 10px;
            }
        }
    </style>
@endsection
