<!DOCTYPE html>
<html itemscope itemtype="https://schema.org/WebSite" lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    @include('partials.head')

    <body>
        <header class="page-header">
            <h1 class="page-title">@if ($trip->is_active) Where in the World is Ben? @else {{ $trip->name }} @endif</h1>
            <nav class="other-links">
                <ul>
                    @if (!$trip->is_active)
                    <li><p><a href="/">Current trip</a></p></li>
                    @endif
                    <li><p><a href="/past-trips">Past trips</a></p></li>
                </ul>
            </nav>
            <section class="trip-meta">
                <p>
                    <span> Tracking started: {!! render_date_difference($trip->date_start) !!}</span> |
                    <span class="{{ ($trip->is_active) ? "positive" : "negative" }}">{{ ($trip->is_active) ? "Active" : "Ended" }}</span> | 
                    @if ($trip->is_active)
                    <span class="{{ ($trip->is_tracking) ? "positive" : "negative" }}">{{ ($trip->is_tracking) ? "Currently tracking" : "Not currently tracking" }}</span> 
                    @endif
                    <span class="small">(Last update: {!! render_date_difference($trip->updated_at) !!})</span>
                </p>
            </section>
        </header>

        <main id="routeContainer">
            <section id="mapContainer">
                <div id="map"></div>
            </section>
            <section id="checkinList">
                <h2 class="section__title">@if ($showAllCheckins) Check-ins @else Recent Check-ins @endif</h2>
                <ol start="{{ count($trip->checkins) }}" reversed>
                @if($showAllCheckins)
                    @php $checkinsList = array_reverse($trip->checkins) @endphp
                @else
                    @php $checkinsList = array_slice(array_reverse($trip->checkins), 0, 10) @endphp
                @endif

                @foreach($checkinsList as $checkin)
                    <li>
                        <details class="checkin" id="{{ $checkin->id }}" ontoggle="toggleCheckin(this.open, this.id)">
                            <summary class="checkin__summary">
                                <h2 class="checkin__title">{{ $checkin->title ?? "[No title]" }}</h2>
                                <p class="checkin__meta">{!! render_date_difference($checkin->date) !!}</p>
                            </summary>
                            {{ $checkin->note ?? "[No note]" }}
    @if($checkin->image_url)
    <img class="popup__image" loading="lazy" src="{{ $checkin->image_url }}">
    @endif
                        </details>
                    </li>
                @endforeach
                </ol>
                @if (!$showAllCheckins)
                <p><a id="allCheckinsLink" href="?show=all">Show all checkins</a></p>
                @endif
            </section>
        </main>

        <footer>
            <script>
                /*
                 * Initialise the map
                 */
                var map = L.map('map');//.setView([{{ end($trip->locations)->latitude }}, {{ end($trip->locations)->longitude }}], 7);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    maxZoom: 19,
                    attribution: 'OpenStreetMap'
                }).addTo(map);

                /*
                 * Populate the route line.
                 */
                var routePoints = L.polyline([
                    @foreach($trip->locations as $location)
                    [{{ $location->latitude }}, {{ $location->longitude }}],
                    @endforeach
                ], {
                    color: '#3d3d3d'
                }).addTo(map);

                /*
                 * Populate all the checkins and popup texts.
                 */
                var checkinMarkers = [];
                var marker = null, popupMarkup = null;
                L.Icon.Default.imagePath = "https://track.bengoldsworthy.net/images/";
                @foreach($trip->checkins as $checkin)
                marker = L.marker([{{ $checkin->location->latitude }}, {{ $checkin->location->longitude }}]).addTo(map);
                
                popupMarkup = '<h2 class="popup__title">{{ $checkin->title ?? "No Title" }}</h2>';
                popupMarkup += `<p class="popup__note">{{ $checkin->note }}</p>`;
                popupMarkup += '<img class="popup__image" src="{{ $checkin->image_url }}">';
                marker.bindPopup(popupMarkup).openPopup();
                
                checkinMarkers[{{ $checkin->id }}] = marker;
                @endforeach

                /*
                 * Fit the map to the last 25 locations, and then zoom out
                 * (to help provide context).
                 */
                map.fitBounds([
                @if ($trip->is_active)
                    @foreach(array_slice(array_reverse($trip->locations), 0, 25) as $location)
                    [{{ $location->latitude }}, {{$location->longitude }}],
                    @endforeach    
                @else
                    @foreach($trip->locations as $location)
                    [{{ $location->latitude }}, {{$location->longitude }}],
                    @endforeach    
                @endif
                ]);
                @if ($trip->is_active) map.zoomOut(2.5); @endif

                /*
                 * Add the current location marker.
                 *
                 * If this goes before the `fitBounds()`, it ends up uncentered.
                 * TODO: Revisit once fixed with other popups.
                 */
                var currLocationMarker = L.icon({
                    iconUrl: 'images/current-location-icon.png',
                    iconSize: [30, 45],
                });

                var currLocation = L.marker(
                    [{{ end($trip->locations)->latitude }}, {{ end($trip->locations)->longitude }}],
                    {
                        icon: currLocationMarker
                    }
                ).addTo(map).setZIndexOffset(1000);
                currLocation.bindPopup('<p>Current location</p>').openPopup();

                /*
                 * Changes the currently-selected popup.
                 */
                function toggleCheckin(isOpen, checkinId) {
                    if (isOpen) {
                        var checkins = document.querySelectorAll('details');

                        checkinMarkers[checkinId].openPopup();

                        checkins.forEach(checkin => {
                            if (checkin.id != checkinId && checkin.open) checkin.open = false;
                        });
                        console.log(checkinMarkers[checkinId].getLatLng());
                        map.setView(new L.LatLng(checkinMarkers[checkinId].getLatLng().lat + 0.03, checkinMarkers[checkinId].getLatLng().lng));
                    } else {
                        checkinMarkers[checkinId].closePopup();
                    }
                }
            </script>
        </footer>
    </body>
</html>

@php
function render_date_difference ($start_time) {
    $minute = 60;
    $hour = $minute * 60;
    $day = $hour * 24;
    $week = $day * 7;
    $month = $week * 4;
    $year = $month * 12;
     
    $start_time_dt = new DateTime($start_time);
    $now = new DateTime();
    $trip_start_difference = intval(($now->getTimestamp() - $start_time_dt->getTimestamp()));

    $start_tag = '<span title="' . date('G:H, j M Y', strtotime($start_time)) . '">';
    $end_tag = '</span>';
    $unit = null;
    $div = 1;

    if ($trip_start_difference < $minute) {
        $unit = 'second';
    } else if ($trip_start_difference < $hour) {
        $div = $minute;
        $unit = 'minute';
    } else if ($trip_start_difference < $day) {
        $div = $hour;
        $unit = 'hour';
    } else if ($trip_start_difference < $week) {
        $div = $day;
        $unit = 'day';
    } else if ($trip_start_difference < $month) {
        $div = $week;
        $unit = 'week';
    } else if ($trip_start_difference < $year) {
        $div = $month;
        $unit = 'month';
    } else {
        $div = $year;
        $unit = 'year';
    }

    return "{$start_tag}" . ( floor ( $trip_start_difference / $div ) ) . " {$unit}" . ( ( floor ( $trip_start_difference / $div ) > 1 ) ? 's' : '' ) . " ago{$end_tag}";
}
@endphp