<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <div class="row my-2">
      <div class="col-md-6">
        <h4>Announcements Management</h4>
      </div>
      <div class="col-md-6 text-end">
        <a href="<?php echo base_url(); ?>announcement/addAnnouncement" class="btn btn-primary">
          <i class="bi bi-plus-circle"></i> Add New Announcement
        </a>
      </div>
    </div>

    <div class="row my-2">
      <div class="col-md-12">
        <form action="<?php echo base_url(); ?>announcement/announcements" method="post">
          <div class="input-group custom-search">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" class="form-control" name="searchText" placeholder="Search by title or description..." 
                   value="<?php echo !empty($searchText) ? $searchText : ''; ?>" aria-label="Search">
            <button type="submit" class="btn btn-primary">Search</button>
            <?php if(!empty($searchText)) { ?>
            <a href="<?php echo base_url(); ?>announcement/announcements" class="btn btn-secondary">Clear</a>
            <?php } ?>
          </div>
        </form>
      </div>
    </div>

    <?php
    $success = $this->session->flashdata('success');
    $error = $this->session->flashdata('error');
    if($success) {
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                '.$success.'
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
              </div>';
    }
    if($error) {
        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                '.$error.'
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
              </div>';
    }
    ?>

    <div class="card">
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-bordered align-middle">
            <thead>
              <tr>
                <th>#</th>
                <th>Title</th>
                <th>Description</th>
                <th>Created Date</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if(!empty($announcements)) {
                  $count = 1;
                  foreach($announcements as $announcementId => $announcement) {
                      $title = isset($announcement['title']) ? $announcement['title'] : 'N/A';
                      $description = isset($announcement['description']) ? $announcement['description'] : 'N/A';
                      $createdDate = isset($announcement['createdDate']) ? date('Y-m-d H:i:s', $announcement['createdDate'] / 1000) : 'N/A';
                      
                      // Truncate description for table view
                      $shortDescription = strlen($description) > 100 ? substr($description, 0, 100) . '...' : $description;
              ?>
              <tr>
                <td><?php echo $count++; ?></td>
                <td><strong><?php echo htmlspecialchars($title); ?></strong></td>
                <td><?php echo htmlspecialchars($shortDescription); ?></td>
                <td><?php echo $createdDate; ?></td>
                <td>
                  <a href="<?php echo base_url().'announcement/viewAnnouncement/'.$announcementId; ?>" class="btn btn-sm btn-info" title="View Details">
                    <i class="bi bi-eye"></i>
                  </a>
                  <a href="<?php echo base_url().'announcement/editAnnouncement/'.$announcementId; ?>" class="btn btn-sm btn-warning" title="Edit">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <button class="btn btn-sm btn-success resendNotification" data-announcementid="<?php echo $announcementId; ?>" title="Send Notification">
                    <i class="bi bi-send"></i>
                  </button>
                  <button class="btn btn-sm btn-danger deleteAnnouncement" data-announcementid="<?php echo $announcementId; ?>" data-title="<?php echo htmlspecialchars($title); ?>" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="5" class="text-center">No announcements found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script type="text/javascript">
$(document).ready(function() {
    $('.deleteAnnouncement').click(function(e) {
        e.preventDefault();
        var announcementId = $(this).data('announcementid');
        var title = $(this).data('title');
        
        Swal.fire({
            title: 'Delete Announcement?',
            html: '<strong>' + title + '</strong><br><br><span style="color: #dc3545;">This action cannot be undone!</span>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-trash"></i> Yes, Delete',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deleting...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>announcement/deleteAnnouncement',
                    type: 'POST',
                    data: { announcementId: announcementId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Deleted!',
                                text: response.message || 'Announcement deleted successfully',
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else if(response.status == 'access') {
                            Swal.fire({
                                title: 'Access Denied',
                                text: 'You do not have permission to perform this action',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message || 'Deletion failed',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error occurred while deleting announcement',
                            icon: 'error',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                });
            }
        });
    });

    $('.resendNotification').click(function(e) {
        e.preventDefault();
        var announcementId = $(this).data('announcementid');
        
        Swal.fire({
            title: 'Send Notification?',
            html: 'This will send push notifications to <strong>all users</strong>.<br><br>Are you sure?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#198754',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-send"></i> Send to All',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Sending...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>announcement/resendNotification',
                    type: 'POST',
                    data: { announcementId: announcementId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Sent!',
                                text: response.message || 'Notifications sent successfully',
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            });
                        } else if(response.status == 'access') {
                            Swal.fire({
                                title: 'Access Denied',
                                text: 'You do not have permission to perform this action',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message || 'Failed to send notifications',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error occurred while sending notifications',
                            icon: 'error',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                });
            }
        });
    });
});
</script>

