<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
   header('Location: login.php');
   exit();
}

// Handle bulk actions 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   $notification_ids = $_POST['notification_ids'] ?? [];
   $action = $_POST['action'] ?? '';

   if (!empty($notification_ids)) {
       if ($action === 'mark_read') {
           $ids = implode(',', array_map('intval', $notification_ids));
           $conn->query("UPDATE notifications SET is_read = 1 WHERE notification_id IN ($ids)");
       } elseif ($action === 'delete') {
           $ids = implode(',', array_map('intval', $notification_ids));
           $conn->query("DELETE FROM notifications WHERE notification_id IN ($ids)");
       }
   }
}

// Get notifications with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$query = "SELECT n.*, u.username as created_by 
         FROM notifications n
         LEFT JOIN users u ON n.user_id = u.user_id 
         ORDER BY n.created_at DESC 
         LIMIT ? OFFSET ?";
         
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$notifications = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get total count for pagination
$total_rows = $conn->query("SELECT COUNT(*) as count FROM notifications")->fetch_assoc()['count'];
$total_pages = ceil($total_rows / $limit);
?>

<!DOCTYPE html>
<html>
<head>
   <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Notifications')); ?>
   <?php include 'layouts/head-css.php'; ?>
</head>

<body>
   <div id="layout-wrapper">
       <?php include 'layouts/menu.php'; ?>
       
       <div class="main-content">
           <div class="page-content">
               <div class="container-fluid">
                   <div class="row">
                       <div class="col-12">
                           <div class="card">
                               <div class="card-header align-items-center d-flex">
                                   <h4 class="card-title mb-0 flex-grow-1">All Notifications</h4>
                                   <div class="flex-shrink-0">
                                       <button type="button" class="btn btn-soft-danger btn-sm" id="deleteSelected" disabled>
                                           <i class="ri-delete-bin-2-line align-bottom"></i> Delete Selected
                                       </button>
                                       <button type="button" class="btn btn-soft-success btn-sm" id="markSelectedRead" disabled>
                                           <i class="ri-check-double-line align-bottom"></i> Mark Selected as Read
                                       </button>
                                   </div>
                               </div>

                               <div class="card-body">
                                   <form id="notificationForm" method="POST">
                                       <div class="table-responsive">
                                           <table class="table table-borderless align-middle mb-0">
                                               <thead>
                                                   <tr>
                                                       <th scope="col" style="width: 50px;">
                                                           <div class="form-check">
                                                               <input class="form-check-input" type="checkbox" id="checkAll">
                                                           </div>
                                                       </th>
                                                       <th scope="col">Notification</th>
                                                       <th scope="col">Type</th>
                                                       <th scope="col">Time</th>
                                                       <th scope="col">Status</th>
                                                       <th scope="col">Actions</th>
                                                   </tr>
                                               </thead>
                                               <tbody>
                                                   <?php foreach ($notifications as $notification): ?>
                                                   <tr class="<?php echo $notification['is_read'] ? '' : 'table-light'; ?>">
                                                       <td>
                                                           <div class="form-check">
                                                               <input class="form-check-input notification-check" type="checkbox" 
                                                                      name="notification_ids[]" value="<?php echo $notification['notification_id']; ?>">
                                                           </div>
                                                       </td>
                                                       <td>
                                                           <div class="text-break" style="max-width: 600px;">
                                                               <?php echo htmlspecialchars($notification['content']); ?>
                                                           </div>
                                                       </td>
                                                       <td>
                                                           <span class="badge bg-info-subtle text-info">
                                                               <?php echo htmlspecialchars($notification['type']); ?>
                                                           </span>
                                                       </td>
                                                       <td>
                                                           <?php echo date('M d, Y H:i', strtotime($notification['created_at'])); ?>
                                                       </td>
                                                       <td>
                                                           <?php if ($notification['is_read']): ?>
                                                               <span class="badge bg-success-subtle text-success">Read</span>
                                                           <?php else: ?>
                                                               <span class="badge bg-warning-subtle text-warning">Unread</span>
                                                           <?php endif; ?>
                                                       </td>
                                                       <td>
                                                           <?php if (!$notification['is_read']): ?>
                                                           <button type="button" class="btn btn-soft-success btn-sm" 
                                                                   onclick="markAsRead(<?php echo $notification['notification_id']; ?>)">
                                                               <i class="ri-check-double-line align-bottom"></i>
                                                           </button>
                                                           <?php endif; ?>
                                                           <button type="button" class="btn btn-soft-danger btn-sm"
                                                                   onclick="deleteNotification(<?php echo $notification['notification_id']; ?>)">
                                                               <i class="ri-delete-bin-line align-bottom"></i>
                                                           </button>
                                                       </td>
                                                   </tr>
                                                   <?php endforeach; ?>
                                               </tbody>
                                           </table>
                                       </div>

                                       <input type="hidden" name="action" id="bulkAction" value="">
                                   </form>

                                   <!-- Pagination -->
                                   <?php if ($total_pages > 1): ?>
                                   <div class="d-flex justify-content-end mt-3">
                                       <nav aria-label="Notification navigation">
                                           <ul class="pagination">
                                               <?php for($i = 1; $i <= $total_pages; $i++): ?>
                                               <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                                   <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                               </li>
                                               <?php endfor; ?>
                                           </ul>
                                       </nav>
                                   </div>
                                   <?php endif; ?>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
   <script>
