<%- include('../../layouts/head.ejs') %>
<!-- TinyMCE 5 CDN (Free) -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@5.10.9/tinymce.min.js"></script>

<style>
  .tox-tinymce {
    min-height: 300px;
  }
</style>
<%- include('../../layouts/header.ejs') %>
<main class="dashboard-main">
  <%- include('../../layouts/navbar.ejs') %>

  <div class="container flex-1 pt-20 w-full my-4">
    <%- include('../../partials/utils/title.ejs', {title: "Edit Page Manager"}) %>

    <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
        { label: " Page Manager", href: "/admin/pages" },
         { label: " Edit Page Manager" }
      ];
    %>

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>



    <div class="  mt-4">
      <div class="  bg-white shadow-md rounded-lg" style="padding: 20px;">
        <form id="pageForm">
          <!-- Page Name -->
          <div class="mb-3">
            <label for="page_name" class="form-label">Page Name</label>
            <input type="text"  class="form-control" id="page_name" name="page_name" value="<%= city.page_name %>" placeholder="Enter page name" required />
          </div>

          <!-- Content Editor -->
          <div class="mb-3">
            <label for="editor" class="form-label">Content (HTML + CSS)</label>
            <textarea name="content" required id="editor"><%= city.content %></textarea>
            <div id="editorError" class="text-danger mt-1" style="display: none;">Content is required</div>
          </div>

          <!-- Status -->
          <div class="mb-4">
            <label for="status" class="form-label">Status</label>
            <select class="form-select" required name="status" id="status" required>
              <option value="1" <%= city.active == 1 ? "selected" : "" %>>Active</option>
              <option value="0" <%= city.active == 0 ? "selected" : "" %>>Inactive</option>
            </select>
          </div>

          <!-- Submit Button -->
          <div style="display: flex; justify-content: end; margin-top: 20px;">
            <button type="button" class="btn btn-primary" id="submitBtn">
              Update Page
            </button>
          </div>

        </form>
      </div>
    </div>
  </div>
</main>


<script>
  // Define form configuration
  const formConfig = {
    formId: "pageForm",
    fields: [{
        name: "page_name",
        type: "text",
        required: true,
        messages: {
          required: "Page name is required"
        }
      },

      {
        name: "status",
        type: "select",
        required: true,
        messages: {
          required: "Please select status"
        }
      }
    ]
  };
</script>

<script src="/js/validator/validation.js"></script>


<script>
  // Initialize TinyMCE
  tinymce.init({
    selector: '#editor',
    height: 400,
    plugins: [
      'advlist autolink lists link image charmap print preview anchor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste code help wordcount'
    ],
    toolbar: 'undo redo | formatselect | bold italic backcolor | \
              alignleft aligncenter alignright alignjustify | \
              bullist numlist outdent indent | removeformat | help',
    menubar: 'file edit view insert format tools table help',
    branding: false,
    // For image upload, you'll need to implement your own endpoint
    images_upload_handler: function (blobInfo, success, failure) {
      const xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open('POST', '/admin/pages/upload-image');
      
      xhr.onload = function() {
        if (xhr.status !== 200) {
          failure('HTTP Error: ' + xhr.status);
          return;
        }
        
        const json = JSON.parse(xhr.responseText);
        
        if (!json || typeof json.location != 'string') {
          failure('Invalid JSON: ' + xhr.responseText);
          return;
        }
        
        success(json.location);
      };
      
      xhr.onerror = function () {
        failure('Image upload failed');
      };
      
      const formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      
      xhr.send(formData);
    }
  });

  const formValidator = setupFormValidation(
    formConfig.formId,
    formConfig.fields
  );

  // Submit handler
  document.getElementById('submitBtn').addEventListener('click', function() {
    // Validate form fields
    const isValid = formValidator.validateForm();

    // Get TinyMCE content
    const editorContent = tinymce.get('editor').getContent().trim();
    const editorErrorEl = document.getElementById('editorError');

    // Validate TinyMCE
    if (!editorContent) {
      editorErrorEl.style.display = 'block';
    } else {
      editorErrorEl.style.display = 'none';
    }

    // If any validation fails, stop
    if (!isValid || !editorContent) {
      console.log('Form validation failed');
      return;
    }

    const pageData = {
      page_name: document.getElementById('page_name').value,
      content: editorContent, // TinyMCE content
      status: document.getElementById('status').value
    };

    let pageId = "<%= city.id %>"

    fetch(`/admin/edit-page/${pageId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(pageData)
      })
      .then(response => response.json())
      .then(data => {
        Swal.fire({
          icon: 'success',
          title: 'Page Updated!',
          text: 'The page has been updated successfully.',
        });
        window.location.href = '/admin/pages';

      })
      .catch(error => {
        Swal.fire({
          icon: 'error',
          title: 'Error!',
          text: 'An error occurred while updating the page.',
        });
      });
  });
</script>
<script>
  $(document).ready(function () {
    // Show loader on any AJAX request start
    $(document).ajaxStart(function () {
      $("#loader").show();
    });

    // Hide loader when all AJAX requests finish
    $(document).ajaxStop(function () {
      $("#loader").hide();
    });
  });
</script>
</div>
<%- include('../../layouts/footer.ejs') %>