@extends('layouts.admin')

@section('content')

@include('admin.partials.ckeditor.ckeditor')
    <!-- <div class="text-right">
        <a href="/banner/reports/history" class="btn btn-primary">Email History</a>
    </div> -->
    <!-- Start Date Form Text -->
    <div class="form-group">
        {!! Form::label('start_date', 'Start Date') !!}
        {!! Form::text('start_date', date('Y-m-d', strtotime('first day of last month')), ['class' => 'form-control', 'id' => 'start_date']) !!}
    </div>
    <!-- End date Form Text -->
    <div class="form-group">
        {!! Form::label('end_date', 'End date') !!}
        {!! Form::text('end_date', date('Y-m-d', strtotime('last day of last month')), ['class' => 'form-control', 'id' => 'end_date']) !!}
    </div>
    <!-- Company Form Text -->
    <div class="form-group">
        {!! Form::label('company', 'Company') !!}
        {!! Form::text('company', '', ['class' => 'form-control', 'id' => 'company']) !!}
    </div>
    <!-- Form Submit -->
    <div class="form-group">
        {!! Form::submit('Create Reports', ['class' => 'btn btn-primary form-control', 'id' => 'create_reports']) !!}
    </div>

    <div id="alerts">
        <div class="alert alert-success alert-dismissible fade in" style="display:none">
            <!-- <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> -->
            <strong>Success!</strong> <span class="message"></span>
        </div>
        <div class="alert alert-danger alert-dismissible fade in" style="display:none">
            <!-- <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> -->
            <strong>Error!</strong> <span class="message"></span>
        </div>
        <div class="spinner text-center" style="display:none">
            <i class="fa fa-spinner fa-spin"></i>
        </div>
    </div>

    <div class="reports-container" style="margin-bottom:15px;"></div>

    <input type="hidden" id="reportfiles">
@endsection

