<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Submit a Post</title>
  <!-- Bootstrap CSS (CDN) -->
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
  />
  <style>
    body {
      background: #f0f2f5;
    }
    .post-card {
      margin-bottom: 1rem;
      border-radius: 8px;
      border: 1px solid #ddd;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      padding: 1rem;
      position: relative;
    }
    .post-card h5 {
      margin-bottom: 0.5rem;
    }
    .post-card small {
      color: #666;
    }
    .post-textarea {
      resize: vertical;
      min-height: 120px;
    }
    .archive-link {
      color: #007bff;
      cursor: pointer;
      text-decoration: underline;
    }
    .archive-container {
      position: absolute;
      bottom: 8px;
      right: 16px;
    }
    /* Toast container (position in top-right) */
    .toast-container {
      position: fixed;
      top: 1rem;
      right: 1rem;
      z-index: 9999;
    }
  </style>
</head>
<body>
  <div class="container my-5">
    <h1 class="mb-4 text-center">Share Your Thoughts</h1>

    <!-- CREATE POST SECTION -->
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card shadow-sm mb-5">
          <div class="card-body">
            <h4 class="card-title mb-3">Create a New Post</h4>
            
            <!-- Post Content -->
            <div class="mb-3">
              <label for="postContent" class="form-label">Your Post</label>
              <textarea
                class="form-control post-textarea"
                id="postContent"
                placeholder="Write something interesting..."
              ></textarea>
            </div>

            <!-- Security Key Input -->
            <div class="mb-3">
              <label for="teacherKeyInput" class="form-label">Security Key</label>
              <input
                type="text"
                class="form-control"
                id="teacherKeyInput"
                placeholder="Enter your security key here"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ALL POSTS SECTION -->
    <div class="row justify-content-center">
      <div class="col-md-8">
        <h2 class="mb-3">All Posts</h2>
        <div id="postsContainer">
          <!-- Dynamically populated via JS -->
        </div>
      </div>
    </div>
  </div>

  <!-- ARCHIVE MODAL -->
  <div
    class="modal fade"
    id="archiveModal"
    tabindex="-1"
    aria-labelledby="archiveModalLabel"
    aria-hidden="true"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="archiveModalLabel">Archive Post</h1>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <p>Please enter your security key to archive this post:</p>
          <input
            type="text"
            class="form-control"
            id="archiveKeyInput"
            placeholder="Security Key"
          />
          <!-- We'll store the row index of the post to be archived here -->
          <input type="hidden" id="archiveRowIndex" />
        </div>
      </div>
    </div>
  </div>

  <!-- TOAST CONTAINER (for success/error messages) -->
  <div class="toast-container p-3">
    <!--
      data-bs-autohide="true" => automatically hide
      data-bs-delay="3000" => hide after 3 seconds
    -->
    <div
      id="liveToast"
      class="toast"
      role="alert"
      aria-live="assertive"
      aria-atomic="true"
      data-bs-autohide="true"
      data-bs-delay="3000"
    >
      <div class="toast-header">
        <!-- We'll dynamically set text and background with JS -->
        <strong id="toastTitle" class="me-auto">Title</strong>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="toast"
          aria-label="Close"
        ></button>
      </div>
      <div id="toastBody" class="toast-body"></div>
    </div>
  </div>

  <!-- Bootstrap JS (for modal & toast) -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  <script>
    // Adjust to your actual backend endpoints if needed
    const API_BASE_POSTS = 'https://service.tansinh.info/api/posts';
    const API_BASE_ZALO = 'https://service.tansinh.info/api/zalocredentials';

    // We'll store teacher_key -> teacher_name mapping here
    const teacherMap = new Map();
    // Local cache of posts, Map<rowIndex, postObject>
    const postsData = new Map();

    // A small flag to prevent repeated auto-submits
    let hasSubmitted = false;

    /**
     * On page load, fetch teacher keys first, then set up events, then load posts.
     */
    window.onload = async () => {
      await loadTeacherKeys();
      setupEventListeners();
      loadPosts();
    };

    /**
     * Fetch teacher keys from /view endpoint.
     */
    async function loadTeacherKeys() {
      try {
        const res = await fetch(`${API_BASE_ZALO}/view`);
        const data = await res.json();
        data.forEach(item => {
          const tKey = item.teacher_key?.trim();
          const tName = item.teacher_name?.trim();
          if (tKey && tName) {
            teacherMap.set(tKey, tName);
          }
        });
      } catch (err) {
        console.error('Error loading teacher credentials:', err);
      }
    }

    /**
     * Setup input listeners for post creation (auto-submission)
     * and for the archive modal (auto-archive).
     */
    function setupEventListeners() {
      const postContentEl = document.getElementById('postContent');
      const teacherKeyEl = document.getElementById('teacherKeyInput');

      // For auto-submission of posts
      postContentEl.addEventListener('input', checkAndAutoSubmitPost);
      teacherKeyEl.addEventListener('input', checkAndAutoSubmitPost);

      // For archiving:
      // When user types valid key in the modal, we auto-archive.
      const archiveKeyEl = document.getElementById('archiveKeyInput');
      archiveKeyEl.addEventListener('input', async function() {
        const enteredKey = archiveKeyEl.value.trim();
        const rowIndex = document.getElementById('archiveRowIndex').value;

        // If key is valid, auto-archive
        if (teacherMap.has(enteredKey)) {
          try {
            await finalizeArchive(rowIndex, enteredKey);

            // Close modal
            const modalEl = document.getElementById('archiveModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            if (modalInstance) modalInstance.hide();
          } catch (err) {
            console.error('Error archiving post:', err);
            showToast('error', 'Error', 'Error archiving post. Check console.');
          }
        }
      });
    }

    /**
     * Check if we can auto-submit the post:
     * - post content must not be empty
     * - teacher key must be valid
     * - hasSubmitted must be false (prevent double submit)
     *
     * If conditions met, call submitPost().
     */
    function checkAndAutoSubmitPost() {
      const content = document.getElementById('postContent').value.trim();
      const key = document.getElementById('teacherKeyInput').value.trim();

      if (!hasSubmitted && content && teacherMap.has(key)) {
        hasSubmitted = true;
        submitPost(content, key);
      } 
      // If fields become invalid again, reset the hasSubmitted flag 
      // so user can type a new post next time without refreshing.
      else if (!content || !teacherMap.has(key)) {
        hasSubmitted = false;
      }
    }

    /**
     * Actually submit the post to the server, then show a toast on success.
     */
    async function submitPost(content, key) {
      // If somehow content or key are missing, return.
      if (!content || !teacherMap.has(key)) return;

      const now = new Date();

      // Build body data
      const bodyData = {
        postid: Date.now().toString(),
        postcontent: content,
        author: teacherMap.get(key) || "web_user",
        timestamp: now.toISOString(),
        archived_status: "",
        blank1: "",
        blank2: "",
        blank3: "",
        blank4: "",
        blank5: "",
        blank6: "",
        blank7: "",
        blank8: "",
        blank9: "",
        blank10: "",
        blank11: ""
      };

      try {
        const response = await fetch(`${API_BASE_POSTS}/add`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(bodyData)
        });
        if (!response.ok) {
          throw new Error(`Server error: ${response.status}`);
        }

        // Clear form fields
        document.getElementById('postContent').value = '';
        document.getElementById('teacherKeyInput').value = '';
        hasSubmitted = false; // reset so user can post again

        // Show success toast, then reload posts
        showToast('success', 'Success', 'Post submitted successfully!');
        loadPosts();
      } catch (err) {
        console.error('Error submitting post:', err);
        showToast('error', 'Error', 'Error submitting post. Check console.');
      }
    }

    /**
     * Load existing posts from /view, store them, then render (excluding archived).
     */
    async function loadPosts() {
      const container = document.getElementById('postsContainer');
      container.innerHTML = `<p class="text-muted">Loading posts...</p>`;
      try {
        const res = await fetch(`${API_BASE_POSTS}/view`);
        const data = await res.json();
        data.reverse(); // newest at top

        postsData.clear();
        data.forEach((post) => {
          // post.id is the zero-based row index
          postsData.set(post.id, post);
        });

        renderPosts(data);
      } catch (err) {
        console.error('Error loading posts:', err);
        container.innerHTML = `<p class="text-danger">Error loading posts.</p>`;
      }
    }

    /**
     * Render the posts in #postsContainer, excluding archived.
     */
    function renderPosts(posts) {
      const container = document.getElementById('postsContainer');
      container.innerHTML = '';

      // Filter out archived posts
      const visiblePosts = posts.filter(
        (p) => !p.archived_status || p.archived_status.trim() === ''
      );

      if (!Array.isArray(visiblePosts) || visiblePosts.length === 0) {
        container.innerHTML = `<p class="text-muted">No posts found.</p>`;
        return;
      }

      visiblePosts.forEach((post) => {
        const postDiv = document.createElement('div');
        postDiv.className = 'post-card';
        postDiv.innerHTML = `
          <h5>Post ID: ${post.postid || '(none)'}</h5>
          <small class="d-block mb-2 text-secondary">
            Author: ${post.author || 'Anonymous'} |
            ${
              post.timestamp
                ? new Date(post.timestamp).toLocaleString()
                : ''
            }
          </small>
          <p>${post.postcontent || ''}</p>
          <div class="archive-container">
            <span class="archive-link" onclick="archivePost(${post.id})">
              Archive
            </span>
          </div>
        `;
        container.appendChild(postDiv);
      });
    }

    /**
     * Called when the user clicks "Archive". This opens a modal so the user can enter a security key.
     */
    function archivePost(rowIndex) {
      // Store the rowIndex in a hidden field
      document.getElementById('archiveRowIndex').value = rowIndex;
      // Clear the key input
      document.getElementById('archiveKeyInput').value = '';

      // Show the archive modal
      const modalElement = document.getElementById('archiveModal');
      const modal = new bootstrap.Modal(modalElement);
      modal.show();
    }

    /**
     * Final archiving logic (once we have a valid key).
     * We set archived_status, send PUT /edit, and show a toast on success.
     */
    async function finalizeArchive(rowIndex, key) {
      const teacherName = teacherMap.get(key);
      if (!teacherName) {
        throw new Error('Invalid security key');
      }

      const now = new Date();
      const hh = String(now.getHours()).padStart(2, '0');
      const mm = String(now.getMinutes()).padStart(2, '0');
      const ss = String(now.getSeconds()).padStart(2, '0');
      const dd = String(now.getDate()).padStart(2, '0');
      const mo = String(now.getMonth() + 1).padStart(2, '0');
      const yyyy = now.getFullYear();
      const timeStampStr = `${hh}:${mm}:${ss} ${dd}${mo}${yyyy}`;

      const archiveMessage = `Archived by ${teacherName} at ${timeStampStr}`;

      // Get the original post from our map
      const post = postsData.get(+rowIndex);
      if (!post) {
        throw new Error(`Cannot find post with rowIndex=${rowIndex}`);
      }

      // Prepare updated object for PUT /edit
      const updatedPost = {
        id: +rowIndex,
        postid: post.postid,
        postcontent: post.postcontent,
        author: post.author,
        timestamp: post.timestamp,
        archived_status: archiveMessage,
        blank1: post.blank1 || "",
        blank2: post.blank2 || "",
        blank3: post.blank3 || "",
        blank4: post.blank4 || "",
        blank5: post.blank5 || "",
        blank6: post.blank6 || "",
        blank7: post.blank7 || "",
        blank8: post.blank8 || "",
        blank9: post.blank9 || "",
        blank10: post.blank10 || "",
        blank11: post.blank11 || ""
      };

      const response = await fetch(`${API_BASE_POSTS}/edit`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedPost)
      });

      if (!response.ok) {
        throw new Error(`Server error: ${response.status}`);
      }

      // On success
      showToast('success', 'Archived', 'Post archived successfully!');
      loadPosts();
    }

    /**
     * Show a Bootstrap toast message in the top-right corner.
     * @param {string} type - 'success' or 'error'
     * @param {string} title - Toast title text
     * @param {string} message - Toast body text
     */
    function showToast(type, title, message) {
      const toastEl = document.getElementById('liveToast');
      const toastTitle = document.getElementById('toastTitle');
      const toastBody = document.getElementById('toastBody');

      // Reset classes for background colors
      toastEl.classList.remove('text-bg-success', 'text-bg-danger');

      // Apply a nicer background color depending on type
      if (type === 'success') {
        toastEl.classList.add('text-bg-success');
      } else if (type === 'error') {
        toastEl.classList.add('text-bg-danger');
      }

      toastTitle.innerText = title;
      toastBody.innerText = message;

      // Create/show the toast
      const bsToast = new bootstrap.Toast(toastEl);
      bsToast.show();
    }
  </script>
</body>
</html>
