@extends('layouts.adminmaster')

@section('styles')

    <!-- INTERNAL multiselecte css-->
    <link href="{{asset('build/assets/plugins/multipleselect/multiple-select.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
    <link href="{{asset('build/assets/plugins/multi/multi.min.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

    <!-- INTERNAl Summernote css -->
    <link rel="stylesheet" href="{{asset('build/assets/plugins/summernote/summernote.css')}}?v=<?php echo time(); ?>">

    <!-- INTERNAL Datepicker css-->
    <link rel="stylesheet" href="{{ asset('build/assets/plugins/flatpickr/flatpickr.min.css') }}">

    <style>
        #unsubscribeSpan {
            cursor: pointer;
        }
        #indUsers .ms-drop {
            z-index: 998;
        }
    </style>

@endsection

@section('content')

    <!--Page header-->
    <div class="page-header d-xl-flex d-block">
        <div class="page-leftheader">
            <h4 class="page-title"><span class="font-weight-normal text-muted ms-2">{{ lang('Create Campaign', 'menu') }}</span></h4>
        </div>
    </div>
    <!--End Page header-->

    <div class="col-xl-12 col-lg-12 col-md-12">
        <div class="card ">
            <form id="campaingCreateForm" enctype="multipart/form-data">
                <div class="card-header border-0 d-md-max-block">
                    <h4 class="card-title">{{ lang('Create Campaign') }}</h4>
                </div>
                <div class="card-body overflow-scroll custom-show-data">
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Template') }}</label>
                                <select class="form-control select2" id="template" data-placeholder="{{ lang('Choose Template') }}">
                                    <option></option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Type') }} <span class="text-danger">*</span></label>
                                <select name="sendType" class="form-control select2 select2type" data-placeholder="{{ lang('Choose Type') }}">
                                    <option></option>
                                    <option value="individualUsers">{{ lang('All Users') }}</option>
                                    <option value="batch">{{ lang('Batch') }}</option>
                                    <option value="livechat">{{ lang('Livechat Users') }}</option>
                                    <option value="newsletter">{{ lang('News Letter Users') }}</option>
                                </select>
                                <span class="text-danger" id="sendTypeError"></span>
                            </div>
                        </div>
                        <div class="col-xl-6 d-none" id="indUsers">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Users') }}</label>
                                <select name="selectedUsers[]" data-placeholder="{{ lang('Select Users') }}" class="filter-multi" id="select2" multiple>

                                </select>
                                <span class="text-danger" id="selectedUsersError"></span>
                            </div>
                        </div>
                        <div class="col-xl-6 d-none" id="batchWise">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Batch') }} <span class="text-danger">*</span></label>
                                <select name="batchName[]" id="batchName" multiple class="form-control select2" data-placeholder="{{ lang('Choose Batch') }}">
                                    <option></option>
                                </select>
                                <span class="text-danger" id="batchNameError"></span>
                            </div>
                        </div>
                        <div class="col-xl-6 d-none" id="livechatUsers">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Users') }} <span class="text-danger">*</span></label>
                                <select name="livechatUsers[]" id="livechatUsersSelect" multiple class="form-control select2" data-placeholder="{{ lang('Choose Users') }}">
                                    <option></option>
                                </select>
                                <span class="text-danger" id="livechatUsersError"></span>
                            </div>
                        </div>
                        <div class="col-xl-6 d-none" id="newsletterUsers">
                            <div class="form-group">
                                <label class="form-label">{{ lang('Choose Users') }}</label>
                                <select name="newsletterUsers[]" id="newsletterUsersSelect" data-placeholder="{{ lang('Choose Users') }}" class="filter-multi" id="select2" multiple>

                                </select>
                                <span class="text-danger" id="newsletterUsersError"></span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="form-group">
                                <label class="form-label">{{lang('Mail Subject')}} <span class="text-red">*</span></label>
                                <input type="text" name="subject" id="subject" placeholder="{{ lang('Enter subject for email') }}" class="form-control">
                                <span class="text-danger" id="mailSubjectError"></span>
                            </div>
                        </div>
                        <div class="col-xl-12">
                            <div class="form-group">
                                <label class="form-label">{{lang('Email Body')}} <span class="text-red">*</span></label>
                                <textarea rows="25" id="messageTextarea" class="summernote form-control" name="message">

                                </textarea>
                                <span class="text-danger" id="mailMessageError"></span>
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="form-group">
                                <label class="form-label">{{lang('Schedule Campaign')}}</label>
                                <div class="input-group">
                                    <div class="input-group-text">
                                        <i class="feather feather-calendar"></i>
                                    </div>
                                    <input class="form-control fc-datepicker" placeholder="YYYY-MM-DD" type="text" name="date" id="date" autocomplete="off">
                                </div>
                                <span id="dateError" class="text-danger alert-message"></span>
                            </div>
                            <div class="form-group">
                                <label class="form-label">{{lang('Unsubscribe Link')}} </label>
                                <span class="badge badge-info" id="unsubscribeSpan">&#123;&#123;unsubscribe_link&#125;&#125;</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <div class="form-group float-end">
                        <button class="btn btn-secondary" type="submit">{{ lang('Submit') }}</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

