<%- 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;
  }

  .text-danger {
    color: red;
    font-size: 0.9rem;
  }
</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: "Add Page Manager"}) %>

    <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
        { label: " Page Manager", href: "/admin/page"},
         { label: " Add 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" 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" id="editor" required></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" name="status" id="status" required>
              <option value="" disabled selected>Select a status</option>
              <option value="1">Active</option>
              <option value="0">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">
              Add Page
            </button>
          </div>

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

  <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
      };

      fetch('/admin/pages/create', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(pageData)
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            Swal.fire({
              icon: 'success',
              title: 'Page Created!',
              text: 'The page has been created successfully.',
            });
            window.location.href = '/admin/pages';
          } else {
            Swal.fire({
              icon: 'error',
              title: 'Error!',
              text: data.message || 'An error occurred while creating the page.',
            });
          }
        })
        .catch(error => {
          console.error('Error:', error);
          Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'An error occurred while creating 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>
</main>
<%- include('../../layouts/footer.ejs') %>