<?php 
    include('menu_admin.php');
    include_once 'model/posts_model.php';

    // Instantiate posts model and fetch all posts
    $posts_model = new posts_model();
    $posts = $posts_model->get_all_posts();
?>

<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Admin Panel - Posts</title>
      <link rel="apple-touch-icon" sizes="76x76" href="images/logo.png">
      <link rel="icon" type="image/png" href="images/logo.png">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
      <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
      <link rel="stylesheet" href="dist/css/adminlte.min.css">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
      <style>
        /* Existing styles for the layout */
        .top-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .top-section h1 { font-size: 1.5rem; font-weight: bold; margin: 0; }
        .search-input { width: 100%; padding: 10px; margin-right: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 1rem; }
        .new-post-btn-container { display: flex; justify-content: flex-end; }
        .new-post-btn { padding: 10px 20px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
        .new-post-btn i { margin-right: 8px; }
        .new-post-btn:hover { background-color: #218838; }
        .post-card { border: 1px solid #ddd; border-radius: 8px; padding: 20px; background-color: #fff; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; justify-content: space-between; min-height: 250px; }
        .post-title { font-size: 1.1rem; font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .post-info { font-size: 0.9rem; color: #666; margin-top: 10px; }
        .post-actions { margin-top: 15px; display: flex; justify-content: space-between; }
        .btn-custom { padding: 5px 10px; margin-right: 8px; }
        .post-grid { 
          display: grid; 
          grid-template-columns: repeat(auto-fill, 
          minmax(320px, 1fr)); gap: 20px; 
        }
        .post-image { width: 100%; height: 150px; object-fit: cover; border-radius: 8px; }
        .btn-custom {
          display: flex;
          align-items: center;    /* Vertically center the icon and text */
          justify-content: center; /* Horizontally center the icon and text */
          padding: 5px 10px;
          margin-right: 8px;
        }

        .search-input {
            width: 100%;                    /* Make the input fill the container */
            max-width: 900px;               /* Optional: limit the width to 500px for larger screens */
            padding: 12px 20px;             /* Increase padding for larger input area */
            font-size: 1.1rem;              /* Increase font size for better readability */
            border: 2px solid #ccc;         /* Add a border with lighter color */
            border-radius: 50px;            /* Rounded corners */
            transition: all 0.3s ease;      /* Smooth transition for focus effect */
        }

        .search-input:focus {
            border-color: #28a745;          /* Green border on focus */
            outline: none;                  /* Remove the default focus outline */
            box-shadow: 0 0 8px rgba(40, 167, 69, 0.2); /* Soft green shadow */
        }

        .search-input::placeholder {
            color: #aaa;                    /* Light color for placeholder text */
            font-style: italic;              /* Make the placeholder text italic */
        }


        .btn-custom i {
            margin-right: 5px; /* Space between the icon and the text */
        }

      </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <!-- Top Section: Search Filter & New Post Button -->
                        <div class="top-section">
                            <h1>Manage Posts</h1>
                            <!-- Search Filter Box -->
                            <div class="search-filter">
                                <input type="text" id="search-input" class="search-input" placeholder="Search posts..." oninput="filterPosts()" />
                            </div>
                            <!-- New Post Button -->
                            <div class="new-post-btn-container">
                                <!-- Button to trigger modal -->
                                <button type="button" class="new-post-btn" data-toggle="modal" data-target="#addPostModal">
                                    <i class="fas fa-plus"></i> New Post
                                </button>
                            </div>

                        </div>

                        <!-- Posts Display (Styled with Cards) -->
                        <div class="post-grid" id="post-grid">
                            <?php
                                if ($posts) {
                                    foreach ($posts as $post) {
                                        // Fetch number of comments for this post
                                        $comment_count = $posts_model->get_comment_count_by_post($post['ID']);
                                        
                                        // Format the post's date
                                        $date_posted = date("F j, Y", strtotime($post['post_date']));
                                        
                                        // Determine commenting status (assuming 1 = open, 0 = closed)
                                        $comment_status = ($post['comment_status'] == 'open') ? 'Enabled' : 'Disabled';
                                        $status_class = ($post['comment_status'] == 'open') ? 'text-success' : 'text-danger';
                                        
                                        // Determine the button text for enabling/disabling comments
                                        $toggle_button_text = ($post['comment_status'] == 'open') ? 'Disable Comments' : 'Enable Comments';
                                        $toggle_button_class = ($post['comment_status'] == 'open') ? 'btn btn-danger' : 'btn btn-success';

                                        // Determine post status
                                        $post_status = ($post['post_status'] == 'publish') ? 'Published' : 'Draft';
                                        

                                        // Display post in a card
                                        echo "<div class='post-card' data-title='{$post['post_title']}'>";

                                        // Add image to the card
                                        if (!empty($post['image'])) {
                                            echo "<img src='../uploads/{$post['image']}' alt='Post Image' class='post-image'>";
                                        }

                                        echo "<div class='post-title'>{$post['post_title']}</div>";
                                        echo "<div class='post-info'>";
                                        echo "<strong>Posted on:</strong> {$date_posted} <br>";
                                        echo "<strong>Comments:</strong> {$comment_count} <br>";
                                        echo "<strong>Post Status:</strong> {$post_status} <br>";
                                        echo "<span class='comment-status {$status_class}'><strong>Commenting State:</strong> {$comment_status}</span>";
                                        echo "</div>";
                                        echo "<div class='post-actions'>";
                                        
                                        echo "<a href='#' class='btn btn-info btn-sm btn-custom view-post' data-id='{$post['ID']}'><i class='fas fa-eye'></i> View</a>";
                                        
                                        echo "<a href='#' class='btn btn-warning btn-sm btn-custom edit-post' data-id='{$post['ID']}'><i class='fas fa-edit'></i> Edit</a>";

                                        echo "<a href='#' class='btn btn-danger btn-sm btn-custom delete-post' data-id='{$post['ID']}'><i class='fas fa-trash'></i> Delete</a>";

                                        echo "<a href='#' class='{$toggle_button_class} toggle-comment-status' data-id='{$post['ID']}' data-status='{$post['comment_status']}'>" . $toggle_button_text . "</a>";
                                        echo "</div>";
                                        echo "</div>";
                                    }
                                } else {
                                    echo "<div class='col-12 text-center'>No posts found.</div>";
                                }
                            ?>
                        </div> <!-- End of post grid -->
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- JS for Real-Time Filtering -->
    <script>
        function filterPosts() {
            const searchQuery = document.getElementById('search-input').value.toLowerCase();
            const posts = document.querySelectorAll('.post-card');

            posts.forEach(post => {
                const title = post.getAttribute('data-title').toLowerCase();
                if (title.includes(searchQuery)) {
                    post.style.display = 'block';
                } else {
                    post.style.display = 'none';
                }
            });
        }

        // Handle toggling of comment status
        document.querySelectorAll('.toggle-comment-status').forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const postId = this.getAttribute('data-id');
                const currentStatus = this.getAttribute('data-status');

                const action = currentStatus == 'open' ? 'Disable Comments' : 'Enable Comments';

                // SweetAlert confirmation
                Swal.fire({
                    title: `Are you sure you want to ${action.toLowerCase()}?`,
                    text: `This will ${action.toLowerCase()} for this post.`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, proceed!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Proceed to update the comment status
                        fetch(`toggle_comment_status.php?id=${postId}`)
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    // Update button text and status
                                    const button = document.querySelector(`.toggle-comment-status[data-id="${postId}"]`);
                                    const newStatus = data.new_status === 'open' ? 'Disable Comments' : 'Enable Comments';
                                    button.textContent = newStatus;
                                    button.setAttribute('data-status', data.new_status);
                                    Swal.fire('Success!', `Commenting is now ${newStatus.toLowerCase()}.`, 'success');
                                    location.reload();
                                } else {
                                    Swal.fire('Error!', 'Something went wrong. Please try again.', 'error');
                                }
                            });
                    }
                });
            });
        });

        // Attach click event to all 'View' buttons
