<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Plant</title>
    <link rel="manifest" href="/manifest.json">
    <link rel="stylesheet" href="./stylesheets/addplant/style.css">
    <script src='/javascripts/API.js'></script>
    <script>
        API();
    </script>
    <%- include('./partials/base'); %>
</head>
<body style="overflow-y: hidden !important;">
<%- include('./partials/header', { title: 'Add Plant',visibility:'hidden' }); %>

<!--Add Plant Form-->
<section class="vh-10">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-6 text-black">
                <div class="d-flex align-items-center h-custom-2 px-5 ms-xl-4 mt-5 pt-5 pt-xl-0 mt-xl-n5">
                    <form style="width: 60rem;max-height: 60vh;overflow-y: auto;overflow-x: hidden"  >
                        <fieldset class="border p-2">
                            <legend class="float-none w-auto">User Details:</legend>
                            <div class="form-outline mb-4">
                                <label for="username" class="form-label">UserName<span
                                            style="color: red;margin-right: 1px; font-size: 20px;">*</span>: </label>
                                <input type="text" class="form-control" id="username" required name="username">
                            </div>
                            <div class="form-outline mb-4">
                                <label for="email" class="form-label">Email: </label>
                                <input type="email" class="form-control" id="email" name="email">
                            </div>
                            <div class="form-outline mb-4">
                                <label for="phone" class="form-label">Phone: </label>
                                <input type="string" class="form-control" id="phone" name="phone">
                            </div>
                        </fieldset>
                        <div class="form-outline mb-4">
                            <label for="plantName" class="form-label">Plant Name<span
                                        style="color: red;margin-right: 1px; font-size: 20px;">*</span>: </label>
                            <input type="text" class="form-control" id="plantName" required name="plantName">
                        </div>

                        <div class="form-outline mb-4">
                            <label for="plantCommonName" class="form-label">Plant Common Name: </label>
                            <input type="text" class="form-control" id="plantCommonName" name="plantCommonName">
                        </div>

                        <div class="form-outline mb-4">
                            <label for="plantScientificName" class="form-label">Plant Scientific Name: </label>
                            <input type="text" class="form-control" id="plantScientificName" name="plantScientificName">
                        </div>

                        <div class="form-outline mb-4">
                            <label for="plantFamily" class="form-label">Plant Family: </label>
                            <input type="text" class="form-control" id="plantFamily" name="plantFamily">
                        </div>

                        <div class="form-outline mb-4">
                            <label for="plantGenus" class="form-label">Plant Genus: </label>
                            <input type="text" class="form-control" id="plantGenus" name="plantGenus">
                        </div>

                        <div class="form-outline mb-4">
                            <label for="plantSpecies" class="form-label">Plant Species: </label>
                            <input type="text" class="form-control" id="plantSpecies" name="plantSpecies">
                        </div>
                        <div class="form-outline mb-4">
                            <label for="plantDescription" class="form-label">Plant Description: </label>
                            <textarea class="form-control" id="plantDescription" rows="10" cols="10"
                                      name="plantDescription"></textarea>
                        </div>
                        <div class="form-outline mb-4">
                            <label for="plantDescription" class="form-label">Plant Size: </label>
                            <div class="row">
                                <div class="col">
                                    <label for="plantLength" class="form-label">Length<span
                                                style="color: red;margin-right: 1px; font-size: 20px;">*</span>:</label>
                                    <input type="number" class="form-control" id="plantLength" required
                                           name="plantLength">
                                </div>
                                <div class="col">
                                    <label for="plantWidth" class="form-label">Width<span
                                                style="color: red;margin-right: 1px; font-size: 20px;">*</span>:</label>
                                    <input type="number" class="form-control" id="plantWidth" required
                                           name="plantWidth">
                                </div>
                                <div class="col">
                                    <label for="plantHeight" class="form-label">Height<span
                                                style="color: red;margin-right: 1px; font-size: 20px;">*</span>:</label>
                                    <input type="number" class="form-control" id="plantHeight" required
                                           name="plantHeight">
                                </div>
                            </div>
                        </div>

                        <div class="form-outline mb-4">
                            <fieldset class="border p-2">
                                <legend class="float-none w-auto">Characteristics:</legend>
                                <input type="hidden" name="leavesValue" id="leavesValue">
                                <input type="hidden" name="floweringValue" id="floweringValue">
                                <input type="hidden" name="fruitValue" id="fruitValue">
                                <label for="flowering" class="form-label">Flowering:</label>
                                <input class="form-check-input" type="radio" name="flowering" id="floweringYes"
                                       value="Yes" >
                                <label class="form-check-label" for="floweringYes">
                                    Yes
                                </label>

                                <input class="form-check-input" type="radio" name="flowering" id="floweringNo"
                                       value="No" checked>
                                <label class="form-check-label" for="floweringNo">
                                    No
                                </label>

                                <div class="row">
                                    <div class="col">
                                        <label for="leaves" class="form-label">Leaves:</label>
                                        <input class="form-check-input" type="radio" name="leaves" id="leavesYes"
                                               value="Yes">
                                        <label class="form-check-label" for="leavesYes">
                                            Yes
                                        </label>

                                        <input class="form-check-input" type="radio" name="leaves" id="leavesNo"
                                               value="No" checked>
                                        <label class="form-check-label" for="leavesNo">
                                            No
                                        </label>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col">
                                        <label for="leaves" class="form-label">Fruit Bearing:</label>
                                        <input class="form-check-input" type="radio" name="fruitBearing" id="fruitsYes"
                                               value="Yes">
                                        <label class="form-check-label" for="fruitsYes">
                                            Yes
                                        </label>

                                        <input class="form-check-input" type="radio" name="fruitBearing" id="fruitsNo"
                                               value="No" checked>
                                        <label class="form-check-label" for="fruitsNo">
                                            No
                                        </label>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <label for="sunExposure" class="form-label">Sun Exposure:</label>
                                        <select id="sunExposure" name="sunExposure">
                                            <option value="Shade">Shade</option>
                                            <option value="Partial Sun">Partial Sun</option>
                                            <option value="Full Sun">Full Sun</option>
                                        </select>

                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <label for="flowerColor" class="form-label">Flower Color:</label>
                                        <input type="text" class="form-control" id="flowerColor" name="flowerColor"/>
                                    </div>
                                </div>
                            </fieldset>
                        </div>


                        <div class="form-outline mb-4">
                            <label for="uploadImage">Please Upload Image<span
                                        style="color: red;margin-right: 1px; font-size: 20px;">*</span>:</label>
                            <input type="file" id="uploadImage" name="uploadImage" accept="image/*" required>
                        </div>

                        <div class="form-outline mb-4">
                            <label for="datePicker" class="form-label">Date<span
                                        style="color: red;margin-right: 1px; font-size: 20px;">*</span>: </label>
                            <input type="datetime-local" id="datePicker" class="form-control" required name="datePicker"/>
                        </div>

                        <div class="form-outline mb-4">
                            <label for="altitude" class="form-label">Altitude: </label>
                            <input type="number" class="form-control" id="altitude">
                        </div>

                        <div class="form-outline mb-4" required>

                            <label for="pickLocation">Please Pick a Location<span
                                        style="color: red;margin-right: 1px; font-size: 20px;">*</span>:</label>
                            <button type="button" class="btn btn-success" id="fetchLocationBtn" style="width: 30%;margin-left: 0;margin-bottom: 3%">
                                <i class="fas fa-location-dot" style="margin-right: 2%;"></i>Current Location
                            </button>

                            <input type="hidden" id="location" name="location" value="" >
                            <div id="map" style="height: 400px; width: 600px;">

                            </div>

                        </div>
                        <div class="form-outline mb-4">
                            <fieldset class="border p-2">
                                <legend class="float-none w-auto">Address of Plant:</legend>
                                <label for="addressLine" class="form-label">Address Line:</label>
                                <textarea class="form-control" id="addressLine" rows="5" cols="10"
                                          name="addressLine"></textarea>
                                <label for="city" class="form-label">City:</label>
                                <input class="form-control" id="city" type="text" name="city"/>
                                <label for="state" class="form-label">State:</label>
                                <input class="form-control" id="state" type="text" name="state"/>
                                <label for="country" class="form-label">Country:</label>
                                <input class="form-control" id="country" type="text" name="country"/>
                                <label for="pincode" class="form-label">PinCode:</label>
                                <input class="form-control" id="pincode" type="text" name="pincode"/>
                            </fieldset>
                        </div>
                        <button type="button" class="btn btn-success btn-md btn-block" id="addplantbtn">Add Plant</button>
                    </form>

                </div>

            </div>

            <div class="col-sm-6 px-0 d-none d-sm-block" style="height: 100vh;">
                <img src="/images/add-plant.svg"
                     alt="Add Plant image" class="w-100 vh-70"
                     style="object-fit: cover; object-position: left;height: 80%">
            </div>
        </div>
    </div>
