<?php

declare(strict_types=1);

// ///////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'config' . \DIRECTORY_SEPARATOR . 'config.inc.php';

    // Gestion multiboutique (au cas où) : Ce module est global
    if (Shop::isFeatureActive()) {
        Shop::setContext(Shop::CONTEXT_ALL);
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
    exit;
}

$context = Context::getContext();

// Workaround pour PrestaShop
// @phpstan-ignore-next-line
$context->controller = (object) [
    'controller_type' => 'cron',
    'php_self' => 'iframe_cliniques',
];

$stores = Db::getInstance()->executeS(
    'SELECT s.*, cl.name country, st.iso_code state
    FROM ' . _DB_PREFIX_ . 'store s
    ' . Shop::addSqlAssociation('store', 's') . '
    LEFT JOIN ' . _DB_PREFIX_ . 'country_lang cl ON (cl.id_country = s.id_country)
    LEFT JOIN ' . _DB_PREFIX_ . 'state st ON (st.id_state = s.id_state)
    WHERE s.active = 1 AND cl.id_lang = 1'
);

if (!is_array($stores)) {
    $stores = [];
}

$storesJson = [];

$parnode = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><markers></markers>');

foreach ($stores as $store) {
    $storeInfo = [
        'name' => $store['name'],
        'lat' => (float) $store['latitude'],
        'lng' => (float) $store['longitude'],
        'id_store' => (int) $store['id_store'],
        'has_store_picture' => file_exists(_PS_STORE_IMG_DIR_ . (int) $store['id_store'] . '.jpg'),
    ];
    if (isset($store['distance'])) {
        $storeInfo['distance'] = (int) $store['distance'];
    }

    if ($storeInfo['lat'] && $storeInfo['lng']) {
        $storesJson[] = $storeInfo;
    }
}
?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Vétérinaires MyVetshop</title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"
                integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
                crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyAoXf8d4tua7hcyskA8N5I93NdtuXACpGU&sensor=false&region=FR"></script>
        <script type="text/javascript">
            var defaultLat = 46.5446283;
            var defaultLong = 2.6293777;
            var img_ps_dir = 'https://www.myvetshop.fr/img/';
            var logo_store = 'vetshop-21-logo_invoice-1487698190.jpg';
            var stores = <?php echo json_encode($storesJson); ?>;
            var hasStoreIcon = false;

            var map, infoWindow;
            var markers = [];

            function getDocHeight(doc) {
                doc = doc || document;
                // stackoverflow.com/questions/1145850/
                var body = doc.body, html = doc.documentElement;
                var height = Math.max(body.scrollHeight, body.offsetHeight,
                    html.clientHeight, html.scrollHeight, html.offsetHeight);
                return height;
            }

            $(document).ready(function () {
                $('body').height(getDocHeight());

                map = new google.maps.Map(document.getElementById('map'), {
                    center: new google.maps.LatLng(defaultLat, defaultLong),
                    zoom: 10,
                    mapTypeId: 'roadmap',
                    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
                });
                infoWindow = new google.maps.InfoWindow();

                $(document).on('click', 'input[name=location]', function (e) {
                    e.preventDefault();
                    $(this).val('');
                });

                initMarkers();
            });

            function createMarker(latlng, name, address, other, id_store, has_store_picture) {
                var html = '<b>' + name + '</b><br/>' + address + (has_store_picture === 1 ? '<br /><br /><img src="https://www.myvetshop.fr/img/st/' + parseInt(id_store) + '.jpg" alt="" />' : '') + other + '<br /><a href="http://maps.google.com/maps?saddr=&daddr=' + latlng + '" target="_blank">Clinique vétérinaire<\/a>';
                var image = new google.maps.MarkerImage(img_ps_dir + logo_store);
                var marker = '';
                if (hasStoreIcon)
                    marker = new google.maps.Marker({map: map, icon: image, position: latlng});
                else
                    marker = new google.maps.Marker({map: map, position: latlng});
                google.maps.event.addListener(marker, 'click', function () {
                    infoWindow.setContent(html);
                    infoWindow.open(map, marker);
                });
                markers.push(marker);
            }

            function initMarkers() {
                var bounds = new google.maps.LatLngBounds();
                for (var i = 0; i < stores.length; i++) {
                    var store = stores[i];
                    var name = store.name;
                    var id_store = store.id_store;
                    var has_store_picture = store.has_store_picture;
                    var latlng = new google.maps.LatLng(
                        parseFloat(store.lat),
                        parseFloat(store.lng));
                    createMarker(latlng, name, '', '', id_store, has_store_picture);
                    bounds.extend(latlng);
                }
                map.fitBounds(bounds);
                var zoomOverride = map.getZoom();
                if (zoomOverride > 10)
                    zoomOverride = 10;
                map.setZoom(zoomOverride);
            }
        </script>
    </head>

    <body style="margin: 0">
    <div id="map" style="height: 100%; width: 100%; min-height: 300px; min-width: 300px;"></div>
    </body>
    </html>
<?php