document.querySelectorAll('.view-post').forEach(button => {
    button.addEventListener('click', function (e) {
        e.preventDefault();

        const postId = this.getAttribute('data-id');  // Get the post ID

        // Fetch the post details using AJAX
        fetch(`view_post_details.php?id=${postId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Populate modal with post details
                    document.getElementById('postTitle').textContent = data.post.title;
                    document.getElementById('postDate').textContent = `Posted on: ${data.post.date}`;
                    document.getElementById('postContent').innerHTML = data.post.content;

                    // Display post image
                    const postImage = document.getElementById('postImage');
                    if (data.post.image) {
                        postImage.src = `../uploads/${data.post.image}`;  // Assuming image is stored in the uploads folder
                    } else {
                        postImage.style.display = 'none';  // Hide the image container if there's no image
                    }

                    // Clear previous comments
                    const commentList = document.getElementById('commentList');
                    commentList.innerHTML = '';

                    // Add comments to the modal
                    if (data.post.comments.length > 0) {
                        data.post.comments.forEach(comment => {
                            const li = document.createElement('li');
                            li.textContent = `${comment.comment_author}: ${comment.comment_content}`;
                            commentList.appendChild(li);
                        });
                    } else {
                        const li = document.createElement('li');
                        li.textContent = 'No comments yet.';
                        commentList.appendChild(li);
                    }

                    // Show the modal
                    var myModal = new bootstrap.Modal(document.getElementById('postModal'));
                    myModal.show();
                } else {
                    Swal.fire('Error!', 'Failed to load post details.', 'error');
                }
            })
            .catch(error => console.error('Error fetching post details:', error));
    });
});

// Handle Delete Post with SweetAlert
document.querySelectorAll('.delete-post').forEach(button => {
    button.addEventListener('click', function(e) {
        e.preventDefault();  // Prevent default link behavior

        const postId = this.getAttribute('data-id');  // Get post ID

        // Show SweetAlert confirmation
        Swal.fire({
            title: 'Are you sure?',
            text: 'This post will be marked as deleted, and you will not be able to undo this action.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Delete',
            cancelButtonText: 'No, cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Proceed with marking the post as deleted using AJAX
                fetch(`mark_post_deleted.php?id=${postId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Notify the user of success and refresh the page
                            Swal.fire('Deleted!', 'The post has been marked as deleted.', 'success')
                                .then(() => {
                                    location.reload();  // Reload the page to reflect the changes
                                });
                        } else {
                            Swal.fire('Error!', 'Something went wrong. Please try again.', 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        Swal.fire('Error!', 'There was an error processing your request.', 'error');
                    });
            }
        });
    });
});




    </script>
    <!-- Post Details Modal -->