</section>
<%- include('./partials/footer'); %>
<script src="/javascripts/idb-utility.js"></script>
<script src="/javascripts/local-storage.js"></script>
<!-- Include the UUID library -->
<script src="https://cdn.jsdelivr.net/npm/uuid@8.3.2/dist/umd/uuidv4.min.js"></script>
<script>
    function initMap() {
        createMapWithMarker(15.380074, 78.983592, "map",true);
    }

    function createMapWithMarker(latitude, longitude, mapElementId,draggable) {
        let mapOptions = {
            zoom: 5,
            center: {lat: latitude, lng: longitude},
            draggable: draggable
        };
        let map = new google.maps.Map(document.getElementById(mapElementId), mapOptions);

        let markerOptions = {
            position: new google.maps.LatLng(latitude, longitude),
            map: map,

        };
        let marker = new google.maps.Marker(markerOptions);

        if(draggable) {
            map.addListener("click", (e) => {
                if (marker) marker.setMap(null);
                marker = new google.maps.Marker({
                    position: e.latLng,
                    map: map,
                });
                document.getElementById("location").value = `${e.latLng.lat()},${e.latLng.lng()}`;
            });
        }
    }

    function updateRadioButttons() {
        const selectedFlowering = document.querySelector('input[name="flowering"]:checked');
        const floweringValue = selectedFlowering ? selectedFlowering.value : null;

        const selectedLeaves = document.querySelector('input[name="leaves"]:checked');
        const leavesValue = selectedLeaves ? selectedLeaves.value : null;

        const selectedFruits = document.querySelector('input[name="fruitBearing"]:checked');
        const fruitsValue = selectedFruits ? selectedFruits.value : null;
        document.getElementById('leavesValue').value = leavesValue == "Yes" ? true : false;
        document.getElementById('floweringValue').value = floweringValue == "Yes" ? true : false;
        document.getElementById('fruitValue').value = fruitsValue == "Yes" ? true : false;
    }

    document.addEventListener('DOMContentLoaded', function() {
        updateRadioButttons();
    });

    document.querySelectorAll('input[type="radio"]').forEach(radio => {
        radio.addEventListener('change', updateRadioButttons);
    });

    //Fetch Current Location Logic
    document.getElementById("fetchLocationBtn").addEventListener("click", function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;

                // Update the location input field with the retrieved latitude and longitude
                document.getElementById("location").value = `${lat},${lng}`;
                const mapElementId = "map";
                createMapWithMarker(lat, lng, mapElementId,false);
            }, function (error) {
                console.error("Error fetching location: ", error);
                alert("Unable to fetch current location. Please try again.");
            });
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    });

    //Sending Form Data to Database
    document.getElementById('addplantbtn').addEventListener('click', function(event) {
        const locationValue = document.getElementById('location').value;
        if (locationValue=="") {
            event.preventDefault();
            alert('Please pick a location before submitting the form.');
        }
        else{
            var userId = getUserId();
            var sightingId = uuidv4();
            const dateTimeValue = document.getElementById("datePicker").value;
            const date = new Date(dateTimeValue);
            const options = {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            };

            const localDateTimeString = date.toLocaleString('en-GB', options);
            const formData = {
                sightingId:sightingId,
                username: document.getElementById("username").value,
                email: document.getElementById("email").value,
                phoneNumber: document.getElementById("phone").value,
                name: document.getElementById("plantName").value,
                commonName: document.getElementById("plantCommonName").value,
                scientificName: document.getElementById("plantScientificName").value,
                family: document.getElementById("plantFamily").value,
                genus: document.getElementById("plantGenus").value,
                species: document.getElementById("plantSpecies").value,
                description: document.getElementById("plantDescription").value,
                length: document.getElementById("plantLength").value,
                width: document.getElementById("plantWidth").value,
                height: document.getElementById("plantHeight").value,
                hasLeaves:   document.getElementById('leavesValue').value,
                flowering: document.getElementById('floweringValue').value,
                fruitBearing:  document.getElementById('fruitValue').value,
                sunExposure: document.getElementById("sunExposure").value,
                flowerColor: document.getElementById("flowerColor").value,
                date: localDateTimeString,
                altitude: document.getElementById("altitude").value,
                location:document.getElementById("location").value,
                line: document.getElementById("addressLine").value,
                city:document.getElementById("city").value,
                state:document.getElementById("state").value,
                country:document.getElementById("country").value,
                pinCode:document.getElementById("pincode").value,
                suggestions: ["NoSuggestion"],
                userid:userId
            };
            const uploadImage = document.getElementById("uploadImage").files[0];
            if (uploadImage) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const base64Image = event.target.result;
                    formData.uploadImage = base64Image;

                    // After image is processed, store form data in IndexedDB or send it to the server
                    addNewPlantsToSyncIDBInBothModes(formData);
                };

                reader.readAsDataURL(uploadImage); // Convert image file to Base64 format
            } else {
                // If no image is uploaded, just process the rest of the form data
                addNewPlantsToSyncIDBInBothModes(formData);
            }

        }
    });


</script>

</body>
</html>
