@extends('backend.layouts.app')
@section('content')
<div class="row page-titles">
   <div class="col-md-5 align-self-center">
      <h4 class="text-themecolor">Blog Manager</h4>
   </div>
   <div class="col-md-7 align-self-center text-right">
      <div class="d-flex justify-content-end align-items-center">
         <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
            <li class="breadcrumb-item"><a href="{{route('content')}}">Blog Manager</a></li>
            <li class="breadcrumb-item active">Edit Blog Manager</li>
         </ol>
      </div>
   </div>
</div>

<div id="deleteModal" class="modal fade" role='dialog'>
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-body">
            <p>Are you sure you want to delete this?</p>
         </div>
         <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <span id='deleteButton'></span>
         </div>
      </div>
   </div>
</div>

<div id="deleteModalCover" class="modal fade" role='dialog'>
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-body">
            <p>Are you sure you want to delete this?</p>
         </div>
         <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <span id='deleteButtonCover'></span>
         </div>
      </div>
   </div>
</div>

<!-- Content Wrapper. Contains page content -->
<!-- Main content -->
<section class="content">
   <div class="container-fluid">
      <div class="row">
         @if (session('status'))
         <div class="alert alert-success alert-dismissible fade show" role="alert"><i class="far fa-check-circle"></i>
            <strong></strong> {{ session('status') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
         </div>
         @endif
         <div class="col-md-12">
            <div class="card card-primary">
               <div class="tab-content">
                  <form action="{{ route('blog.update',['id'=>$blogs->id] + request()->query()) }}" id="contentForm" method="POST" enctype="multipart/form-data">
                     @csrf
                     <div class="card-body">
                        <div class="row">
                           <div class="col-sm-6">
                              <div class="form-group">
                                 <label for="title">Title<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                 <input type="text" name="title" value="{{ $blogs->title }}" class="form-control" id="title" placeholder="Enter Title">
                                 @error('title')
                                 <p style="color:red;">{{ $message }}</p>
                                 @enderror
                              </div>
                           </div>

                           <div class="col-sm-6">
                            <div class="form-group">
                               <label for="name">Post by name<span style="color: red;font-size:18px;"><b>*</b></span></label>
                               <input type="text" name="name" value="{{ $blogs->name }}" class="form-control" id="name" placeholder="Enter name">
                               @error('name')
                               <p style="color:red;">{{ $message }}</p>
                               @enderror
                            </div>
                         </div>

                         <div class="col-sm-6" style="margin-bottom: 2rem;">
                            <div class="form-group">
                               <label for="name">Cover letter</span></label>
                               <input type="file" name="cover_letter" value="{{ old('cover_letter') }}" class="form-control" id="cover_letter" placeholder="Enter cover letter" accept="image/*">
                               @error('cover_letter')
                               <p style="color:red;">{{ $message }}</p>
                               @enderror
                            </div>
                            @if(isset($blogs->cover_letter))
                            <div class="image-wrapper" style="display: inline-block; margin-right: 10px; position: relative;">
                                <img style="height: 50px;" src="{{ asset('images/blogs/coverletter/' . $blogs->cover_letter) }}" alt="Image">
                                <button
                                    type="button"
                                    class="btn btn-danger btn-sm"
                                    onclick="confirmDeleteCover('{{ $blogs->id }}')"
                                    style="position: absolute; top: 0; right: 0; background: transparent; border: none; color: red;">
                                    &times; <!-- HTML entity for '×' -->
                                </button>
                            </div>
                            @endif
                           

                         </div>

                         {{-- <div class="col-sm-6">
                            <div class="form-group">
                               <label for="name">Images</label>
                               <input type="file" name="images[]" value="{{ old('images') }}" class="form-control" multiple id="images" placeholder="Enter cover letter" accept="image/*">
                               @error('images')
                               <p style="color:red;">{{ $message }}</p>
                               @enderror
                            </div>
                            @if(isset($blogImages))
                            @foreach ($blogImages as $key => $image)
                            <div class="image-wrapper" style="display: inline-block; margin-right: 10px; position: relative;">
                                <img style="height: 50px;" src="{{ asset('images/blogs/images/' . $image) }}" alt="Image">

                                <!-- Cross/Remove Button -->
                                <button
                                    type="button"
                                    class="btn btn-danger btn-sm"
                                    onclick="confirmDeleteModal('{{ $key }}')"
                                    style="position: absolute; top: 0; right: 0; background: transparent; border: none; color: red;">
                                    &times; <!-- HTML entity for '×' -->
                                </button>



                                <!-- Form for deleting the image -->

                            </div>
                            @endforeach
                            @endif
                         </div> --}}


                           <div class="col-sm-6">
                              <div class="form-group">
                                 <label for="slug">Slug<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                 <input type="text" name="slug" value="{{ $blogs->slug }}" class="form-control" id="slug" placeholder="Enter Slug">
                                 @error('slug')
                                 <p style="color:red;">{{ $message }}</p>
                                 @enderror
                              </div>
                           </div>

                           <div class="col-sm-12">
                              <div class="form-group">
                                 <div class="custom-control custom-checkbox mr-sm-2 m-b-15">
                                    <input type="checkbox" class="custom-control-input" name="status" id="checkbox0" @if($blogs->status==1) checked @else @endif value="1">
                                    <label class="custom-control-label"  for="checkbox0">Is Active </label>
                                 </div>
                              </div>
                           </div>


                           <div class="col-sm-12">
                              <div class="tab-content" id="languageTabContent" style="margin-top:1%">
                                    <div class="" id="language-content" role="tabpanel" aria-labelledby="language-tab">
                                          <div class="row">
                                             <div class="col-sm-6">
                                                <div class="form-group">
                                                      <label for="meta_title">Meta Title</label>
                                                      <input type="text" name="meta_title" id="meta_title" class="form-control" placeholder="Enter Meta Title" value="{{ $blogs->meta_title   }}">
                                                </div>
                                             </div>
                                             <div class="col-sm-6">
                                                <div class="form-group">
                                                      <label for="meta_keyword">Meta Keyword</label>
                                                      <input type="text" name="meta_keyword" id="meta_keyword" class="form-control" placeholder="Enter Meta Keyword" value="{{ $blogs->meta_keyword }}">
                                                </div>
                                             </div>
                                             <div class="col-sm-12">
                                                <div class="form-group">
                                                      <label for="meta_description">Meta Description</label>
                                                      <textarea name="meta_description" id="meta_description" class="form-control" placeholder="Enter Meta Description">{{ $blogs->meta_description }}</textarea>
                                                </div>
                                             </div>
                                             <div class="col-sm-12">
                                                <div class="form-group">
                                                      <label for="description">Description<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                                      <textarea name="description" id="description" class="form-control" placeholder="Enter Description">{{ $blogs->description }}</textarea>
                                                </div>
                                             </div>
                                          </div>
                                    </div>
                              </div>


                           </div>
                         </div>
                     <div class="card-body">
                        <button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
                        <a href="{{ route('blog', request()->query()) }}" class="btn btn-secondary">Back</a>
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </div>
</section>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {



   $.validator.addMethod("maxFileSize", function(value, element, param) {
    if (element.files.length) {
        var fileSize = element.files[0].size;
        return this.optional(element) || (fileSize <= param);
    }
    return true; // No file selected
}, "The file must be less than {0} bytes.");

$.validator.addMethod("extension", function(value, element, param) {
    param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif";
    return this.optional(element) || value.match(new RegExp("\\.(" + param + ")$", "i"));
}, "Invalid file type.");



$.validator.addMethod("maxFileSizeMultiple", function(value, element, param) {
    var files = element.files;
    for (var i = 0; i < files.length; i++) {
        if (files[i].size > param) {
            return false; // Return false if any file exceeds the limit
        }
    }
    return true; // All files are within the limit
}, "Each file must be less than {0} bytes.");
    // Convert Blade variables to JavaScript variables
    const form = $('#contentForm');
    CKEDITOR.replace('description');

    // Initialize jQuery Validation
    form.validate({
      ignore: [] , 
        rules: {
            title: {
                required: true,
                minlength: 3,
                noOnlySpaces: true
            },
            name: {
                required: true,
                minlength: 3,
                noOnlySpaces: true
            },
            slug: {
                required: true,
                minlength: 3
            },
            meta_title: {
                maxlength: 70,
            },
            meta_keyword: {
                maxlength: 70,
            },
            meta_description: {
                minlength: 5
            },
            description: {
                required: function() 
                        {
                         CKEDITOR.instances.description.updateElement();
                        },
                minlength: 5,
                noOnlySpaces: true
            },
            cover_letter: { // New field added
               extension: "jpg|jpeg|png|gif",// Optional: maximum file size in KB
            maxFileSize: 2 * 1024 * 1024,
            },
            'images[]': {
               extension: "jpg|jpeg|png|gif",// 2 MB in bytes
                maxFileSizeMultiple: 2 * 1024 * 1024 ,
            },
        },
        messages: {
            title: {
                required: "The title field is required.",
                minlength: "The title must be at least 3 characters long."
            },
            slug: {
                required: "The slug field is required.",
                minlength: "The slug must be at least 3 characters long."
            },
            description: {
                required: "The description field is required.",
                minlength: "The description must be at least 5 characters long."
            },
            meta_title: {
                required: "The meta title field is required.",
                minlength: "The meta title must be at least 5 characters long."
            },
            meta_keyword: {
                required: "The meta keyword field is required.",
                minlength: "The meta keyword must be at least 5 characters long."
            },
            meta_description: {
                required: "The meta description field is required.",
                minlength: "The meta description must be at least 5 characters long."
            },
            cover_letter:{
               extension: "Only image files (JPG, JPEG, PNG, GIF) are allowed.",
               maxFileSize:"Cover letter should not be greater than 2MB.",
            },
            'images[]': {
               extension: "Only image files (JPG, JPEG, PNG, GIF) are allowed.",
                maxFileSizeMultiple: "Image size should not be greater than 2MB.",
            },
        },
        errorClass: "error",
        highlight: function(element) {
            $(element).addClass('is-invalid').removeClass('is-valid');
        },
        unhighlight: function(element) {
            $(element).removeClass('is-invalid');
            // .addClass('is-valid');
        },
        submitHandler: function(form) {
            // Ensure CKEditor data is included in the form submission
            for (var instance in CKEDITOR.instances) {
                CKEDITOR.instances[instance].updateElement();
            }
            form.submit();
        }
    });

    // Track if there were changes made (optional)
    let isInputChanged = false;
    form.find('input, textarea').on('input', function() {
        isInputChanged = true;
    });

    $('#submitButton').click(function() {
        if (!isInputChanged) {
            return;
        }
        if (form.valid()) {
            form.submit();
        }
    });
});


function confirmDeleteModal(id) {
        $('#deleteModal').modal();
        $('#deleteButton').html('<a class="btn btn-danger" style="color:white;" onclick="deleteData(' + id + ')">Delete</a>');
    }

    function confirmDeleteCover(id) {
        $('#deleteModalCover').modal();
        $('#deleteButtonCover').html('<a class="btn btn-danger" style="color:white;" onclick="deleteCover(' + id + ')">Delete</a>');
    }

    
    function deleteCover(id) {
            location.replace("{{ route('blog.delete.cover') }}?id=" + id  + "{{ request()->getQueryString() ? '&' . request()->getQueryString() : '' }}");
        }

    function deleteData(id) {
            location.replace("{{ route('blog.delete.image') }}?id=" + id  + "{{ request()->getQueryString() ? '&' . request()->getQueryString() : '' }}");
        }
</script>



@endsection