document.addEventListener('DOMContentLoaded', function() {
   const form = document.getElementById('notificationForm');
   const checkAll = document.getElementById('checkAll');
   const deleteSelected = document.getElementById('deleteSelected');
   const markSelectedRead = document.getElementById('markSelectedRead');
   const checks = document.querySelectorAll('.notification-check');

   checkAll.addEventListener('change', function() {
       checks.forEach(check => check.checked = this.checked);
       updateBulkButtons();
   });

   checks.forEach(check => {
       check.addEventListener('change', function() {
           updateBulkButtons();
           checkAll.checked = Array.from(checks).every(c => c.checked);
       });
   });

   function updateBulkButtons() {
       const hasChecked = Array.from(checks).some(c => c.checked);
       deleteSelected.disabled = !hasChecked;
       markSelectedRead.disabled = !hasChecked;
   }

   deleteSelected.addEventListener('click', function() {
       Swal.fire({
           title: 'Delete Selected Notifications?',
           text: "This action cannot be undone!",
           icon: 'warning',
           showCancelButton: true,
           confirmButtonText: 'Yes, delete them!',
           cancelButtonText: 'Cancel'
       }).then((result) => {
           if (result.isConfirmed) {
               document.getElementById('bulkAction').value = 'delete';
               form.submit();
           }
       });
   });

   markSelectedRead.addEventListener('click', function() {
       Swal.fire({
           title: 'Mark Selected as Read?',
           icon: 'question',
           showCancelButton: true,
           confirmButtonText: 'Yes, mark as read',
           cancelButtonText: 'Cancel'
       }).then((result) => {
           if (result.isConfirmed) {
               document.getElementById('bulkAction').value = 'mark_read';
               form.submit();
           }
       });
   });
});

function markAsRead(id) {
   Swal.fire({
       title: 'Processing...',
       text: 'Please wait',
       allowOutsideClick: false,
       showConfirmButton: false,
       willOpen: () => {
           Swal.showLoading();
       }
   });

   fetch('mark_notification_read.php', {
       method: 'POST',
       headers: {'Content-Type': 'application/json'},
       body: JSON.stringify({notification_id: id})
   })
   .then(response => response.json())
   .then(data => {
       if(data.success) {
           Swal.fire({
               icon: 'success',
               title: 'Success!',
               text: 'Notification marked as read',
               showConfirmButton: false,
               timer: 1500
           }).then(() => {
               window.location.reload();
           });
       } else {
           throw new Error(data.error || 'Failed to mark as read');
       }
   })
   .catch(error => {
       Swal.fire({
           icon: 'error',
           title: 'Error!',
           text: error.message
       });
   });
}

function deleteNotification(id) {
   Swal.fire({
       title: 'Delete Notification?',
       text: "This action cannot be undone!",
       icon: 'warning',
       showCancelButton: true,
       confirmButtonText: 'Yes, delete it!',
       cancelButtonText: 'Cancel'
   }).then((result) => {
       if (result.isConfirmed) {
           const form = document.getElementById('notificationForm');
           document.getElementById('bulkAction').value = 'delete';
           const input = document.createElement('input');
           input.type = 'hidden';
           input.name = 'notification_ids[]';
           input.value = id;
           form.appendChild(input);
           form.submit();
       }
   });
}
   </script>
</body>
</html>