@extends('Admin.layouts.master')

@section('content')
@php
$currentPage = 'manage-reports';
@endphp

<div class="layout-px-spacing">
    <div class="middle-content container-xxl p-0">
        <div class="row layout-top-spacing">
            <div class="top-tabel">
                <div class="row">
                    <div class="col-md-4">
                        <h6 class="card-title">Manage Reports & Analysis</h6>
                    </div>
                    <div class="col-md-8"></div>
                </div>
            </div>
        </div>
        <form id="reportForm" action="{{ route('reports.export') }}" method="POST">
            @csrf
            <div class="row widget-content widget-content-area br-8 position-btn m-auto py-3" style="overflow: auto;">
                <div class="col-6">
                    <label for="startDate">Start Date:</label>
                    <input class="form-control" placeholder="Select start date" type="text" id="startDate" name="startDate">
                </div>
                <div class="col-md-6">
                    <label for="endDate">End Date:</label>
                    <input class="form-control" placeholder="Select end date" type="text" id="endDate" name="endDate">
                </div>
            </div>
            <div class="row widget-content widget-content-area br-8 position-btn m-auto py-3" style="overflow: auto;">
                @php
                    $points = [
                        'Total Subscribed',
                        'Total Users',
                        'Redemptions',
                        'Redemptions for Specific Restaurants',
                        'Referrals Made',
                        'Referees Joined',
                        'Subscriptions Cancelled'
                    ];
                @endphp

                @foreach($points as $point)
                <div class="col-md-12">
                    <div class="card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center collapsed" data-toggle="collapse" data-target="#collapse{{ $loop->index }}" aria-expanded="false" aria-controls="collapse{{ $loop->index }}" role="button">
                            <label>
                                <input type="radio" name="reportType" value="{{ $point }}" class="report-type-radio"> {{ $point }}
                            </label>
                            <span class="toggle-icon"></span>
                        </div>
                        <div id="collapse{{ $loop->index }}" class="collapse state-checkboxes" data-point="{{ $point }}">
                            <div class="card-body">
                                @if($point === 'Redemptions for Specific Restaurants')
                                    <label>
                                        <input type="checkbox" class="check-all"> Check All
                                    </label>
                                    <div class="state-checkboxes-container">
                                        @foreach($restaurants as $restaurant)
                                        <label class="state-checkbox-label">
                                            <input type="checkbox" name="restaurants[]" value="{{ $restaurant->id }}" class="state-checkbox"> {{ $restaurant->name }}
                                        </label>
                                        @endforeach
                                    </div>
                                @else
                                    <label>
                                        <input type="checkbox" class="check-all"> Check All
                                    </label>
                                    <div class="state-checkboxes-container">
                                        @foreach($states as $state)
                                        <label class="state-checkbox-label">
                                            <input type="checkbox" name="states[]" value="{{ $state->id }}" class="state-checkbox"> {{ $state->name }}
                                        </label>
                                        @endforeach
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
            <div class="row">
                <div class="col-md-12 text-center">
                    <button type="submit" class="download-btn-custom mt-3 custom-width-10">
                        <span>Download</span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

@section('section_script')
<script>
    // Initialize Flatpickr for the date range with placeholders and set maxDate to today
    flatpickr("#startDate", {
        dateFormat: "m/d/Y", // Change date format to 'm/d/Y'
        maxDate: "today",
        onChange: function (selectedDates, dateStr) {
            // Set the minimum date for the end date input
            flatpickr("#endDate").set("minDate", dateStr);
        }
    });

    flatpickr("#endDate", {
        dateFormat: "m/d/Y", // Change date format to 'm/d/Y'
        maxDate: "today",
    });

    // Show/hide checkboxes based on selected radio button
    document.querySelectorAll('input[name="reportType"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            document.querySelectorAll('.state-checkboxes').forEach(function(checkboxDiv) {
                checkboxDiv.classList.remove('show');
                checkboxDiv.querySelectorAll('.state-checkbox').forEach(function(checkbox) {
                    checkbox.disabled = true;
                });
                checkboxDiv.querySelector('.check-all').disabled = true;
            });
            var selectedPoint = this.value;
            document.querySelectorAll('.state-checkboxes[data-point="' + selectedPoint + '"]').forEach(function(checkboxDiv) {
                checkboxDiv.classList.add('show');
                checkboxDiv.querySelectorAll('.state-checkbox').forEach(function(checkbox) {
                    checkbox.disabled = false;
                });
                checkboxDiv.querySelector('.check-all').disabled = false;
            });
        });
    });

    // Handle "Check All" functionality
    document.querySelectorAll('.check-all').forEach(function(checkAllBox) {
        checkAllBox.addEventListener('change', function() {
            var checkboxes = this.closest('.state-checkboxes').querySelectorAll('.state-checkbox');
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = checkAllBox.checked;
            });
        });
    });

    // Form validation before submission
    document.getElementById('reportForm').addEventListener('submit', function(event) {
        var selectedRadio = document.querySelector('input[name="reportType"]:checked');
        var selectedCheckboxes = document.querySelectorAll('.state-checkboxes.show .state-checkbox:checked');
        var startDate = document.getElementById("startDate").value;
        var endDate = document.getElementById("endDate").value;
        var today = new Date().toISOString().split('T')[0]; // Get today's date in YYYY-MM-DD format

        if (!startDate) {
            event.preventDefault(); // Prevent form submission
            toastr.error('Please select a start date.');
            return;
        }

        if (!endDate) {
            event.preventDefault(); // Prevent form submission
            toastr.error('Please select an end date.');
            return;
        }

        if (new Date(startDate) > new Date(today) || new Date(endDate) > new Date(today)) {
            event.preventDefault(); // Prevent form submission
            toastr.error('Please select a date within the allowed range.');
            return;
        }

        if (!selectedRadio) {
            event.preventDefault(); // Prevent form submission
            toastr.error('Please select a report type.');
            return;
        }

        if (selectedCheckboxes.length === 0) {
            event.preventDefault(); // Prevent form submission
            toastr.error('Please select at least one record.');
            return;
        }

        // Add a timeout to ensure the form data is sent before refreshing
        setTimeout(function() {
            location.reload();
        }, 1000); // Adjust the timeout as needed (milliseconds)
    });
</script>

<style>
    .state-checkboxes-container {
        display: flex;
        flex-wrap: wrap;
    }
    .state-checkbox-label {
        margin-right: 10px;
        display: inline-block;
    }
    .card {
        border: 1px solid #ccc;
        margin-bottom: 15px;
    }
    .card-header {
        background-color: #f8f9fa;
        padding: 10px;
        border-bottom: 1px solid #ddd;
        cursor: pointer;
    }
    .card-header .toggle-icon {
        transition: transform 0.3s;
    }
    .card-header.collapsed .toggle-icon {
        transform: rotate(180deg);
    }
    .card-body {
        padding: 10px;
    }
    .download-btn-custom {
        display: inline-block;
        background-color: #007bff;
        color: #fff;
        padding: 10px 20px;
        text-decoration: none;
        border-radius: 5px;
    }
    .text-center {
        text-align: center;
    }
    .collapse.show {
        display: block;
    }
    .collapse {
        display: none;
    }
</style>
@endsection