<div class="modal fade" id="postModal" tabindex="-1" aria-labelledby="postModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="postTitle"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div id="postImageContainer">
          <img id="postImage" src="" alt="Post Image" class="img-fluid" style="max-width: 100%; height: auto;">
        </div>
        <p id="postDate"></p>
        <div id="postContent"></div>
        <h5>Comments:</h5>
        <ul id="commentList">
          <!-- Comments will be dynamically added here -->
        </ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<!-- New Post Modal -->
<div class="modal fade" id="addPostModal" tabindex="-1" aria-labelledby="addPostModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addPostModalLabel">Add New Post</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="addPostForm" enctype="multipart/form-data" method="post" action="add_post_backend.php">
        <div class="modal-body">
          <!-- Post Title -->
          <div class="form-group">
            <label for="postTitle">Post Title</label>
            <input type="text" class="form-control" id="postTitle" name="postTitle" required>
          </div>

          <!-- Post Content -->
          <div class="form-group">
            <label for="postContent">Post Content</label>
            <textarea class="form-control" id="postContent" name="postContent" rows="5" required></textarea>
          </div>

          <!-- Post Category -->
          <div class="form-group">
            <label for="postCategory">Post Category</label>
            <select class="form-control" id="postCategory" name="postCategory" required>
              <option value="">Select Category</option>
              <?php
                // Fetch categories from the HRDC database
                $categories = $posts_model->get_categories(); 
                foreach ($categories as $category) {
                    echo "<option value='{$category['category_id']}'>{$category['category_name']}</option>";
                }
              ?>
            </select>
          </div>

          <!-- Post Status (Publish/Draft) -->
          <div class="form-group">
            <label for="postStatus">Post Status</label>
            <select class="form-control" id="postStatus" name="postStatus" required>
              <option value="publish">Publish</option>
              <option value="draft">Draft</option>
            </select>
          </div>

          <!-- Comment Status (Open/Closed) -->
          <div class="form-group">
            <label for="commentStatus">Comment Status</label>
            <select class="form-control" id="commentStatus" name="commentStatus" required>
              <option value="open">Open</option>
              <option value="closed">Closed</option>
            </select>
          </div>

          <!-- Post Image -->
          <div class="form-group">
            <label for="postImage">Post Image (Mandatory)</label>
            <input type="file" class="form-control" id="postImage" name="postImage" required>
            <small class="form-text text-muted">Please upload an image for the post.</small>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save Post</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Post Modal -->
