@extends('Admin.layouts.master')

@section('content')
    @php
        $currentPage = 'manage_notification';
    @endphp
    <style>
        .error-message {
            color: #FF0000;
        }

        form .error-message {
            color: red;
            /* Set your desired color here */
        }

        form .input_class.error-message {
            color: #0e1726;
        }
    </style>

    <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">
                            <a class="d-flex align-items-center justify-content-center pl-2"
                                href="{{ route('manage.notification') }}">
                                <img class="back-btn" src="{{ asset('public/assets/img/left-arrow.svg') }}">
                                <h6 class="card-title p-0">Add Details</h6>
                            </a>
                        </div>
                        <div class="col-md-8">

                        </div>
                    </div>
                </div>
                <div class="col-xl-12 col-lg-12 col-sm-12  layout-spacing">
                    <div class="widget-content widget-content-area br-8 position-btn h-10">
                        <div class="view-details Article">
                            <form id="send_notification_form">
                                @csrf
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="company-name" class="label">Notification Content</label>
                                            <input type="text" class="form-control" name="title">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="company-name" class="label">Description</label>
                                            <textarea type="text" class="form-control" name="description"></textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="company-name" class="label">Upload Image</label>
                                            <input type="file" class="form-control" name="image" accept="image/*"
                                                onchange="previewImage(event)">
                                            <img id="preview" src="#" alt="your image" class="mt-3"
                                                style="display:none;width:20%;" />
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="location" class="label">When should this message start
                                                sending:</label>
                                            <div class="form-check form-check-sm form-check-custom form-check-solid me-3">
                                                <input class="form-check-input" type="radio" name="user_type"
                                                    value="1" id="select-all-ids" />
                                                <label class="form-check-label" for="select-all-ids">Send to subscribed
                                                    users who are in their respective states</label><br>
                                                <div id="dropdown-1"
                                                    style="display: none; max-height: 200px; overflow-y: auto;">
                                                    <div class="form-check">
                                                        <input class="form-check-input select-all-checkbox" type="checkbox"
                                                            id="select-all-1" />
                                                        <label class="form-check-label" for="select-all-1">Select All
                                                            States</label>
                                                    </div>
                                                    @foreach ($state as $states)
                                                        <div class="form-check">
                                                            <input class="form-check-input state-checkbox" type="checkbox"
                                                                name="states[]" value="{{ $states['id'] }}"
                                                                id="state-1-{{ $states['id'] }}" />
                                                            <label class="form-check-label"
                                                                for="state-1-{{ $states['id'] }}">{{ $states['name'] }}</label>
                                                        </div>
                                                    @endforeach
                                                </div>
                                                <input class="form-check-input" type="radio" name="user_type"
                                                    id="select-popular-ids" value="2" />
                                                <label class="form-check-label" for="select-popular-ids">Send to
                                                    unsubscribed users who are in their respective states</label><br>
                                                <div id="dropdown-2"
                                                    style="display: none; max-height: 200px; overflow-y: auto;">
                                                    <div class="form-check">
                                                        <input class="form-check-input select-all-checkbox" type="checkbox"
                                                            id="select-all-2" />
                                                        <label class="form-check-label" for="select-all-2">Select All
                                                            States</label>
                                                    </div>
                                                    @foreach ($state as $states)
                                                        <div class="form-check">
                                                            <input class="form-check-input state-checkbox" type="checkbox"
                                                                name="states[]" value="{{ $states['id'] }}"
                                                                id="state-2-{{ $states['id'] }}" />
                                                            <label class="form-check-label"
                                                                for="state-2-{{ $states['id'] }}">{{ $states['name'] }}</label>
                                                        </div>
                                                    @endforeach
                                                </div>
                                                <input class="form-check-input" type="radio" name="user_type"
                                                    id="select-ids" value="3" />
                                                <label class="form-check-label" for="select-ids">Send to subscribed and
                                                    unsubscribed users who are in their respective states</label><br>
                                                <div id="dropdown-3"
                                                    style="display: none; max-height: 200px; overflow-y: auto;">
                                                    <div class="form-check">
                                                        <input class="form-check-input select-all-checkbox"
                                                            type="checkbox" id="select-all-3" />
                                                        <label class="form-check-label" for="select-all-3">Select All
                                                            States</label>
                                                    </div>
                                                    @foreach ($state as $states)
                                                        <div class="form-check">
                                                            <input class="form-check-input state-checkbox" type="checkbox"
                                                                name="states[]" value="{{ $states['id'] }}"
                                                                id="state-3-{{ $states['id'] }}" />
                                                            <label class="form-check-label"
                                                                for="state-3-{{ $states['id'] }}">{{ $states['name'] }}</label>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                            <div id="user_type_error" class="error-message"></div>
                                        </div>
                                    </div>



                                    <div class="col-md-12">
                                        <div class="notification-card">
                                            <label for="company-name" class="label">Delivery Schedule</label>

                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="company-name" class="label">When should this message
                                                        start sending?</label>
                                                    <div class="form-group radio-btn">
                                                        <input type="radio" class="form-control" name="schedule_radio1"
                                                            id="push_schedule_radi01" value="0">
                                                        <label for="push_schedule_radi01"
                                                            class="label">Immediately</label>
                                                    </div>
                                                    <div class="form-group radio-btn">
                                                        <input type="radio" class="form-control" name="schedule_radio1"
                                                            id="push_schedule_radi02" value="1">
                                                        <label for="push_schedule_radi02" class="label">Specific
                                                            Time</label>
                                                    </div>
                                                    <div class="form-group checkbox-btsss" style="display: none;">
                                                        <input type="datetime-local" class="form-control"
                                                            name="schedule_date" min="{{ date('Y-m-d\TH:i') }}">
                                                    </div>
                                                    <label id="schedule_radio1-error" class="error-message"
                                                        for="schedule_radio1"></label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <button class="download-btn-custom mt-3 custom-width-10" type="submit"
                                            id="store_notification_btn">
                                            <span>Submit</span>
                                        </button>
                                    </div>
                                </div>
                            </form>

                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
