<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/Announcement.php';

// Redirect if not logged in or not a DAC Staff
redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

// Initialize Announcement class
$announcement = new Announcement($pdo);

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action_type = $_POST['action_type'] ?? ''; // 'add' or 'edit' or 'delete'
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $status = $_POST['status'] ?? 'Draft';
    $announcement_id = $_POST['announcement_id'] ?? null;
    $current_photo = $_POST['current_photo'] ?? ''; // For editing, keep track of existing photo

    if ($action_type === 'delete') {
        if ($announcement_id) {
            try {
                $announcement->deleteAnnouncement($announcement_id);
                set_message('Announcement deleted successfully!', 'success');
            } catch (Exception $e) {
                set_message('Error deleting announcement: ' . $e->getMessage(), 'danger');
            }
        }
    } else {
        // Handle photo upload
        $photoPath = $current_photo; // Default to current photo if not uploading new
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            try {
                $photoPath = $announcement->handlePhotoUpload($_FILES['photo']);
                // If editing and a new photo is uploaded, delete the old one
                if ($action_type === 'edit' && !empty($current_photo) && $current_photo !== $photoPath) {
                    unlink('../uploads/announcements/' . $current_photo); // Delete old file
                }
            } catch (Exception $e) {
                set_message('Photo upload error: ' . $e->getMessage(), 'danger');
                header('Location: manage_announcements.php');
                exit();
            }
        }

        if (empty($title) || empty($description)) {
            set_message('Title and description cannot be empty.', 'danger');
        } else {
            try {
                if ($action_type === 'add') {
                    $announcement->addAnnouncement($title, $description, $photoPath, $status, $_SESSION['user_id']);
                    set_message('Announcement added successfully!', 'success');
                } elseif ($action_type === 'edit' && $announcement_id) {
                    $announcement->updateAnnouncement($announcement_id, $title, $description, $photoPath, $status, $_SESSION['user_id']);
                    set_message('Announcement updated successfully!', 'success');
                }
            } catch (Exception $e) {
                set_message('Error: ' . $e->getMessage(), 'danger');
            }
        }
    }
    header('Location: manage_announcements.php');
    exit();
}

// Fetch announcements for display
$announcements = $announcement->getAllAnnouncements();

// Prepare data for editing if action is 'edit'
$editAnnouncement = null;
if ($action === 'edit' && $id) {
    $editAnnouncement = $announcement->getAnnouncementById($id);
}
?>