<!-- Edit Post Modal -->
<div class="modal fade" id="editPostModal" tabindex="-1" aria-labelledby="editPostModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editPostModalLabel">Edit Post</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="editPostForm" enctype="multipart/form-data" method="post" action="edit_post_backend.php">
        <div class="modal-body">
          <!-- Post Title -->
          <div class="form-group">
            <label for="editPostTitle">Post Title</label>
            <input type="text" class="form-control" id="editPostTitle" name="editPostTitle" required>
          </div>

          <!-- Post Content -->
          <div class="form-group">
            <label for="editPostContent">Post Content</label>
            <textarea class="form-control" id="editPostContent" name="editPostContent" rows="5" required></textarea>
          </div>

          <!-- Post Category -->
          <div class="form-group">
            <label for="editPostCategory">Post Category</label>
            <select class="form-control" id="editPostCategory" name="editPostCategory" required>
              <option value="">Select Category</option>
              <?php
                // Fetch categories from the HRDC database
                $categories = $posts_model->get_categories(); 
                foreach ($categories as $category) {
                    echo "<option value='{$category['category_id']}'>{$category['category_name']}</option>";
                }
              ?>
            </select>
          </div>

          <!-- Post Status (Publish/Draft) -->
          <div class="form-group">
            <label for="editPostStatus">Post Status</label>
            <select class="form-control" id="editPostStatus" name="editPostStatus" required>
              <option value="publish">Publish</option>
              <option value="draft">Draft</option>
            </select>
          </div>

          <!-- Comment Status (Open/Closed) -->
          <div class="form-group">
            <label for="editCommentStatus">Comment Status</label>
            <select class="form-control" id="editCommentStatus" name="editCommentStatus" required>
              <option value="open">Open</option>
              <option value="closed">Closed</option>
            </select>
          </div>

          <!-- Post Image -->
          <div class="form-group">
            <label for="editPostImage">Post Image (Optional)</label>
            <input type="file" class="form-control" id="editPostImage" name="editPostImage">
            <small class="form-text text-muted">Please upload a new image if you want to change the current one.</small>

            <!-- Display Current Image -->
            <div id="currentImageContainer" class="mt-2">
              <!-- This will be dynamically populated -->
              <img id="currentImage" src="../uploads/" alt="Current Post Image" class="img-fluid" style="max-width: 100%; height: auto;">
            </div>
          </div>

          <!-- Hidden Post ID -->
          <input type="hidden" id="editPostId" name="editPostId">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>





    <!-- JS Libraries -->
    <script src="plugins/jquery/jquery.min.js"></script>
    <script src="plugins/jquery-ui/jquery-ui.min.js"></script>
    <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="dist/js/adminlte.js"></script>
    <script src="js/script.js"></script>
    <script>
    // Handle click on Edit Post button
document.querySelectorAll('.edit-post').forEach(button => {
    button.addEventListener('click', function (e) {
        e.preventDefault();

        const postId = this.getAttribute('data-id');  // Get the post ID

        // Fetch the post details using AJAX
        fetch(`get_post_details.php?id=${postId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Pre-fill the modal with the post details
                    document.getElementById('editPostTitle').value = data.post.post_title;
                    document.getElementById('editPostContent').value = data.post.post_content;
                    document.getElementById('editPostCategory').value = data.post.post_category;
                    document.getElementById('editPostStatus').value = data.post.post_status;
                    document.getElementById('editCommentStatus').value = data.post.comment_status;
                    document.getElementById('editPostId').value = data.post.ID;

                    // Show the current image (if available)
                    const currentImageContainer = document.getElementById('currentImageContainer');
                    const currentImage = document.getElementById('currentImage');

                    if (data.post.image) {
                        // Display the current image
                        currentImage.src = `../uploads/${data.post.image}`;
                        currentImageContainer.style.display = 'block'; // Ensure the container is visible
                    } else {
                        // Hide the current image container if no image is present
                        currentImageContainer.style.display = 'none';
                    }

                    // Show the modal
                    var myModal = new bootstrap.Modal(document.getElementById('editPostModal'));
                    myModal.show();
                } else {
                    Swal.fire('Error!', 'Failed to load post details.', 'error');
                }
            })
            .catch(error => console.error('Error fetching post details:', error));
    });
});
</script>
</body>
</html>
