<?php
// Carica i dealer dal JSON
$dealers = json_decode(file_get_contents('dealers.json'), true);

// Parametri POST
$capCityCountrySearch = $_POST['capCityCountrySearch'] ?? '';
$categories = $_POST['categories'] ?? [];

// Se nessuna categoria è selezionata, considera tutte
if (empty($categories)) {
    $categories = ["Edile", "Agricoltura", "Noleggio", "Assistenza", "Filiale"];
}

/*
// Estrai solo il nome della città
if (!empty($capCityCountrySearch)) {
    // Rimuove eventuale CAP (es. '50100 Firenze' → 'Firenze')
    $parts = explode(',', $city);
    $firstPart = trim($parts[0]);
    
    // Se inizia con un CAP, prendiamo la seconda parola
    if (preg_match('/^\d{5}\s+(.+)$/', $firstPart, $matches)) {
        $cityName = $matches[1];
    } else {
        $cityName = $firstPart;
    }
} else {
    $cityName = '';
}
    */

// Filtro
$filteredDealers = array_filter($dealers, function ($dealer) use ($capCityCountrySearch, $categories) {
    $matchCityOrZip = !$capCityCountrySearch || 
        stripos($dealer['city'], $capCityCountrySearch) !== false || 
        stripos($dealer['cap'] ?? '', $capCityCountrySearch) !== false ||
        stripos($dealer['country'] ?? '', $capCityCountrySearch) !== false;

    $matchCategory = empty($categories) || array_intersect($categories, $dealer['categories']);
    return $matchCityOrZip && $matchCategory;
});

// Se nessun dealer trovato, tentativo per nazione
$geolocatedPoint = null;
if (empty($filteredDealers) && $capCityCountrySearch) {
    // Geocoding per trovare ISO code
    $geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($capCityCountrySearch) . "&key=AIzaSyAmOtjRmwVvsRiudCKKiuMlM0-_MhNNh44";
    $geoJson = json_decode(file_get_contents($geoUrl), true);
    echo "<!-- Geo URL: $geoUrl -->\n";
    echo "<!-- Geo JSON: " . json_encode($geoJson) . " -->\n"; die();

    if ($geoJson['status'] === 'OK') {
        $components = $geoJson['results'][0]['address_components'];
        $countryCode = null;

        foreach ($components as $comp) {
            if (in_array('country', $comp['types'])) {
                $countryCode = $comp['short_name']; // ISO 2 lettere
                break;
            }
        }

        if ($countryCode) {
            // Salva posizione geocodata per pin di fallback
            $geolocatedPoint = $geoJson['results'][0]['geometry']['location'];

            $filteredDealers = array_filter($dealers, function ($dealer) use ($countryCode, $categories) {
                return (
                    strtoupper($dealer['country_code'] ?? '') === strtoupper($countryCode) &&
                    array_intersect($categories, $dealer['categories'])
                );
            });
        }
    }
}
?>

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <title>Dealer Locator</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="style.css">
</head>

<body>
<h2>Trova un dealer</h2>

<form method="post" id="searchForm">
    <input type="text" name="capCityCountrySearch" id="capCityCountrySearch" placeholder="Città o CAP" value="<?= htmlspecialchars($capCityCountrySearch) ?>">

    <fieldset>
        <legend>Categorie</legend>
        <label><input type="checkbox" name="categories[]" value="Edile" <?= (empty($_POST) || in_array('Edile', $categories)) ? 'checked' : '' ?>> Edile</label>
        <label><input type="checkbox" name="categories[]" value="Agricoltura" <?= (empty($_POST) || in_array('Agricoltura', $categories)) ? 'checked' : '' ?>> Agricoltura</label>
        <label><input type="checkbox" name="categories[]" value="Noleggio" <?= (empty($_POST) || in_array('Noleggio', $categories)) ? 'checked' : '' ?>> Noleggio</label>
        <label><input type="checkbox" name="categories[]" value="Assistenza" <?= (empty($_POST) || in_array('Assistenza', $categories)) ? 'checked' : '' ?>> Assistenza</label>
        <label><input type="checkbox" name="categories[]" value="Filiale" <?= (empty($_POST) || in_array('Filiale', $categories)) ? 'checked' : '' ?>> Filiale</label>
    </fieldset>
    
    <!--<button type="submit">Cerca</button>-->
</form>

<button id="toggleSidebar">Mostra/Nascondi Risultati</button>

<div id="sidebar">
    <!--<h3>Risultati trovati: <?= count($filteredDealers) ?></h3>-->
    <h3>&nbsp;</h3>
    <ul>
        <?php foreach ($filteredDealers as $index => $dealer): ?>
            <li data-index="<?= $index ?>">
                <strong><?= htmlspecialchars($dealer['name']) ?></strong><br>
                <?= htmlspecialchars($dealer['address']) ?><br>
                Categorie: <?= implode(', ', $dealer['categories']) ?>
            </li>
        <?php endforeach; ?>
    </ul>
</div>

<div id="map" style="width: 100%; height: 500px; margin-top: 20px;"></div>

<script>
    const dealers = <?= json_encode(array_values($filteredDealers)) ?>;
    const fallbackPoint = <?= json_encode($geolocatedPoint) ?>;
    const suggestions = [];

    dealers.forEach(dealer => {
        if (dealer.cap) {
            suggestions.push({ label: `${dealer.cap}, ${dealer.city}, ${dealer.country}`, match: dealer.cap });
        }
        if (dealer.city) {
            suggestions.push({ label: `${dealer.cap}, ${dealer.city}, ${dealer.country}`, match: dealer.city });
        }
        if (dealer.country) {
            suggestions.push({ label: `${dealer.cap}, ${dealer.city}, ${dealer.country}`, match: dealer.country });
        }
    });

    // Elimina duplicati ignorando maiuscole
    const seen = new Set();
    const uniqueSuggestions = suggestions.filter(s => {
        const key = s.label.toLowerCase() + '|' + s.match.toLowerCase();
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
    });

    $("#capCityCountrySearch").autocomplete({
        minLength: 1,
        source: function (request, response) {
            const term = request.term.toLowerCase();

            const filtered = uniqueSuggestions.filter(s =>
                s.match.toLowerCase().includes(term)
            );

            response(filtered);
        },
        focus: function (event, ui) {
            event.preventDefault(); // evita che scriva il label
        },
        select: function (event, ui) {
            $("#capCityCountrySearch").val(ui.item.match); // Inserisce solo la parte matchata
            event.preventDefault();
        }
    });

    function isAnyCategoryChecked() {
        return $('input[name="categories[]"]:checked').length > 0;
    }

    function submitIfValid() {
        if (!isAnyCategoryChecked()) {
            alert('Seleziona almeno una categoria.');
            return;
        }
        $("#searchForm").submit();
    }

    $('input[name="categories[]"]').on('change', submitIfValid);

    $(document).ready(function(){
      $("#toggleSidebar").trigger("click");
    });

</script>
<script src="script.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/src/markerclusterer.js"></script>
<script
    async defer loading="async"
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAmOtjRmwVvsRiudCKKiuMlM0-_MhNNh44&libraries=places&callback=initAll">
</script>
</body>
</html>