<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Maps Scraper</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='range_styles.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='index_header.css') }}">

</head>
<body>



<h2 style="text-align:center; font-weight: bold">Google Maps Scraper</h2>

<div class="navbar">
    <a class="active" href="{{ url_for('index') }}"><i class="fa fa-fw fa-home"></i> Home</a>
    <a href="{{ url_for('view_data') }}"><i class="fa-sharp fa-solid fa-eye"></i> My Buffer Data</a>
    {% if user_type == 'Admin' %}
        <a href="{{ url_for('view_all_data') }}"><i class="fa-sharp fa-solid fa-eye"></i> All Buffer Data</a>
        <a href="{{ url_for('admin_reports') }}"><i class="fa-sharp fa-solid fa-eye"></i> Reports</a>
    {% endif %}
    <a class="login" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt"></i> Logout</a>
    <a class="login" href="#" style="cursor: none;"><i class="fa fa-fw fa-user"></i> Welcome {{ username }}</a>
</div>

<div class="container mt-4">
    <form id="mapForm">
        <div class="bordered-section">
            <div class="d-flex align-items-center justify-content-between">
                <label>Looking for Points of Interest: </label>
                <button type="button" class="btn btn-link" data-toggle="modal" data-target="#addPoiModal">Add More Business Types</button>
            </div>

            <div class="row">
                <!-- Loop through points of interest and add checkboxes -->
                {% for poi in list_of_poi %}
                    <div class="col-md-3">
                        <div class="form-check d-flex align-items-center">
                            <input class="form-check-input" type="checkbox" value="{{ poi }}" id="searchInput{{ loop.index }}">
                            <label class="form-check-label ml-4" for="searchInput{{ loop.index }}"> {{ poi }} </label>
                            <button type="button" class="btn btn-sm btn-danger remove-poi ml-2" onclick="removePoi('{{ poi }}')">
                                <i class="fas fa-times"></i> <!-- Font Awesome "X" icon -->
                            </button>
                        </div>
                    </div>
                    {% if loop.index % 4 == 0 and not loop.last %}
                        </div><div class="row">
                    {% endif %}
                {% endfor %}
            </div>
        </div>

        <!-- Modal for Adding New Point of Interest -->
        <div class="modal fade" id="addPoiModal" tabindex="-1" role="dialog" aria-labelledby="addPoiModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addPoiModalLabel">Add New Point of Interest</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="addPoiForm">
                            <div class="form-group">
                                <label for="newPoiInputModal">Enter new point of interest:</label>
                                <input type="text" class="form-control" id="newPoiInputModal" placeholder="Enter new point of interest">
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" id="submitPoiButton">Add</button>
                    </div>
                </div>
            </div>
        </div>


        <div class="form-group">
            <div class="form-row">
                <div class="col-md-5">
                    <label for="addressDropdown">Select Address from Database:</label>
                    <select class="form-control" id="addressDropdown">
                        <option value="">Select Address</option>
                        {% for address in list_of_addresses %}
                            <option value="{{ address.id }}" data-add="{{ address.address }}" data-lat="{{ address.lat }}" data-lng="{{ address.lng }}">{{ address.address }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-2">
                    <span class="or-text">or</span>
                </div>
                <div class="col-md-5">
                    <label for="mapLookupInput">Enter Address or Location:</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="mapLookupInput" placeholder="Enter address or location">
                        <div class="input-group-append">
                            <span class="input-group-text">
                                <i class="fa fa-search" id="lookupIcon" style="cursor: pointer;"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Map Display -->
        <div id="map" style="height: 400px; margin-bottom: 20px;"></div>

        <div class="form-row">
            <div class="form-group col-md-5">
                <label for="latitude">Latitude:</label>
                <input type="text" class="form-control" id="latitude" readonly>
            </div>
            <div class="form-group col-md-5">
                <label for="longitude">Longitude:</label>
                <input type="text" class="form-control" id="longitude" readonly>
            </div>
            <div class="form-group col-md-2">
                <button type="button" class="btn btn-primary mb-2" id="saveAddress" style="display: none;">Save Address <i class="fa fa-save" aria-hidden="true"></i></button>
                <button type="button" class="btn btn-primary mb-2" id="updateAddress" style="display: none;">Update Address <i class="fa fa-update" aria-hidden="true"></i></button>
            </div>
        </div>

<!--        Miles Range (0 - 10)-->
        <div class="form-group">
            <div class="range_container">
                <div class="sliders_control">
                    <input id="fromSlider" type="range" value="0" min="0" max="10"/>
                    <input id="toSlider" type="range" value="1" min="0" max="10"/>
                </div>
                <div class="form_control">
                    <div class="form_control_container">
                        <div class="form_control_container__time">Min</div>
                        <input class="form_control_container__time__input" type="number" id="fromInput" value="0" min="0" max="10"/>
                    </div>
                    <div class="form_control_container">
                        <div class="form_control_container__time">Max</div>
                        <input class="form_control_container__time__input" type="number" id="toInput" value="1" min="0" max="10"/>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            <button type="button" class="btn btn-primary mb-2" id="populateButton">Populate Data <i class="fa fa-database" aria-hidden="true"></i></button>
            <button type="button" class="btn btn-secondary mb-2" id="clearButton"><a href="{{ url_for('index') }}" style="color: inherit; text-decoration: none;"> Clear <i class="fa fa-eraser" aria-hidden="true"></i></a></button>
            <button type="button" class="btn btn-info mb-2" id="viewBufferData" style="margin-left: 400px;"><a href="{{ url_for('view_data') }}" style="color: inherit; text-decoration: none;"> View Saved Data <i class="fa fa-eye" style="font-size:20px;"></i> ({{buffer_data_count}})</a></button>
            <button type="button" class="btn btn-danger mb-2" id="clearBufferData">Clear Saved Data <i class="fa fa-trash" style="font-size:20px;"></i></button>
        </div>
    </form>

    <!-- Overlay -->
    <div id="overlay"></div>

    <!-- Loader -->
    <div id="loader">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2">Please wait, We are Fetching Data...</p>
    </div>

    <!-- Loader -->
    <div id="loader1">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2">Please wait, Data Saving in progress...</p>
    </div>

    <!-- Modal for Address Input -->
    <div class="modal fade" id="addressModal" tabindex="-1" role="dialog" aria-labelledby="addressModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addressModalLabel">Address Details</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addressForm">
                        <div class="form-group">
                            <label for="addressName">Address Name:</label>
                            <input type="text" class="form-control" id="addressName" placeholder="Enter address name">
                        </div>
                        <div class="form-group">
                            <label for="modalLatitude">Latitude:</label>
                            <input type="text" class="form-control" id="modalLatitude" readonly>
                        </div>
                        <div class="form-group">
                            <label for="modalLongitude">Longitude:</label>
                            <input type="text" class="form-control" id="modalLongitude" readonly>
                        </div>
                        <input type="hidden" id="addressId"> <!-- Hidden input for the address ID -->
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveAddressModalButton">Save Address</button>
                    <button type="button" class="btn btn-primary" id="updateAddressModalButton">Update Address</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for Buffer Input -->
    <div class="modal fade" id="bufferModal" tabindex="-1" role="dialog" aria-labelledby="bufferModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bufferModalLabel">Enter Buffer Details</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="bufferForm">
                        <div class="form-group">
                            <label for="userName">User Name:</label>
                            <input type="text" class="form-control" id="userName" readonly>
                        </div>
                        <div class="single-row">
                            <div class="form-group">
                                <label for="highwayNumber">Highway Number:</label>
                                <input type="text" class="form-control" id="highwayNumber" placeholder="Enter highway number" required>
                            </div>
                            <div class="form-group">
                                <label for="exitNumber">Exit Number:</label>
                                <input type="text" class="form-control" id="exitNumber" placeholder="Enter exit number" required>
                            </div>
                        </div>
                        <div class="single-row">
                            <div class="form-group">
                                <label for="BufferModalLatitude">Latitude:</label>
                                <input type="text" class="form-control" id="BufferModalLatitude" readonly>
                            </div>
                            <div class="form-group">
                                <label for="BufferModalLongitude">Longitude:</label>
                                <input type="text" class="form-control" id="BufferModalLongitude" readonly>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveBufferButton">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Results Section -->
    <div class="container mt-4">
        <div id="dataDisplay">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="mt-3 mb-0">Search Results <span id="resultsCount"></span></h4>
                <div class="mt-3 mb-0">
                    <i class="fa fa-file-excel-o" style="font-size: 40px; color: green; display: none;" id="downloadButton" data-toggle="tooltip" title="Download Excel"></i>
                </div>
            </div>
            <!-- No records found message -->
            <div id="noRecordsMessage" class="text-center" style="display: none;">
                <h3>No records found.</h3>
            </div>
            <!-- Results Table -->
            <table class="table table-bordered" id="resultsTable" style="display: none;">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col" style="min-width:80px;"><input type="checkbox" id="selectAllCheckbox" checked><span style="display: none;">Select</span></th>
                        <th scope="col" style="min-width:80px;">Sr. No.</th>
                        <th scope="col" class="name">Name</th>
                        <th scope="col" class="address">Address</th>
                        <th scope="col" class="mobile">Distance</th>
                        <th scope="col" class="mobile">Mobile</th>
                        <th scope="col" class="mobile">Latitude</th>
                        <th scope="col" class="mobile">Longitude</th>
                        <th scope="col" class="name">County</th>
                        <th scope="col" class="name">Property Type</th>
                    </tr>
                </thead>
                <tbody id="resultsBody" class="table-wrap">
                    <!-- Results will be dynamically added here -->
                </tbody>
            </table>

            <div class="container mt-5" id="bufferButtonContainer" style="display: none;">
                <div class="d-flex align-items-center">
                    <button type="button" class="btn btn-primary mb-2 mr-3" id="bufferButton">
                        Save Data to Buffer <i class="fa fa-save" style="font-size:20px;"></i>
                    </button>
                    <p class="mb-0">Buffer Already Contains: <span id="bufferCount">{{buffer_data_count}} rows</span></p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts Display Data-->
<script>
    function displayResults(results) {
        const resultsBody = document.getElementById('resultsBody');
        const resultsTable = document.getElementById('resultsTable');
        const noRecordsMessage = document.getElementById('noRecordsMessage');
        const downloadButton = document.getElementById('downloadButton');
        const bufferButtonContainer = document.getElementById('bufferButtonContainer');
        const resultsCount = document.getElementById('resultsCount');

        resultsBody.innerHTML = '';

        resultsCount.textContent = '(' + results.length + ' Rows)';

        if (results.length === 0) {
            noRecordsMessage.style.display = 'block';
            resultsTable.style.display = 'none';
            downloadButton.style.display = 'none';
            bufferButtonContainer.style.display = 'none';
        } else {
            noRecordsMessage.style.display = 'none';
            resultsTable.style.display = 'table';
            downloadButton.style.display = 'inline';
            bufferButtonContainer.style.display = 'block';

            results.forEach((result, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" name="selected" value=${result[0]} checked></td>
                    <td>${index + 1}</td>
                    <td class="name">${result[1]}</td>
                    <td class="address">${result[2]}</td>
                    <td class="mobile">${result[3]}</td>
                    <td class="mobile">${result[4]}</td>
                    <td class="mobile">${result[5]}</td>
                    <td class="mobile">${result[6]}</td>
                    <td class="name">${result[7]}</td>
                    <td class="name">${result[8]}</td>
                `;
                resultsBody.appendChild(row);
            });
        }
        document.getElementById('dataDisplay').style.display = 'block';
    }
</script>

<!-- Save buffer Data and clear -->
<script>
    $(document).ready(function() {
        $('#bufferButton').on('click', function() {
            $('#bufferModal').modal('show');
            document.getElementById('BufferModalLatitude').value = document.getElementById('latitude').value;
            document.getElementById('BufferModalLongitude').value = document.getElementById('longitude').value;
            document.getElementById('userName').value = "{{ username }}";
        });

        // Handle form submission in the modal
        $('#saveBufferButton').on('click', function() {
            var userName = $('#userName').val();
            var highwayNumber = $('#highwayNumber').val();
            var exitNumber = $('#exitNumber').val();
            var latitude = $('#modalLatitude').val();
            var longitude = $('#modalLongitude').val();

            let input_data = {
                userName: userName,
                highwayNumber: highwayNumber,
                exitNumber: exitNumber,
                latitude: latitude,
                longitude: longitude
            };

            document.getElementById('overlay').style.display = 'block';
            document.getElementById('loader1').style.display = 'block';
            let selectedIds = [];
            $('input[name="selected"]:checked').each(function() {
                selectedIds.push($(this).val());
            });

            const data = { ids: selectedIds, input_data: input_data };
            $.ajax({
                url: '/save_data',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                timeout: 600000, 
                success: function(response) {
                    document.getElementById('overlay').style.display = 'none';
                    document.getElementById('loader1').style.display = 'none';
                    alert(response.message);
                    // Update the buffer count dynamically
                    $('#bufferCount').text(response.buffer_data_count + ' rows');
                    $('#viewBufferData').find('a').text('View Saved Data (' + response.buffer_data_count + ')');
                    // Close the modal
                    $('#bufferModal').modal('hide');
                }
            });
        });

        // Clear Saved Data
        $('#clearBufferData').on('click', function() {
            // Display confirmation dialog
            if (confirm("Are you sure you want to clear saved data?")) {
                $.ajax({
                    url: '/clear_data',
                    type: 'POST',
                    success: function(response) {
                        alert(response.message);
                        $('#dataDisplay').empty(); // Clear the data display on success
                        location.reload();
                    }
                });
            } else {
                // If user cancels, do nothing
                return false;
            }
        });
    });
</script>

<!-- Select All checkbox -->
<script>
    $(document).ready(function() {
        // Master checkbox change handler
        $('#selectAllCheckbox').change(function() {
            const isChecked = $(this).prop('checked');
            $('input[name="selected"]').prop('checked', isChecked);
        });

        // Individual checkbox change handler
        $('#resultsBody').on('change', 'input[name="selected"]', function() {
            const allChecked = $('input[name="selected"]:checked').length === $('input[name="selected"]').length;
            $('#selectAllCheckbox').prop('checked', allChecked);
        });
    });
</script>

<!-- Add this script tag for xlsx library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.4/xlsx.full.min.js"></script>

<!--  download excel -->
<script>
  $(document).ready(function() {
    $('#downloadButton').on('click', function() {
      const tableData = [];
      const headers = [];
      $('#resultsTable thead tr th').each(function() {
        //headers.push($(this).text());
        if ($(this).text() !== 'Select') { // Exclude 'Select' column
          headers.push($(this).text());
        }
      });
      tableData.push(headers);

      $('#resultsTable tbody tr').each(function() {
        const row = [];
        $(this).find('td').each(function(index) {
          if (index !== 0) { // Exclude the first column ('Select')
            if (index === 11) {
              // Handle URL column to fetch from anchor tag
              const url = $(this).find('a').attr('href');
              row.push(url);
            } else {
              row.push($(this).text());
            }
          }
        });
        tableData.push(row);
      });

      const ws = XLSX.utils.aoa_to_sheet(tableData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(data);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'search_results.xlsx';
      a.click();
    });
  });
</script>

<!-- Add POI -->
<script>
    document.getElementById('submitPoiButton').addEventListener('click', function() {
        const newPoi = document.getElementById('newPoiInputModal').value;
        if (newPoi) {
            fetch('/api/add_poi', { // Update the API endpoint as needed
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ poi: newPoi })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Handle successful addition (e.g., update the UI)
                    location.reload(); // Reload the page to show the updated list
                } else {
                    alert('Error adding point of interest');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error adding point of interest');
            });
        }
    });
</script>

<!-- Remove POI -->
<script>
function removePoi(poi) {
    if (confirm('Are you sure you want to remove "' + poi + '" from the Point of Interest list?')) {
        fetch('/api/remove_poi', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ poi: poi })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Remove the POI element from the DOM
                const poiElement = document.querySelector(`input[value="${poi}"]`).closest('.form-check');
                poiElement.remove();
                alert('Point of interest removed successfully.');
                window.location.reload();
            } else {
                alert('Error removing point of interest.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error removing point of interest.');
        });
    }
}
</script>

<!-- CSS for Select2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />

<!-- JS for Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="{{ url_for('static', filename='index_scripts.js') }}"></script>
<script src="{{ url_for('static', filename='range_scripts.js') }}"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0rSf88TVQe8jv0E7ZXMhRahTvz-566KU&libraries=places&callback=initMap" async defer></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0rSf88TVQe8jv0E7ZXMhRahTvz-566KU&v=3.exp&callback=initMap"></script>

<!-- <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBwg_LyNB9AsizTdmTEX2gp-TydKCxFv84&libraries=places&callback=initMap" async defer></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBwg_LyNB9AsizTdmTEX2gp-TydKCxFv84&v=3.exp&callback=initMap"></script> -->



<script>
    window.onload = function () {
        initMap();
    };
</script>
</body>
</html>
