<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Maps Reports Creation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='index_header.css') }}">
    <!-- Custom CSS -->
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Arial', sans-serif;
        }
        .container {
            margin-top: 30px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #007bff;
            color: #fff;
            font-weight: bold;
            border-radius: 15px 15px 0 0;
        }
        .form-control {
            border-radius: 10px;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075);
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(38, 143, 255, 0.25);
        }
        .btn-primary {
            background-color: #007bff;
            border-radius: 10px;
            transition: background-color 0.3s ease;
        }
        .btn-primary:hover {
            background-color: #0056b3;
        }
        .footer {
            margin-top: 30px;
            padding: 20px;
            background-color: #007bff;
            color: #fff;
            text-align: center;
            border-radius: 10px;
        }

        .notification {
            display: none;
            position: fixed;
            bottom: 10px;
            right: 10px;
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }
        .navbar{
            width: 95%;
            margin-left:30px;
        }
    </style>
</head>
<body>


<h2 style="text-align:center; font-weight: bold; padding: 15px;">Google Maps Scraper Reports Generator</h2>

<div class="navbar">
    <a 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> View 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') }}" class="active" ><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> {{ username }}</a>
</div>




    <!-- Main Container -->
    <div class="container">
        <div class="card">
            <div class="card-header">
                Reports Creation
            </div>
            <div class="card-body">
                <form id="reportForm">

                    <div class="form-group mb-3">
                        <label for="userSelect" class="form-label">Select User(s):</label>
                        <select id="userSelect" class="form-control" multiple="multiple"></select>
                    </div>


                    <div class="form-group mb-3">
                        <label for="highwaySelect" class="form-label">Select Highway(s):</label>
                        <select id="highwaySelect" class="form-control" multiple="multiple"></select>
                    </div>
                    <div class="form-group mb-3">
                        <label for="exitSelect" class="form-label">Select Exit(s):</label>
                        <select id="exitSelect" class="form-control" multiple="multiple" disabled></select>
                    </div>
                    <div class="row mb-3">
                        <div class="form-group col-md-6">
                            <label for="startDate" class="form-label">Start Date:</label>
                            <input type="text" id="startDate" class="form-control" placeholder="Select Start Date" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="endDate" class="form-label">End Date:</label>
                            <input type="text" id="endDate" class="form-control" placeholder="Select End Date" disabled>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Create Report</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Footer -->
<!--    <div class="footer">-->
<!--        © 2024 Corporate Reports. All Rights Reserved.-->
<!--    </div>-->

    <!-- jQuery, Select2, and Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- jQuery UI for Datepicker -->
    <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>

    <!-- Custom Script -->

    <script>
        $(document).ready(function() {
            // Initialize Select2 for the dropdowns
            $('#highwaySelect').select2({
                placeholder: 'Select Highway(s)'
            });

            $('#exitSelect').select2({
                placeholder: 'Select Exit(s)'
            });

            $('#userSelect').select2({
                placeholder: 'Select User(s)'
            });


            // Fetch highways from the API on page load
            $.ajax({
                url: '/api/get_users',
                method: 'GET',
                success: function(data) {
                    $('#userSelect').empty();
                    data.users.forEach(function(user) {
                        // $('#userSelect').append(new Option(user.name, user.id));
                        $('#userSelect').append(new Option(user));
                    });
                },
                error: function() {
                    alert('Failed to fetch highways.');
                }
            });



            // Fetch highways from the API on page load
            $.ajax({
                url: '/api/get_highways',
                method: 'GET',
                success: function(data) {
                    $('#highwaySelect').empty();
                    data.highways.forEach(function(highway) {
                        $('#highwaySelect').append(new Option(highway.name, highway.name));
                    });
                },
                error: function() {
                    alert('Failed to fetch highways.');
                }
            });

            // Handle the change event on highway selection
            $('#highwaySelect').change(function() {
                const selectedHighways = $(this).select2('data').map(highway => highway.text);
                if (selectedHighways.length > 0) {
                    $('#exitSelect').prop('disabled', false);
                    $.ajax({
                        url: '/api/get_exits',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ state_ids: selectedHighways }),
                        success: function(data) {
                            $('#exitSelect').empty();
                            data.exits.forEach(function(exit) {
                                $('#exitSelect').append(new Option(exit.name, exit.name));
                            });
                        },
                        error: function() {
                            alert('Failed to fetch exits.');
                        }
                    });
                } else {
                    $('#exitSelect').prop('disabled', true).empty();
                }
            });

            // Handle form submission
            $('#reportForm').submit(function(event) {
                event.preventDefault(); // Prevent default form submission

                // Gather selected values
                const selectedUsers = $('#userSelect').val();
                const selectedHighways = $('#highwaySelect').val();
                const selectedExits = $('#exitSelect').val();
                const startDate = $('#startDate').val();
                const endDate = $('#endDate').val();

                // Send data to the report generation API
                $.ajax({
                    url: '/api/report', // Update with your report generation API endpoint
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        users: selectedUsers,
                        highways: selectedHighways,
                        exits: selectedExits,
                        start_date: startDate,
                        end_date: endDate
                    }),
                    xhrFields: {
                        responseType: 'blob' // Important to ensure response is treated as binary
                    },
                    success: function(data) {

                        const currentDate = new Date();
                        const timestamp = currentDate.getFullYear() +
                            ('0' + (currentDate.getMonth() + 1)).slice(-2) +
                            ('0' + currentDate.getDate()).slice(-2) + '_' +
                            ('0' + currentDate.getHours()).slice(-2) + '_' +
                            ('0' + currentDate.getMinutes()).slice(-2);
                        const filename = `report_${timestamp}.xlsx`;

                        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);

                        showNotification('Report Generated Successfully.');
                        alert("Report Generated Successfully.");
                    },
                    error: function() {
                        showNotification('Failed to generate report.');
                        alert("Failed to generate report.");
                    }
                });
            });

            function showNotification(message) {
                let notification = $('<div class="notification"></div>');
                notification.text(message);
                $('body').append(notification);
                notification.fadeIn().delay(3000).fadeOut(function() {
                    $(this).remove();
                });
            }


            // Date Pickers Initialization
            const today = new Date();
            const formattedToday = $.datepicker.formatDate('yy-mm-dd', today);

            $("#startDate").datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true,
                maxDate: formattedToday,
                onSelect: function(selectedDate) {
                    $("#endDate").prop('disabled', false);
                    $("#endDate").datepicker("option", "minDate", selectedDate);
                }
            });

            $("#endDate").datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true
            });

        });
    </script>




</body>
</html>
