<x-app-layout>
    {{-- <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot> --}}

    <style>
        input::placeholder {
            line-height: 40px !important;
        }
    </style>


    <div class="py-4">
        <div class="container-fluid">
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div class="app-content content">
                <div class="details-wrapper">
                    <div class="content-detached content-right">
                    <div class="content-body">
                        <section id="configuration">
                            <div class="row">
                            <div class="col-12">
                            <nav aria-label="breadcrumb ">
                          <ol class="breadcrumb bg-white">
                            <li class="breadcrumb-item"><a href="{{ url('/datarepositories/list/Published') }}">Data Repositories</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Create</li>
                          </ol>
                        </nav>
                        </div></div>
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                <form method="POST" action="{{ route('datarepositories.store') }}" id="createdatarepositories" class="edit-form" enctype="multipart/form-data">
                                    @csrf
                                        <div class="card-header">
                                            <h4 class="card-title">Create Data Repository </h4>
                                            <div class="cntrolBtn">
                                            <button class="btn btn-outline-primary createdatarepobutton" type="button"  onclick="createDatarepository('-1');">Save as Draft</button>
                                            <button class="btn btn-primary createdatarepobutton" type="button" onclick="createDatarepository('1');">Publish</button>
                                            <a class="btn btn-outline-primary createdatarepobutton" href = "{{url('datarepositories/list/Published')}}">Cancel</a>
                                        </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="form-content">
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div class="row">
                                                            <div class="col-md-4 col-12">
                                                                <label class="control-label">Title<span class="text-danger">*</span></label>
                                                                <input type="text" name="title" class="form-control" placeholder="" value="" required autofocus>
                                                            </div>

                                                            <div class="col-md-4 col-12">
                                                                <label class="control-label">Category<span class="text-danger">*</span></label>
                                                                <select id="categoryList" class="form-control" name="category_id" required onchange="triggerSubcategory();">
                                                                <option value="">--Select--</option>
                                                                @if(!empty($category) && isset($category))
                                                                @foreach($category as $categories)
                                                                <option value="{{$categories->id}}">{{$categories->categoryname}}</option>
                                                                @endforeach
                                                                @endif
                                                                </select>
                                                            </div>

                                                            <div class="col-md-4 col-12">
                                                                <label class="control-label">Sub Category</label>
                                                                <select id="subcategoryList" class="form-control" name="sub_category_id">
                                                                <option value="">--Select--</option>
                                                                </select>
                                                            </div>

                                                            <div class="col-md-12 col-12">
                                                                <label class="control-label">Doc Name<span class="text-danger"> *</span></label>
                                                                <input type="text" name="doc_name" class="form-control" placeholder="" value="" required autofocus>
                                                            </div>
                                                            <div class="col-12">
                                                            <div class="form-group" id="txtArea" style="display:none;">
                                                             <label class="control-label">Description<span class="text-danger">*</span></label>
                                                              <textarea style="height:auto;" name="description" id="description" class="form-control autoExpand"></textarea>
                                                            </div>
                                                              <input  class="ml10" type="hidden" name="hascontent" id="hascontent" value="" />
                                                          <input class="ml10" type="hidden" name="editorcount" id="editorcount" value="1" />
                                                              <p id="pretxt" class="alert alert-warning tc">Loading Content Editor ...</p>
                                                          </div>
                                                            <div class="col-md-6 col-12">
                                                                <label class="control-label">Display Date</label>
                                                                <input type="text" name="publish_date" class="form-control datepck_startdate" placeholder="dd/mm/yyyy" value="">
                                                            </div>
                                                            <div class="col-md-6 col-12">
                                                                <label class="control-label">Uploaded By</label>
                                                                <input type="text" name="uploaded_by" class="form-control" placeholder="" value="">
                                                            </div>

                                                            <div class="col-md-4 col-sm-4 col-12">
                                                                <label class="control-label">Add a Document<span class="text-danger">*</span></label>
                                                                <div class="remove-img remove-doc justify-content-end doc-upload">
                                                                    <div class="doc-controls">
                                                                         
                                                                        <div class="docControls">
                                                                            
                                                                            <div class="remove-icon" onclick="removeDoc()" id="docdiv" style="display: none">
                                                                                <i class="fas fa-times icon-img"></i>
                                                                            </div> 
                                                                        </div>
                                                                    </div>

                                                                    <div class="position-relative uploadImg" id="upload-icon">
                                                                        <input type="file" name="upload_doc" id="upload_doc">   
                                                                        <span><i class='fas fa-upload'></i></span>
                                                                    </div>
                                                                    
                                                                    <div class="upload-doc-name" id="file-upload-filename"></div>
                                                                </div>
                                                            </div>

                                                        <div class="col-12 mt-3">
                                                                <div class="company-header">
                                                                    <h6 class="card-title">Document Access</h6>
                                                                </div>
                                                            </div>           
                                                        <div class="col-md-4 col-12">
                                                                <label class="control-label">Doc Priority<span class="text-danger">*</span></label>
                                                                <select class="form-control" name="doc_priority" id="doc_priority" onchange="companiesListing();">
                                                                <option value="">--Select--</option>
                                                                <option value="1">Public</option>
                                                                <option value="2">Confidential</option>
                                                                <option value="3">Highly Confidential</option>
                                                                @if(ENVIRONMENT == 'Development')
                                                                <option value="4">Selected Access</option>
                                                                @endif
                                                                </select>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-8 col-12 companiestable mt-3" style="display: none;">
                                                                <label class="control-label">Users List</label>
                                                                <table class="table table-bordered" style="width:100%">
                                                                    <tr>
                                                                        <th class="checkclass"><input type="checkbox"  name="selectall" id="selectall" onclick="selectAll(this);">&nbsp;&nbsp;Select All</th>
                                                                        <th>Name</th>
                                                                        <th>Company Name</th>
                                                                        <th>File Access Level</th>
                                                                    </tr>
                                                                    <?php $fileAccess = array('L'=>'Low','M'=>'Medium','H'=>'High');?>
                                                                    @if(!empty($companies))
                                                                    @foreach($companies as $company)
                                                                    <tr class ="commonclass @if($company->access_level == 'L') lowclass @elseif($company->access_level == 'M') mediumclass @elseif($company->access_level == 'H') highclass @endif">
                                                                        <td class="checkclass"><input type="checkbox"  name="companycheck[]" value="{{$company->id}}"class="companychk" onclick="selectCompanyUser(this);"></td>
                                                                        <td>{{$company->firstname}} {{$company->lastname}}</td>
                                                                        <td>{{$company->companyname}}</td>
                                                                        <td>@if(isset($fileAccess[$company->access_level])) {{$fileAccess[$company->access_level]}} @endif</td>
                                                                    </tr>
                                                                    @endforeach
                                                                    @endif
                                                                </table>
                                                            </div>
                                                            <div class="DataNote mx-3 p-2">
                                                                <p>Note: You can add data repository information and click on Publish. All published data repositories will be available for the website front end user. Documents tagged to the data repository will be accessible based on the File Access Permissions.</p>
                                                                <ul>
                                                                    <li>Public - accessible for all </li>
                                                                    <li>Confidential - accessible for users with medium and high access level </li>
                                                                    <li>Highly Confidential - accessible for users with high access level</li>
                                                                    <li>Selected Access - accessible only for selected users</li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <input type="hidden" name="companyvalid" id="companyvalid" value='1'>
                                                    <input type="hidden" name="newsstatus" id="newsstatus" >
                                                </div>
                                            </div>
                                        </div>
                                        <!-- <div class="card-content collapse show">
                                            <div class="card-body card-dashboard">
                                                <div class="tab-content form-content" id="edit-tabcontent">

                                                    <div class="tab-pane fade" id="overview" role="tabpanel" aria-labelledby="overview-tab">
                                                    </div>		
                                                    
                                                    <div class="tab-pane fade active show" id="club-details" role="tabpanel" aria-labelledby="club-details-tab">
                                                        <div class="flex-rowblock">
                                                            <div class="left-flexbox">
                                                                
                                                            </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div> -->
                                    </form>
                                </div>
                            </div>
                        </div>
                    </section>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=f4xmcmxdltpuabqrju9bvz7gtauleb4ebiua6d1n6farq25z"></script> 
    <script type="text/javascript">
        
      tinymce.init({
          selector: 'textarea',
          menubar: false,
          height: 500,
          paste_as_text: true,
          relative_urls: false,
          convert_urls: false,
         remove_script_host : false,
         plugins: 'searchreplace autolink directionality visualblocks visualchars fullscreen image link media charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern, paste',
         toolbar1: 'formatselect | italic underline forecolor backcolor | media | link | image | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent',
          image_advtab: true,
          setup: function (ed) {
            ed.on('init', function(args) {
                $('#pretxt').hide();
                $('#txtArea').show();
            });
            ed.on('change', function(e) {
               calculateEditorCountPrimary();
           });
           ed.on('keyup', function(e) {
               calculateEditorCountPrimary();
                //$("#channelcontent").val(ed.getContent());
           });
          }
     });
        $(document).ready(function () {
            $('#createdatarepositories').validate({
            ignore: [],
            rules : {
                title : 'required',
                category_id: 'required',
               
                doc_name  : 'required',
                doc_priority  : 'required',
                sub_category_id : {
                  subCatgoryvalidate : true
                },
                companyvalid : 'required',
                hascontent : 'required',
                editorcount : 'required',
                upload_doc : 'required',
            },
            messages : {
                title :'Please enter title.',
                category_id: 'Please select category.', 
                sub_category_id: 'Please select sub category.', 
                doc_name: 'Please enter doc name.',
                doc_priority: 'Please select doc priority.',
                companyvalid: 'Please select atleast one company.',
                hascontent : 'Please enter description',
                editorcount : 'Maximum word limit for the content is 12,000.',
                upload_doc : 'Please upload a document',
            }
            });
            jQuery.validator.addMethod("subCatgoryvalidate", function(value, element, params) {
                var exists = false;
                //alert($('#subcategoryList option:not(:disabled)').length);
                if($('#subcategoryList option:not(:disabled)').length =='1'){
                    return true;
                  }else{
                    if( $( "#subcategoryList option:selected" ).val()!=''){
                        return true;
                    }else{
                        return false;
                    }
                    
                  }
              });
            $(".datepck_startdate").datepicker({
                    format: 'yyyy/mm/dd',
                    startDate: new Date() ,
                    defaultDate: new Date(),
                    autoclose: true,
                    changeMonth: true,
                    changeYear: true,
                    todayHighlight: true,
                    onClose  : function() {$(this).valid();}
            });
            $(document).on('change','#upload_doc',function(event){
                var filename = $('input[type=file]').val().split('\\').pop();
                var ext = $('#upload_doc').val().split('.').pop().toLowerCase();
                //var infoArea = document.getElementById( 'file-upload-filename' );
                if($.inArray(ext, ['doc','docx','pdf','ppt','pptx','xls','xlsx']) == -1) {
                    alert('Upload a document with size less than 25MB.');
                }else{
                    var _URL = window.URL || window.webkitURL;
                    var file, img;
                if ((file = this.files[0])) {
                    var fileExtension = ['doc', 'docx', 'pdf'];
                    var tmppath = URL.createObjectURL(event.target.files[0]);
                    $("#userdoc").attr("src",tmppath);
                    $("#file-upload-filename").show();
                    $("#file-upload-filename").html('');
                    document.getElementById('file-upload-filename').innerHTML =
                    document.getElementById('file-upload-filename').innerHTML
                    +
                    '<br /> ' + 'Uploaded file: <b>' + filename;
                    $("#docdiv").show();    
                    $("#upload-icon").hide();
                }
                }
            });
        });
        $("input[type='file']").on("change", function () {
            if(this.files[0].size > 25000000) {
                alert("Please upload file less than 25MB. Thanks!!");
                $(this).val('');
            }
        });
    function createDatarepository(status){
        $("#newsstatus").val(status);
        if( $("#createdatarepositories").valid()){
        var isValid = 1;
        if( isValid =='1' ) {
          $(".createdatarepobutton").prop("disabled", true);
          $("#createdatarepositories").submit();
        }
        }else{
            setTimeout(function(){
                $('html, body').animate({
                    scrollTop: ($('.error:visible').first().offset().top - 100)
            }, 500);
            //$('.error:visible').first().focus();
            },500);
         }
    }
    function companiesListing(){
        $('.companiestable').show();
        $('.checkclass').hide();
        $("#companyvalid").val('1')
         $("#companyvalid").valid();
         $('.commonclass').hide();
         if($('#doc_priority').val() == '1'){
            $('.lowclass').show();
            $('.mediumclass').show();
            $('.highclass').show();
         }
        else if($('#doc_priority').val() == '2'){
            $('.mediumclass').show();
            $('.highclass').show();
        }
        else if($('#doc_priority').val() == '3'){
            $('.highclass').show();
        }
        else if($('#doc_priority').val() == '4'){
            $('.lowclass').show();
            $('.mediumclass').show();
            $('.highclass').show();
            $('.checkclass').show();
            $("#companyvalid").val('');
             $(".companychk").prop("checked", false);
        }

    }
    function selectAll(ths){
        $("#companyvalid").val('');
        $(".companychk").prop("checked", false);
        if( $(ths).is(":checked") ){
        $(".companychk").prop("checked", true);
       $("#companyvalid").val('1');
        $("#companyvalid").valid();
    }
    }
    function selectCompanyUser(ths){
        var altlength = $(".companychk").length;
        var cnt = 0;
         $(".companychk").each(function (item) {
            if( $(this).is(":checked") ){
                 cnt++ ;
            }
        });
            $("#selectall").prop("checked",false);
        if( altlength == cnt ){
            $("#selectall").prop("checked",true);
        }


        if(cnt > 0){
            $("#companyvalid").val('1');
        }else{
            $("#companyvalid").val('');
        }
            $("#companyvalid").valid();
    }
    function removeDoc(){
        if (confirm('Are you sure you want to delete this document?')) {
            $("#userdoc").attr("src","{{url('images/upload-img.png')}}");
            $("#docdiv").hide();
            $("#upload-icon").show();
            $("#file-upload-filename").hide();
        }
    }
    function calculateEditorCountPrimary(){
            var editorwordcount = getStatsPrimary('description').words;
            editorwordcount = editorwordcount - 1;
            $("#editorcount").val('');
            $("#hascontent").val('');
            if( editorwordcount <= 12000 ){
                $("#editorcount").val(1);
            }
            if( editorwordcount > 0 ){
                $("#hascontent").val(1);
            }

            $("#editorcount").valid();
            $("#hascontent").valid();
        }
        function getStatsPrimary(id) {
            var body = tinymce.get(id).getBody(), text = tinymce.trim(body.innerText || body.textContent);

            return {
                chars: text.length,
                words: text.split(/[\w\u2019\'-]+/).length
            };
        }
        function triggerSubcategory(){
          $.ajax({
                  url: '{{ url("datarepository/triggersubcategory") }}',
                  type: "post",
                  cache: false,
                  data: { 'cat_id': $("#categoryList option:selected").val(),
                  "_token": "{{ csrf_token() }}"
                },
                success: function(data){
                if(data.success==1){
                  $("#subcategoryList").html(data.view);
                  // $(".selectpickernew").multiselect("destroy");
                  // $(".selectpickernew").multiselect("rebuild");
                }else if(data.error==1){
                  $(".errmsg").html(data.message);
                  $(".errmsg").show();
                  setTimeout(function(){ jQuery(".errmsg").hide(); }, 6000);
                }
                }
                });
          }
    </script>
</x-app-layout>