@endsection
@section('section_script')
    <script>
        $(document).ready(function() {
            // Custom validator for checking state checkboxes
            $.validator.addMethod('stateRequired', function(value, element) {
                let selectedUserType = $('input[name="user_type"]:checked').val();
                if (selectedUserType) {
                    let dropdownId = `dropdown-${selectedUserType}`;
                    return $(`#${dropdownId} .state-checkbox:checked`).length > 0;
                }
                return true;
            }, 'Please select at least one state.');

            // Validate the form
            $('#send_notification_form').validate({
                ignore: [],
                debug: false,
                rules: {
                    title: {
                        required: true
                    },
                    description: {
                        required: true
                    },
                    image: {
                        required: true
                    },
                    user_type: {
                        required: true
                    },
                    schedule_radio1: {
                        required: true
                    },
                    schedule_date: {
                        required: function() {
                            return $('#push_schedule_radi02').is(':checked');
                        }
                    },
                    'states[]': {
                        stateRequired: true
                    }
                },
                messages: {
                    title: {
                        required: 'Please enter this field'
                    },
                    description: {
                        required: 'Please enter this field'
                    },
                    image: {
                        required: 'Please upload an image file'
                    },
                    user_type: {
                        required: 'Please select at least one category'
                    },
                    schedule_radio1: {
                        required: 'Please select a delivery schedule'
                    },
                    schedule_date: {
                        required: 'Please select a specific time'
                    },
                    'states[]': {
                        stateRequired: 'Please select at least one state.'
                    }
                },
                errorClass: 'error-message',
                errorPlacement: function(error, element) {
                    if (element.attr("name") == "user_type") {
                        error.appendTo("#user_type_error").addClass('error-message');
                    } else if (element.attr("name") == "schedule_radio1") {
                        error.insertAfter("#push_schedule_radi02").addClass('error-message');
                    } else if (element.attr("name") == "states[]") {
                        error.insertAfter(`#dropdown-${$('input[name="user_type"]:checked').val()}`)
                        error.appendTo("#user_type_error").addClass('error-message');
                    } else {
                        error.insertAfter(element).addClass('error-message');
                    }
                },
                submitHandler: function(form) {
                    var formData = new FormData(form);
                    let base_url = url_path;
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });
                    $.ajax({
                        url: base_url + '/insert_notification',
                        type: 'POST',
                        data: formData,
                        beforeSend: function() {
                            $('#store_notification_btn').html('Please wait...');
                            $('#store_notification_btn').attr('disabled', true);
                        },
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.status_code == 200) {
                                toastr.success(result.message);
                                setTimeout(function() {
                                    window.location.href = base_url +
                                        "/manage-notification";
                                }, 2000);
                            } else if (result.status_code == 422) {
                                // Display validation errors using toastr
                                $.each(result.errors, function(key, value) {
                                    toastr.error(value);
                                    setTimeout(function() {
                                        window.location.href = base_url +
                                            "/manage-notification";
                                    }, 2000);
                                });
                            } else {
                                toastr.error('Something Went Wrong');
                                setTimeout(function() {
                                    window.location.href = base_url +
                                        "/manage-notification";
                                }, 2000);
                            }
                            $('#store_notification_btn').attr('disabled', false);
                            $('#store_notification_btn').text('Submit');
                        },
                    });
                }
            });

            // Hide date and time input by default
            $('.checkbox-btsss').hide();

            // Show/hide date and time input based on radio button selection
            $('#push_schedule_radi01').click(function() {
                $('.checkbox-btsss').hide();
                $('input[name="schedule_date"]').val(''); // Clear date and time input
            });

            $('#push_schedule_radi02').click(function() {
                $('.checkbox-btsss').show();
            });

        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            function handleUserTypeChange() {
                var dropdowns = [
                    document.getElementById('dropdown-1'),
                    document.getElementById('dropdown-2'),
                    document.getElementById('dropdown-3')
                ];

                dropdowns.forEach(function(dropdown, index) {
                    if (index + 1 == this.value) {
                        dropdown.style.display = 'block';
                        toggleCheckboxes(dropdown, false);
                    } else {
                        dropdown.style.display = 'none';
                        toggleCheckboxes(dropdown, true);
                    }
                }, this);
            }

            function toggleCheckboxes(dropdown, disable) {
                var checkboxes = dropdown.querySelectorAll('.form-check-input');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].disabled = disable;
                }
            }

            var userTypeRadios = document.getElementsByName('user_type');
            for (var i = 0; i < userTypeRadios.length; i++) {
                userTypeRadios[i].addEventListener('change', handleUserTypeChange);
            }

            var checkedRadio = document.querySelector('input[name="user_type"]:checked');
            if (checkedRadio) {
                handleUserTypeChange.call(checkedRadio);
            }

            function handleSelectAllChange() {
                var dropdown = this.closest('div[id^="dropdown-"]');
                var checkboxes = dropdown.querySelectorAll('.state-checkbox');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].checked = this.checked;
                }
            }

            var selectAllCheckboxes = document.querySelectorAll('.select-all-checkbox');
            for (var i = 0; i < selectAllCheckboxes.length; i++) {
                selectAllCheckboxes[i].addEventListener('change', handleSelectAllChange);
            }
        });
    </script>
    <script>
        function previewImage(event) {
            var input = event.target;
            var reader = new FileReader();

            reader.onload = function() {
                var preview = document.getElementById('preview');
                preview.src = reader.result;
                preview.style.display = 'block';
            };

            if (input.files && input.files[0]) {
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
@endsection