@push('scripts')
    <script>

        "use strict";

        $(function () {
            $( "#company" ).autocomplete({
                source: <?= $companies; ?>
            });
            // CKEDITOR.replace('email_body', {
            //     language: 'en',
            //     height: 350,
            //     extraPlugins: 'youtube',
            //     filebrowserBrowseUrl: '/libs/file_manager/elfinder.html'
            // });
            var monthNames = ["January", "February", "March", "April", "May", "June",
              "July", "August", "September", "October", "November", "December"
            ];
            var d= new Date();
            // var text = "<p>Hello,</p><p>Attached is the "+d.getFullYear()+" "+monthNames[d.getMonth()-1]+" Banner Ad Report. Please do not hesitate to contact me if you have any questions.</p>"
            //             +"<p>Best regards,</p><p><i>{{ Auth::user()->name }}</i></p>"
            //             +"<p><b>Office Manager</b></p>"
            //             +"<p><b>Ph: <i>+1 (954) 848-9955</i></b></p>"
            //             +"<p><b><a href='mailto:{{ Auth::user()->email }}' style='color: #0077cc;'>{{ Auth::user()->email }}</a></b></p>"
            //             +"<p><b><a target='_blank' href='https://maritime-executive.com/' style='color: #0000ff;'>https://maritime-executive.com/</a></b></p>"
            //             +"<img src='{{ asset('media/images/site/logo/marex_logo.png') }}' alt='logo' style='max-width:180px;'>";
            // CKEDITOR.instances.email_body.setData(text);

            $('#start_date').datetimepicker({
                                          'format'   : 'yyyy-mm-dd',
                                          'minView'  : 2,
                                          'autoclose': true
                                      });
            $('#end_date').datetimepicker({
                                            'format'   : 'yyyy-mm-dd',
                                            'minView'  : 2,
                                            'autoclose': true
                                        });
            // $('#start_date').change(function(e){
            //     var startdate = $('#start_date').val();
            //     var enddate = $('#end_date').val();
            //     var startYear = startdate.split("-")[0];
            //     var endYear = enddate.split("-")[0];
            //     var startMonth = monthNames[parseInt(startdate.split("-")[1])-1];
            //     var endMonth = monthNames[parseInt(enddate.split("-")[1])-1];
            //     var textpart = '';
            //     if (startYear == endYear) {
            //         textpart = startYear;
            //         if (startMonth == endMonth) {
            //             textpart += ' ' + startMonth;
            //         } else {
            //             textpart += ' ' + startMonth + '-' + endMonth;
            //         }
            //     } else {
            //         textpart += startYear +' ' + startMonth + '-' +endYear + ' ' + endMonth;
            //     }
            //     var text = "<p>Hello,</p><p>Attached is the "+textpart+" Banner Ad Report. Please do not hesitate to contact me if you have any questions.</p>"
            //                 +"<p>Best regards,</p><p><i>{{ Auth::user()->name }}</i></p>"
            //                 +"<p><b>Office Manager</b></p>"
            //                 +"<p><b>Ph: <i>+1 (954) 848-9955</i></b></p>"
            //                 +"<p><b><a href='mailto:{{ Auth::user()->email }}' style='color: #0077cc;'>{{ Auth::user()->email }}</a></b></p>"
            //                 +"<p><b><a target='_blank' href='https://maritime-executive.com/' style='color: #0000ff;'>https://maritime-executive.com/</a></b></p>"
            //                 +"<img src='{{ asset('media/images/site/logo/marex_logo.png') }}' alt='logo' style='max-width:180px;'>";
            //     CKEDITOR.instances.email_body.setData(text);
            // });
            // $('#end_date').change(function(e){
            //     var startdate = $('#start_date').val();
            //     var enddate = $('#end_date').val();
            //     var startYear = startdate.split("-")[0];
            //     var endYear = enddate.split("-")[0];
            //     var startMonth = monthNames[parseInt(startdate.split("-")[1])-1];
            //     var endMonth = monthNames[parseInt(enddate.split("-")[1])-1];
            //     var textpart = '';
            //     if (startYear == endYear) {
            //         textpart = startYear;
            //         if (startMonth == endMonth) {
            //             textpart += ' ' + startMonth;
            //         } else {
            //             textpart += ' ' + startMonth + '-' + endMonth;
            //         }
            //     } else {
            //         textpart += startYear +' ' + startMonth + '-' +endYear + ' ' + endMonth;
            //     }
            //     var text = "<p>Hello,</p><p>Attached is the "+textpart+" Banner Ad Report. Please do not hesitate to contact me if you have any questions.</p>"
            //                 +"<p>Best regards,</p><p><i>{{ Auth::user()->name }}</i></p>"
            //                 +"<p><b>Office Manager</b></p>"
            //                 +"<p><b>Ph: <i>+1 (954) 848-9955</i></b></p>"
            //                 +"<p><b><a href='mailto:{{ Auth::user()->email }}' style='color: #0077cc;'>{{ Auth::user()->email }}</a></b></p>"
            //                 +"<p><b><a target='_blank' href='https://maritime-executive.com/' style='color: #0000ff;'>https://maritime-executive.com/</a></b></p>"
            //                 +"<img src='{{ asset('media/images/site/logo/marex_logo.png') }}' alt='logo' style='max-width:180px;'>";
            //     CKEDITOR.instances.email_body.setData(text);
            // });

            $('#create_reports').click(function () {

                var start_date = $('#start_date').val();
                var end_date   = $('#end_date').val();
                var company   = $('#company').val();

                $(this).prop('disabled',true);
                $('.spinner').fadeIn();

                $.post('/banner/reports/generate', {start_date: start_date, end_date: end_date, company: company},function(data){
                    var container = $('.reports-container'),
                        // reports = '<input type="checkbox" id="selectall" onchange="selectall(this.checked)"> <label for="selectall">Select all</label>';
                        reports = '';
                    $('.spinner').fadeOut();
                    $('#create_reports').prop('disabled',false);
                    if (data.length == 0) {
                        $('.alert-danger .message').html('Reports with such parameters were not found. Change the parameters and try again.');
                        $('.alert-danger').fadeIn();
                        setTimeout(function(){
                            $('.alert-danger').fadeOut();
                        },5000)
                    } else {
                        $('.alert-success .message').html('Reports was created successfully!');
                        $('.alert-success').fadeIn();
                        setTimeout(function(){
                            $('.alert-success').fadeOut();
                        },5000)
                        data.forEach(function(entry) {
                            var report = '<div class="report-item"><a href="/banner/download/'+entry+'.xls" target="_blank">'+entry+'.xls</a></div>';
                            reports += report;
                            container.html(reports);
                        });
                    }
                })
            });

            $('#send_reports').click(function () {

                var reportfiles = $('#reportfiles').val();
                var email   = $('#email').val();
                var email_title   = $('#email_title').val();
                var email_body   = CKEDITOR.instances.email_body.getData();
                if (reportfiles != "") {
                    $('html, body').animate({
                        scrollTop: $("#alerts").offset().top
                    }, 200);
                    $('#send_reports').prop('disabled',true);
                    $('.spinner').fadeIn();
                    $.post('/banner/reports/send', {reportfiles: reportfiles, email:email,email_title:email_title,email_body:email_body},function(data){
                        if (data == 1) {
                            $('.spinner').fadeOut();
                            $('#send_reports').prop('disabled',false);
                            $('.alert-success .message').html('Email has been sent!');
                            $('.alert-success').fadeIn();
                            setTimeout(function(){
                                $('.alert-success').fadeOut();
                            },5000)
                        }
                    })
                } else {
                    $('html, body').animate({
                        scrollTop: $("#alerts").offset().top
                    }, 100);
                    $('#send_reports').prop('disabled',false);
                    $('.alert-danger .message').html('There is no report selected!');
                    $('.alert-danger').fadeIn();
                    setTimeout(function(){
                        $('.alert-danger').fadeOut();
                    },5000)
                }
            });
        });
        function selectall(isChecked) {
            var container = $('.reports-container');
            var reportfiles = $('#reportfiles');
            var reports = '';

            if (isChecked) {
                container.find('.report-check').each(function(){
                    this.checked = true;
                });
            } else {
                container.find('.report-check').each(function(){
                    this.checked = false;
                })
            }

            for (var i = 0; i < container.find('.report-check:checked').length; i++) {
                if (i == 0) {
                    reports += container.find('.report-check:checked')[i].value;
                } else {
                    reports += ','+container.find('.report-check:checked')[i].value;
                }
            }

            reportfiles.val(reports);
        }

        function selectitem() {
            var container = $('.reports-container');
            var reportfiles = $('#reportfiles');
            var reports = '';

            for (var i = 0; i < container.find('.report-check:checked').length; i++) {
                if (i == 0) {
                    reports += container.find('.report-check:checked')[i].value;
                } else {
                    reports += ','+container.find('.report-check:checked')[i].value;
                }
            }

            reportfiles.val(reports);
        }

    </script>
@endpush