@endsection

@section('scripts')

    <!-- INTERNAL multiselecte js-->
    <script src="{{asset('build/assets/plugins/multipleselect/multiple-select.js')}}?v=<?php echo time(); ?>"></script>

    <!-- INTERNAL Summernote js  -->
    <script src="{{asset('build/assets/plugins/summernote/summernote.js')}}"></script>

    <!-- Date & Time Picker JS -->
    <script src="{{ asset('build/assets/plugins/flatpickr/flatpickr.min.js') }}"></script>

    <script>
        $(function() {
            "use strict";

            // Variables
            var SITEURL = '{{ url('') }}';

            document.querySelector('#campaingCreateForm').onsubmit = async (e) => {
                e.preventDefault();
                ['sendTypeError', 'selectedUsersError', 'batchNameError', 'livechatUsersError', 'newsletterUsersError', 'mailSubjectError', 'mailMessageError'].forEach(id => document.querySelector(`#${id}`).innerHTML = "");

                let selectedUsers = Array.from(document.querySelector('#select2').selectedOptions).map(option => option.value),
                    sendType = document.querySelector('.select2type').value,
                    batchName = Array.from(document.querySelector('#batchName').selectedOptions).map(option => option.value),
                    livechatUsersSelect = Array.from(document.querySelector('#livechatUsersSelect').selectedOptions).map(option => option.value),
                    newsletterUsersSelect = Array.from(document.querySelector('#newsletterUsersSelect').selectedOptions).map(option => option.value),
                    subject = document.querySelector('#subject').value,
                    message = summerNote[0].value,
                    time = document.querySelector('#date').value,
                    moveforward = true;

                if (!sendType) {
                    document.querySelector('#sendTypeError').innerHTML = "{{ lang('Choose type field is required') }}";
                    moveforward = false;
                }

                if (sendType === 'individualUsers' && !selectedUsers.length) {
                    document.querySelector('#selectedUsersError').innerHTML = "{{ lang('Please select users') }}";
                    moveforward = false;
                }

                if (sendType === 'batch' && !batchName) {
                    document.querySelector('#batchNameError').innerHTML = "{{ lang('Please select batch') }}";
                    moveforward = false;
                }

                if (sendType === 'livechat' && !livechatUsersSelect) {
                    document.querySelector('#livechatUsersError').innerHTML = "{{ lang('Please select users') }}";
                    moveforward = false;
                }

                if (sendType === 'newsletter' && !newsletterUsersSelect) {
                    document.querySelector('#newsletterUsersError').innerHTML = "{{ lang('Please select users') }}";
                    moveforward = false;
                }

                if (!subject) {
                    document.querySelector('#mailSubjectError').innerHTML = "{{ lang('Subject field is required') }}";
                    moveforward = false;
                }

                if (!message) {
                    document.querySelector('#mailMessageError').innerHTML = "{{ lang('Email body field is required') }}";
                    moveforward = false;
                }
                if (moveforward) {
                    const postdata = { sendType, selectedUsers, batchName, livechatUsersSelect, newsletterUsersSelect, subject, message, time };
                    const response = await fetch('{{ route('admin.campaign.send') }}', {
                        method: "POST",
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify(postdata),
                    });
                    const data = await response.json();
                    if (data.fail && data.fail == 'true') {
                        location.reload();
                    }
                    if (data.success) {
                        localStorage.setItem('success', data.success);
                        location.href = SITEURL + '/admin/emailCampaigns';
                    }
                }

            }

            let templates,summerNote;


            document.getElementById('unsubscribeSpan').addEventListener('click', function() {
                // Get the text from the span
                var textToCopy = this.textContent;

                // Copy the text to the clipboard
                navigator.clipboard.writeText(textToCopy).then(function() {
                    toastr.success('{{ lang('Text copied successfully.') }}')
                }).catch(function(error) {
                    console.error('Error copying text: ', error);
                });
            });

            (function($) {

                // Csrf Field
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                templates = @json($templates);
                templates.forEach((data) => {
                    $('#template').append(new Option(data.title, data.id));
                });

                let usersList = @json($allUsers);
                usersList.forEach((data) => {
                    $('#select2').append(new Option(data, data));
                });

                let livecustomers = @json($livecustomers);
                livecustomers.forEach((data) => {
                    $('#livechatUsersSelect').append(new Option(data, data));
                })

                let newslettercustomers = @json($newslettercustomers);
                newslettercustomers.forEach((data) => {
                    $('#newsletterUsersSelect').append(new Option(data, data));
                })

                let batches = @json($batches);
                Object.values(batches).forEach((data) => {
                    $('#batchName').append(new Option(data, data));
                })

                $(document).ready(function() {
                    $('.select2').select2({
                        minimumResultsForSearch: '',
                        placeholder: "Search",
                        width: '100%'
                    });
                });

                // Initialize select2 on the select element
                $('.filter-multi').multipleSelect({
                    filter: true,
                });

                summerNote = $('.summernote').summernote();

            })(jQuery);

            /* To choose date */
            flatpickr(".fc-datepicker",{
                minDate: "today",
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                minTime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
            });

            document.querySelector('#template').onchange = (e) => {
                let selected = templates.filter(data => data.id === parseInt(e.target.value));

                if (selected.length > 0) {
                    $('.summernote').summernote('code', selected[0].message);
                    document.querySelector('#subject').value = selected[0].subject;
                } else {
                    console.error('No template found with the selected ID');
                }
            }

            document.querySelector('.select2type').onchange = (e) => {
                if (e.target.value == 'batch') {
                    document.querySelector('#livechatUsers').classList.add('d-none');
                    document.querySelector('#indUsers').classList.add('d-none');
                    document.querySelector('#batchWise').classList.remove('d-none');
                    document.querySelector('#newsletterUsers').classList.add('d-none');
                } else if(e.target.value == 'individualUsers') {
                    document.querySelector('#livechatUsers').classList.add('d-none');
                    document.querySelector('#indUsers').classList.remove('d-none');
                    document.querySelector('#batchWise').classList.add('d-none');
                    document.querySelector('#newsletterUsers').classList.add('d-none');
                } else if(e.target.value == 'newsletter') {
                    document.querySelector('#livechatUsers').classList.add('d-none');
                    document.querySelector('#indUsers').classList.add('d-none');
                    document.querySelector('#batchWise').classList.add('d-none');
                    document.querySelector('#newsletterUsers').classList.remove('d-none');
                } else {
                    document.querySelector('#livechatUsers').classList.remove('d-none');
                    document.querySelector('#indUsers').classList.add('d-none');
                    document.querySelector('#batchWise').classList.add('d-none');
                    document.querySelector('#newsletterUsers').classList.add('d-none');
                }
            }

        });
    </script>
@endsection
