<!DOCTYPE html>
<!-- Page: point of interest editor -->
<html lang="fr">

	<?php include('blocks/d.head.html'); ?>

	<body>

		<?php include('blocks/d.nav.html'); ?>

		<!-- Map canvas -->
		<div id="mapid"></div>

		<!-- POI form panel -->
		<div id="sticky">
			<section>
				<i id="slide-icon" class="fas fa-chevron-up"></i>
				<?php if(isset($new) AND $new==1) { ?>
					<!-- Create POI -->
					<form class="form" action="<?=$config['rel_root_folder']?>poi/new" method="post">
				<?php } 
				else { ?>
					<!-- Update POI -->
					<form class="form" action="<?=$config['rel_root_folder']?>poi/<?=$poi->permalink?>/edit" method="post">
				<?php } ?>
					<!-- Basic fields -->
					<h1 class="flex_line">
						<input type="text" value="<?=$poi->name?>" name="name" id="name" placeholder="Nom de l'hébergement" required>
						<select name="locale" id="locale">
							<?php foreach($locales->objs as $locale) { ?>
								<option <?=$poi->locale==$locale->name?'selected':''?> value="<?=$locale->name?>"><?=$locale->display_name?></option>
							<?php } ?>
						</select>
					</h1>

					<!-- Location fields -->
					<div class="flex_line">
						<input type="number" class="noarrow" step="any" value="<?=$poi->lat?>" name="lat" id="lat" placeholder="Latitude" required>
						<input type="number" class="noarrow" step="any" value="<?=$poi->lon?>" name="lon" id="lon" placeholder="Longitude" required>
						<input type="number" class="noarrow last-child" step="any" value="<?=$poi->ele?>" name="ele" id="ele" placeholder="Altitude">
						<div id="elevation_icon" style="display:none;" title="Calculer l'altitude"><i class="fas fa-search-location"></i></div>
					</div>

					<!-- Type selector -->
					<div class="flex_line" id="type_selector">
						<?php foreach($poi_types as $type) { ?>
						    <input type="radio" name="poi_type" value="<?=$type[3]?>" id="<?=$type[3]?>" required
						           <?=$poi->poi_type == $type[3] ? 'checked' : ''?>>
						    <label for="<?=$type[3]?>"><img src="<?=$config['views_url']?>img/<?=$type[3]?>.svg"><br><?=$type[0]?></label>
						<?php } ?>
					</div>

					<!-- Dynamic form data -->
<script type="text/javascript">
<?php
    $poi_params = $poi->parameters ?? new stdClass();
?>

var poi_params = <?= json_encode($poi_params) ?>;
var current_poi_type = "<?= $poi->poi_type ?>";

var unsaved = false;

// Stocke les abstracts et les squelettes de formulaire
<?php foreach($poi_types as $type) { ?>
    window["<?=$type[3]?>_abstract"] = "<?=$type[4]?>";
    window["<?=$type[3]?>_jsonform"] = <?=json_encode($type[5])?>;
<?php } ?>

// 3 états : 0 = non, 1 = intermédiaire, 2 = oui
function update3State(id) {
    var input = $("input[name="+id+"]");
    var label = $("label[for="+id+"]");

    var v = parseInt(input.val(), 10);

    // cycle propre : 0 → 1 → 2 → 0
    if (v === 0) v = 1;
    else if (v === 1) v = 2;
    else v = 0;

    input.val(v);

    label.removeClass("uncheck intermediate check");

    if (v === 0) label.addClass("uncheck");
    if (v === 1) label.addClass("intermediate");
    if (v === 2) label.addClass("check");

    unsaved = true;
}