<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_admin.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_admin.php");
        ?>
        <!-- Main Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Manage Announcements</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php
            // Display session messages
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">' . htmlspecialchars($_SESSION['message']) . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
            }
            ?>

            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?php echo $editAnnouncement ? 'Edit' : 'Add New'; ?> Announcement</h5>
                </div>
                <div class="card-body">
                    <form action="manage_announcements.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action_type" value="<?php echo $editAnnouncement ? 'edit' : 'add'; ?>">
                        <?php if ($editAnnouncement): ?>
                            <input type="hidden" name="announcement_id" value="<?php echo htmlspecialchars($editAnnouncement['pkdspsann_id']); ?>">
                            <input type="hidden" name="current_photo" value="<?php echo htmlspecialchars($editAnnouncement['dspsann_photopath']); ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label for="title" class="form-label">Title</label>
                            <input type="text" class="form-control rounded" id="title" name="title" value="<?php echo htmlspecialchars($editAnnouncement['dspsann_title'] ?? ''); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label d-flex justify-content-between align-items-center">
                                <span>Description</span>
                            </label>
                            <textarea class="form-control rounded-3" id="description" name="description" rows="8" required><?php echo htmlspecialchars($editAnnouncement['dspsann_description'] ?? ''); ?></textarea>
                            <div class="form-text">Use the toolbar to format bullet lists, emphasize important actions, and link to additional resources.</div>
                        </div>
                        <div class="mb-3">
                            <label for="photo" class="form-label">Photo (Optional)</label>
                            <input type="file" class="form-control rounded" id="photo" name="photo" accept="image/*">
                            <?php if ($editAnnouncement && !empty($editAnnouncement['dspsann_photopath'])): ?>
                                <div class="mt-2">
                                    Current Photo: <img src="../uploads/announcements/<?php echo htmlspecialchars($editAnnouncement['dspsann_photopath']); ?>" alt="Announcement Photo" class="announcement-img">
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select rounded" id="status" name="status" required>
                                <option value="Draft" <?php echo ($editAnnouncement && $editAnnouncement['dspsann_status'] == 'Draft') ? 'selected' : ''; ?>>Draft</option>
                                <option value="Published" <?php echo ($editAnnouncement && $editAnnouncement['dspsann_status'] == 'Published') ? 'selected' : ''; ?>>Published</option>
                                <option value="Archived" <?php echo ($editAnnouncement && $editAnnouncement['dspsann_status'] == 'Archived') ? 'selected' : ''; ?>>Archived</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary rounded">
                            <i class="fas fa-<?php echo $editAnnouncement ? 'save' : 'plus'; ?> me-2"></i> <?php echo $editAnnouncement ? 'Update' : 'Add'; ?> Announcement
                        </button>
                        <?php if ($editAnnouncement): ?>
                            <a href="manage_announcements.php" class="btn btn-secondary rounded ms-2">Cancel Edit</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header text-white" style="background-color: #28a745;">
                    <h5 class="mb-0">All Announcements</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Photo</th>
                                    <th>Status</th>
                                    <th>Reg. Date</th>
                                    <th>Mod. Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($announcements)): ?>
                                    <?php foreach ($announcements as $ann): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($ann['pkdspsann_id']); ?></td>
                                            <td><?php echo htmlspecialchars($ann['dspsann_title']); ?></td>
                                            <td><?php echo htmlspecialchars(substr($ann['dspsann_description'], 0, 100)) . (strlen($ann['dspsann_description']) > 100 ? '...' : ''); ?></td>
                                            <td>
                                                <?php if (!empty($ann['dspsann_photopath'])): ?>
                                                    <img src="../uploads/announcements/<?php echo htmlspecialchars($ann['dspsann_photopath']); ?>" alt="Photo" class="announcement-img">
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td><span class="badge bg-<?php
                                                if ($ann['dspsann_status'] == 'Published') echo 'success';
                                                else if ($ann['dspsann_status'] == 'Draft') echo 'warning';
                                                else echo 'secondary';
                                            ?>"><?php echo htmlspecialchars($ann['dspsann_status']); ?></span></td>
                                            <td><?php echo htmlspecialchars($ann['dspsann_reg_datetime']); ?></td>
                                            <td><?php echo htmlspecialchars($ann['dspsann_mod_datetime']); ?></td>
                                            <td>
                                                <a href="manage_announcements.php?action=edit&id=<?php echo htmlspecialchars($ann['pkdspsann_id']); ?>" class="btn btn-sm btn-warning rounded btn-action">
                                                    <i class="fas fa-edit"></i> 
                                                </a>
                                                <form action="manage_announcements.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this announcement? This action cannot be undone.');">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="announcement_id" value="<?php echo htmlspecialchars($ann['pkdspsann_id']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded btn-action">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="8" class="text-center">No announcements found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <?php
    // Include Footer file for owner pages
    include_once("../includes/footer_admin.php");
    ?>
    <script src="https://cdn.jsdelivr.net/npm/@ckeditor/ckeditor5-build-classic@38.1.1/build/ckeditor.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var textarea = document.querySelector('#description');
            if (textarea && typeof ClassicEditor !== 'undefined') {
                ClassicEditor
                    .create(textarea, {
                        toolbar: [
                            'heading','|','bold','italic','underline','bulletedList','numberedList','blockQuote',
                            '|','link','insertTable','undo','redo'
                        ]
                    })
                    .catch(function (error) {
                        console.error('Failed to initialise rich text editor', error);
                    });
            }
        });
    </script>
</body>
</html>
