<?php $__env->startSection('style'); ?>
<style>
#map { height: 300px; }
#map p { text-align: center; line-height: 300px; }
#map p img { vertical-align: middle; margin-right: 1rem; }
h5 { margin-top: 1rem; }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div id="map">
    <p>
        <img src="<?php echo e(asset('img/ajax-loader.gif')); ?>">
        <span>Caricamento mappa...</span>
    </p>
</div>

<div class="container-fluid" style="margin-bottom: 10px;">
    <form action="<?php echo e(url('park/storelocal')); ?>" method="post">
        <?php echo e(csrf_field()); ?>


        <input type="hidden" name="level_id" id="level-id">
        <input type="hidden" id="lat" name="lat">
        <input type="hidden" id="lng" name="lng">

        <div class="row">
            <div class="col col-12">
                <div id="address">
                    <h5>Ti trovi in</h5>
                    <p></p>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col col-12">
                <small class="text-muted">Se la tua posizione non &egrave; esatta sposta il puntatore (<img src="<?php echo e(asset('img/placeholder.png')); ?>" class="img-fluid" style="width: 16px;">) sulla mappa nel luogo in cui effettivamente ti trovi o in una posizione limitrofa.</small>
            </div>
        </div>

        <div class="row">
            <div class="col col-12">
                <div id="levels"></div>
            </div>
        </div>

        <div class="row d-none">
            <div class="col col-12">
                <h5>Dati veicolo</h5>
                <div id="vehicle" class="form-group">
                    <label for="vehicle-plate" class="sr-only">Targa</label>
                    <input type="text" id="vehicle-plate" name="vehicle_plate" class="form-control" placeholder="Inserisci il numero di targa" autocomplete="off" required uppercase>
                </div>
            </div>
        </div>

        <div class="row d-none">
            <div class="col col-12">
                <div id="error">
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <span id="message"></span>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="row d-none">
            <div class="col col-12">
                <div id="park-times"></div>
            </div>
        </div>
        <div class="row d-none">
            <div class="col col-12">
                <h5>Importo</h5>
                <div class="form-group">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">&euro;</span>
                        </div>
                        <input type="text" id="park-cost" name="park_cost" class="form-control" readonly required>
                    </div>
                </div>
            </div>
        </div>



        <div class="row d-none">
            <div class="col col-12">
                <h5>Utente</h5>
                    <div id="user" class="form-group">
                        <label for="user" class="sr-only">User</label>
                        <input type="text" id="user" name="user" class="form-control" placeholder="Inserisci il nome utente" autocomplete="off" required uppercase>
                    </div>
                    <div id="user" class="form-group">
                        <label for="password" class="sr-only">Password</label>
                        <input type="password" id="password" name="password" class="form-control" placeholder="Inserisci la password" autocomplete="off" required uppercase>
                    </div>
                </div>
                <button type="submit" class="btn btn-outline-primary btn-block"><i class="fab"></i> Crea Sosta</button>
                <input type="hidden" id="paymentId" name="paymentId" value="0">
            </div>
        </div>
    </form>
</div>

<script>
var id,
    options = {
        enableHighAccuracy: false,
        timeout: 5000,
        maximumAge: 0
    };

function init() {
    if (navigator.geolocation) {
        id = navigator.geolocation.watchPosition(success, error, options);
    } else {
        alert("Geolocation is not available!");
    }
}

function success(position) {
    var point = {
        lat: position.coords.latitude,
        lng: position.coords.longitude   
    };

    var map_container = document.getElementById('map'),
        options = {
            center: point,
            mapTypeControlOptions: { 
                mapTypeIds: [google.maps.MapTypeId.ROAD_MAP] 
            },
            streetViewControl: false,
            zoom: 17
        },
        map = new google.maps.Map(map_container, options),
        marker = new google.maps.Marker({
            position: point,
            map: map,
            draggable: true,
            icon: "<?php echo e(asset('/img/placeholder.png')); ?>"
        });

    getPositionAddress(marker.getPosition());

    marker.addListener('dragend', function() {
        var position = marker.getPosition();

        map.panTo(position);
        getPositionAddress(position);
    });
    
    navigator.geolocation.clearWatch(id);
}

function error(error) {
    switch (error.code) {
        case 1:
            // Permission denied
            break;
        case 2: case 3:
            // Position unavailable
            break;
    }
}

function storePositionCoordinates(position) {
    $('#lat').val(position.lat());
    $('#lng').val(position.lng());
}

function getPositionAddress(position) {
    storePositionCoordinates(position);
    
    var point = new google.maps.LatLng({ lat: position.lat(), lng: position.lng() });

    $('#levels').html('');
    $('#vehicle').parents('.row').addClass('d-none');
    $('#park-times').parents('.row').addClass('d-none');
    
    getAreaData({ lat: position.lat(), lng: position.lng() }, function() {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ location: point }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    document.querySelector('#address p').innerText = results[0].formatted_address;
                    document.querySelector('#address p').classList.remove('text-danger');
                }
            }
        });
    });
}

function getAreaData(point, callback) {
    $.get("<?php echo e(url('api/areas')); ?>/" + (point.lat + ',' + point.lng), {}, function(data) {
        try {
            var polygons = JSON.parse(data).features;

            callback();

            $insidePolygon = getPositionPolygon(polygons, point);
            if ($insidePolygon) {
                getAreaLevels($insidePolygon.properties.area_id);
            } else {
                console.log("Area non soggetta a pagamento");
            }
        } catch(e) {
            $('#address p').addClass('text-danger').html("Non siamo riusciti a rilevare la tua posizione esatta.");
        }
    });
}

function getPositionPolygon(polygons, point) {
    var found = false, 
        i = 0;

    while (!found && i < polygons.length) {
        var p_coordinates = polygons[i].geometry.coordinates[0];
        p_coordinates.splice(p_coordinates.lenght - 1, 1);

        var paths = [];
        for (var j = 0; j < p_coordinates.length; j++) {
            paths.push({ lat: p_coordinates[j][1], lng: p_coordinates[j][0] });
        }

        var position = new google.maps.LatLng(point.lat, point.lng);
        var polygon = new google.maps.Polygon({ paths: paths });

        if (google.maps.geometry.poly.containsLocation(position, polygon)) {
            found = true;
        } else {
            i++;
        }
    }

    if (found) {
        return polygons[i];
    }

    return false;
}

function getAreaLevels(area_id) {
    $.get("<?php echo e(url('api/areas')); ?>/" + area_id + "/levels", {}, function(data) {
        $('#levels').html(data);
        $('#vehicle').parents('.row').removeClass('d-none');
        $('#park-times').parents('.row').removeClass('d-none');
    });
}

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo e(config('google.maps_api_key')); ?>&libraries=geometry&callback=init" async defer></script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>