// Génère / met à jour le sous-formulaire selon le type
function updateForm(type) {
    $("#abstract").html(window[type + '_abstract']);

    var html_form = "";
    var jsonform = window[type + '_jsonform'];

    $.each(jsonform, function(index, value) {
        var prefix = index.charAt(0);
        var existing = (poi_params && typeof poi_params[index] !== 'undefined')
            ? poi_params[index]
            : null;

        switch (prefix) {
            case 'b':
                var cls = 'intermediate';
                var val = 1;

                if (existing == 0) {
                    cls = 'uncheck';
                    val = 0;
                } else if (existing == 2) {
                    cls = 'check';
                    val = 2;
                } else if (existing == -1 || existing === null) {
                    cls = 'intermediate';
                    val = 1;
                }
                html_form +=
                    '<label class="threecb ' + cls + '" for="' + index + '" onclick="update3State(\'' + index + '\')">' +
                        value +
                    '</label>' +
                    '<input value="' + val + '" type="hidden" name="' + index + '" id="' + index + '"><br>';
                break;

            case 'n':
                html_form +=
                    '<div class="flex_line">' +
                        '<label for="' + index + '">' + value + '</label>' +
                        '<input min="0" type="number" name="' + index + '" id="' + index + '" ' +
                            (existing !== null ? 'value="' + existing + '"' : '') +
                        '>' +
                    '</div>';
                break;

            case 't':
                html_form +=
                    '<label for="' + index + '">' + value + '</label>' +
                    '<textarea name="' + index + '" id="' + index + '">';
                if (existing !== null) {
                    html_form += String(existing)
                        .replace(/&/g, "&amp;")
                        .replace(/</g, "&lt;")
                        .replace(/>/g, "&gt;");
                }
                html_form += '</textarea>';
                break;

            case 'l':
                html_form +=
                    '<div class="flex_line">' +
                        '<label for="' + index + '">' + value + '</label>' +
                        '<input placeholder="https://" type="url" name="' + index + '" id="' + index + '" ' +
                            (existing ? 'value="' + existing + '"' : '') +
                        '>' +
                    '</div>';
                break;

            default:
                console.log("ERROR: " + index + "'s type is not known");
        }
    });

    $("#specific_form").html(html_form);

    unsaved = false;
    $("#specific_form :input").change(function(){
        unsaved = true;
    });
}

$(document).ready(function(){
		// Au chargement : générer le formulaire du type actuel
    if (current_poi_type) {
        updateForm(current_poi_type);
    }
		unsaved = !is_new;

		$('#type_selector label').click(function(){

		    if (unsaved === true) {
		        if (!confirm("Des changements ont été apportés et vont être supprimés, voulez-vous continuer ?")) {
		            return false;
		        }
		    }

		    const type = $(this).attr("for"); // robuste
		    current_poi_type = type;

		    updateForm(type);
		});
});
</script>
					<!-- Type description -->
					<p id="abstract"></p>
					<!-- Dynamic fields -->
					<div id="specific_form"></div>

					<?php if(isset($new) AND $new==1) { ?>
					<!-- Permalink -->
					<div id="permalink_container">
						<label id="permalink_label" for="permalink"><?=$config['web_root_folder']?>poi/</label>
						<input type="text" name="permalink" id="permalink" placeholder="URL" required>
					</div>
					<?php } ?>

					<!-- Permalink generation -->
					<script type="text/javascript">
$( "#name" ).keyup(function() {
  permalink = $( "#name" ).val();
  permalink = permalink.replace(/ /g,'_');
  permalink = permalink.toLowerCase();
  permalink = permalink.replace(/[^a-z0-9_]/g,'-');
  permalink = permalink.replace(/[_-]+$/g,'');
  $( "#permalink" ).val(permalink);
});
$( "#name" ).change(function() {
  permalink = $( "#name" ).val();
  permalink = permalink.replace(/ /g,'_');
  permalink = permalink.toLowerCase();
  permalink = permalink.replace(/[^a-z0-9_]/g,'-');
  permalink = permalink.replace(/[_-]+$/g,'');
  $( "#permalink" ).val(permalink);
});
					</script>

					<!-- Form submission -->
					<input name="submit" id="submit" type="submit" value="<?= isset($new) && $new == 1 ? "Ajouter l'hébergement" : "Mettre à jour l'hébergement" ?>">
				</form>
			</section>

			<!-- Map variables -->
			<script>
				<?php if($poi->lat != null && $poi->lon != null) { ?>
				var poi_lat = <?=$poi->lat?>;
				var poi_lon = <?=$poi->lon?>;
				<?php } ?>
				var poi_type = "<?=$poi->poi_type?>";
				var is_new = <?= isset($new) && $new == 1 ? "true" : "false" ?>;
				var root = "<?=$config['rel_root_folder']?>";
			</script>


			<!-- Scroll helper -->
			<script type="text/javascript">
$( "#slide-icon" ).click(function() {
  $( "html, body" ).animate({scrollTop: "300px"});
});
		</script>

			<?php include('blocks/d.footer.html'); ?>
		</div>
	</body>
</html>
