<?php 
    include('menu_admin.php');
    include_once 'model/posts_model.php';  // Assuming a different model for press releases

    // Instantiate press releases model and fetch all press releases
    $posts_model = new posts_model();
    $press_releases = $posts_model->get_press_releases();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin Panel - Press Releases</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>
    /* Layout and Card Styles */
    .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: 12px 20px; font-size: 1.1rem; border: 2px solid #ccc; border-radius: 50px; transition: all 0.3s ease; }
    .search-input:focus { border-color: #28a745; outline: none; box-shadow: 0 0 8px rgba(40, 167, 69, 0.2); }
    .press-release-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; }
    .press-release-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; }
    .press-release-image { width: 100%; height: 150px; object-fit: cover; border-radius: 8px; }
    .press-release-title { font-size: 1.1rem; font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .press-release-info { font-size: 0.9rem; color: #666; margin-top: 10px; }
    .btn-custom { display: flex; align-items: center; justify-content: center; padding: 5px 10px; margin-right: 8px; }
    .new-press-release-btn { padding: 10px 20px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
    .new-press-release-btn:hover { background-color: #218838; }
  </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 Press Release Button -->
            <div class="top-section">
              <h1>Manage Press Releases</h1>
              <!-- Search Filter Box -->
              <div class="search-filter">
                <input type="text" id="search-input" class="search-input" placeholder="Search press releases..." oninput="filterPressReleases()" />
              </div>
              <!-- New Press Release Button -->
              <div class="new-press-release-btn-container">
                <button type="button" class="new-press-release-btn" data-toggle="modal" data-target="#addPressReleaseModal">
                  <i class="fas fa-plus"></i> New Press Release
                </button>
              </div>
            </div>

            <!-- Press Releases Display (Styled with Cards) -->
            <div class="press-release-grid" id="press-release-grid">
              <?php
if ($press_releases) {
  foreach ($press_releases as $press_release) {
    // Format the press release's date
    $date_posted = date("F j, Y", strtotime($press_release['date_created']));

    // Document filename (from the database)
    $document_filename = $press_release['resource_name']; // Assuming this is the column where the document filename is stored

    // Full document path
    $document_path = 'press_release/documents/' . $document_filename; // Concatenate the folder path with the filename

    // Determine press release status
    $press_release_status = ($press_release['release_status'] == 'publish') ? 'Published' : 'Draft';

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

    // Display the document
    if (!empty($document_filename)) {
      $file_extension = pathinfo($document_filename, PATHINFO_EXTENSION);

      if ($file_extension == 'pdf') {
        // If the file is a PDF, embed a PDF viewer
        echo "<div class='document-preview'>";
        echo "<embed src='{$document_path}' type='application/pdf' width='100%' height='200px' />";
        echo "</div>";
      } else {
        // If it's a different type of document, display a download link
        echo "<div class='document-preview'>";
        echo "<a href='{$document_path}' target='_blank' class='btn btn-secondary'>Download Document</a>";
        echo "</div>";
      }
    } else {
      echo "<div class='text-danger'>No document uploaded</div>";
    }

    // Display other press release details
    echo "<div class='press-release-title'>{$press_release['title']}</div>";
    echo "<div class='press-release-info'>";
    echo "<strong>Posted on:</strong> {$date_posted} <br>";
    echo "<strong>Release Status:</strong> {$press_release_status} <br>";
    echo "</div>";

    // Action buttons
    echo "<div class='press-release-actions'>";
    echo "<a href='#' class='btn btn-info btn-sm btn-custom view-press-release' data-id='{$press_release['resource_id']}'><i class='fas fa-eye'></i> View</a>";
    echo "<a href='#' class='btn btn-warning btn-sm btn-custom edit-press-release' data-id='{$press_release['resource_id']}'><i class='fas fa-edit'></i> Edit</a>";
    echo "<a href='#' class='btn btn-danger btn-sm btn-custom delete-press-release' data-id='{$press_release['resource_id']}'><i class='fas fa-trash'></i> Delete</a>";
    echo "</div>";

    echo "</div>"; // End of press release card
  }
} else {
  echo "<div class='col-12 text-center'>No press releases found.</div>";
}
?>


            </div> <!-- End of press release grid -->
          </div>
        </div>
      </div>
    </section>
  </div>

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

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

    // Handle Edit and Delete actions
    document.querySelectorAll('.edit-press-release').forEach(button => {
      button.addEventListener('click', function (e) {
        e.preventDefault();
        const pressReleaseId = this.getAttribute('data-id');
        window.location.href = `edit_press_release.php?id=${pressReleaseId}`;
      });
    });

    document.querySelectorAll('.delete-press-release').forEach(button => {
      button.addEventListener('click', function (e) {
        e.preventDefault();
        const pressReleaseId = this.getAttribute('data-id');
        Swal.fire({
          title: 'Are you sure?',
          text: 'This press release will be deleted permanently!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'Cancel'
        }).then((result) => {
          if (result.isConfirmed) {
            // Simulate a delete action, you would replace this with AJAX to delete the press release
            Swal.fire('Deleted!', 'The press release has been deleted.', 'success');
            // Reload the page to show the changes (if using AJAX, remove this)
            location.reload();
          }
        });
      });
    });
  </script>

  <!-- New Press Release Modal -->
  <div class="modal fade" id="addPressReleaseModal" tabindex="-1" aria-labelledby="addPressReleaseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="addPressReleaseModalLabel">Add New Press Release</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <!-- Form to create a new press release -->
          <form action="save_press_release.php" method="POST" enctype="multipart/form-data">
            <div class="form-group">
              <label for="release_title">Press Release Title</label>
              <input type="text" class="form-control" id="release_title" name="release_title" required>
            </div>
            <div class="form-group">
              <label for="release_content">Content</label>
              <textarea class="form-control" id="release_content" name="release_content" rows="5" required></textarea>
            </div>
            <div class="form-group">
              <label for="release_image">Upload Image</label>
              <input type="file" class="form-control-file" id="release_image" name="release_image">
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary">Save Press Release</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- Script dependencies -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script src="dist/js/adminlte.min.js"></script>
</body>
</html>
