<?php
// Check if user is authenticated and is root
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

if (AUTH_USER !== 'root') {
    header('HTTP/1.1 403 Forbidden');
    echo '<div class="alert alert-danger"><i class="fa fa-exclamation-triangle"></i> <strong>Access Denied</strong> - Only root users can manage announcements.</div>';
    return;
}

require_once('/docker/whp/web/libs/announcement_manager.php');
require_once('/docker/whp/web/libs/announcement_actions.php');
$AnnouncementMgr = new announcement_manager();

$message = '';
$message_type = '';
$edit_announcement = null;

// Handle form submissions (non-JS fallback; the async path posts the same
// actions to api/announcement-ajax.php via the shared handler).
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = whp_announcement_handle_action($AnnouncementMgr);
    $message = $result['message'];
    $message_type = $result['type'];
}

// Handle edit request
if (isset($_GET['edit']) && !empty($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $edit_announcement = $AnnouncementMgr->get_announcement($edit_id);
    if (!$edit_announcement) {
        $message = 'Announcement not found';
        $message_type = 'danger';
    }
}

// Get all announcements
$announcements = $AnnouncementMgr->get_all_announcements();
?>

<?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
        <i class="fa fa-info-circle"></i>
        <?php echo htmlspecialchars($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-bullhorn me-2"></i>
                    <?php echo $edit_announcement ? 'Edit Announcement' : 'Create New Announcement'; ?>
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/announcement-ajax.php">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <?php if ($edit_announcement): ?>
                        <input type="hidden" name="action" value="update_announcement">
                        <input type="hidden" name="id" value="<?php echo $edit_announcement['id']; ?>">
                    <?php else: ?>
                        <input type="hidden" name="action" value="create_announcement">
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="title" class="form-label">Title</label>
                                <input type="text" class="form-control" id="title" name="title" 
                                       value="<?php echo $edit_announcement ? htmlspecialchars($edit_announcement['title']) : ''; ?>" 
                                       placeholder="Enter announcement title" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="priority" class="form-label">Priority</label>
                                <select class="form-control" id="priority" name="priority">
                                    <option value="0" <?php echo ($edit_announcement && $edit_announcement['priority'] == 0) ? 'selected' : ''; ?>>Normal</option>
                                    <option value="1" <?php echo ($edit_announcement && $edit_announcement['priority'] == 1) ? 'selected' : ''; ?>>High</option>
                                    <option value="2" <?php echo ($edit_announcement && $edit_announcement['priority'] == 2) ? 'selected' : ''; ?>>Urgent</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">&nbsp;</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="pinned" name="pinned" 
                                           <?php echo ($edit_announcement && $edit_announcement['pinned']) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="pinned">
                                        <i class="fa fa-thumb-tack me-1"></i>Pin to top
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="content" class="form-label">Content (Markdown)</label>
                        <textarea class="form-control" id="content" name="content" rows="10" 
                                  placeholder="Enter announcement content using Markdown syntax" required><?php echo $edit_announcement ? htmlspecialchars($edit_announcement['markdown_content']) : ''; ?></textarea>
                        <div class="form-text bg-dark p-2 rounded mt-2">
                            <small class="text-light">
                                <strong>Markdown Help:</strong>
                                # Heading 1, ## Heading 2, ### Heading 3 | 
                                **bold** | *italic* | 
                                [link text](url) | 
                                `code` | 
                                - list item
                            </small>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="active" name="active" 
                                   <?php echo ($edit_announcement && $edit_announcement['active']) || !$edit_announcement ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="active">
                                Active (visible to users)
                            </label>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-save me-2"></i>
                            <?php echo $edit_announcement ? 'Update Announcement' : 'Create Announcement'; ?>
                        </button>
                        <?php if ($edit_announcement): ?>
                            <a href="index.php?page=announcements-management" class="btn btn-secondary">
                                <i class="fa fa-times me-2"></i>Cancel Edit
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-list me-2"></i>Existing Announcements
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($announcements)): ?>
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        No announcements found. Create your first announcement above.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" data-whp-table data-whp-page-size="25">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Status</th>
                                    <th>Priority</th>
                                    <th>Pinned</th>
                                    <th>Created</th>
                                    <th>Updated</th>
                                    <th data-whp-nosort>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($announcements as $announcement): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($announcement['title']); ?></strong>
                                            <br>
                                            <small class="text-muted">
                                                <?php echo substr(strip_tags($announcement['content']), 0, 100); ?>...
                                            </small>
                                        </td>
                                        <td>
                                            <?php if ($announcement['active']): ?>
                                                <span class="badge bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php 
                                                $priority_labels = [0 => 'Normal', 1 => 'High', 2 => 'Urgent'];
                                                $priority_colors = [0 => 'secondary', 1 => 'warning', 2 => 'danger'];
                                                $priority = $announcement['priority'];
                                            ?>
                                            <span class="badge bg-<?php echo $priority_colors[$priority] ?? 'secondary'; ?>">
                                                <?php echo $priority_labels[$priority] ?? 'Normal'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($announcement['pinned']): ?>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="fa fa-thumb-tack me-1"></i>Pinned
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">Not Pinned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small><?php echo whp_local_time($announcement['created_at'], 'M j, Y g:i A'); ?></small>
                                        </td>
                                        <td>
                                            <small><?php echo whp_local_time($announcement['updated_at'], 'M j, Y g:i A'); ?></small>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="index.php?page=announcements-management&edit=<?php echo $announcement['id']; ?>"
                                                   class="btn btn-outline-primary btn-sm"
                                                   title="Edit <?php echo htmlspecialchars($announcement['title']); ?>"
                                                   aria-label="Edit <?php echo htmlspecialchars($announcement['title']); ?>">
                                                    <i class="fa fa-edit" aria-hidden="true"></i>
                                                </a>
                                                <form method="POST" class="d-inline" data-whp-async data-whp-action="/api/announcement-ajax.php"
                                                      data-whp-confirm="Are you sure you want to <?php echo $announcement['active'] ? 'deactivate' : 'activate'; ?> this announcement?">
                                                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                                    <input type="hidden" name="action" value="toggle_status">
                                                    <input type="hidden" name="id" value="<?php echo $announcement['id']; ?>">
                                                    <?php $toggle_status_label = ($announcement['active'] ? 'Deactivate' : 'Activate') . ' ' . htmlspecialchars($announcement['title']); ?>
                                                    <button type="submit" class="btn btn-outline-<?php echo $announcement['active'] ? 'warning' : 'success'; ?> btn-sm"
                                                            title="<?php echo $toggle_status_label; ?>"
                                                            aria-label="<?php echo $toggle_status_label; ?>">
                                                        <i class="fa fa-<?php echo $announcement['active'] ? 'pause' : 'play'; ?>" aria-hidden="true"></i>
                                                    </button>
                                                </form>
                                                <form method="POST" class="d-inline" data-whp-async data-whp-action="/api/announcement-ajax.php">
                                                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                                    <input type="hidden" name="action" value="toggle_pinned">
                                                    <input type="hidden" name="id" value="<?php echo $announcement['id']; ?>">
                                                    <?php $toggle_pinned_label = ($announcement['pinned'] ? 'Unpin' : 'Pin') . ' ' . htmlspecialchars($announcement['title']); ?>
                                                    <button type="submit" class="btn btn-outline-<?php echo $announcement['pinned'] ? 'warning' : 'secondary'; ?> btn-sm"
                                                            title="<?php echo $toggle_pinned_label; ?>"
                                                            aria-label="<?php echo $toggle_pinned_label; ?>">
                                                        <i class="fa fa-thumb-tack" aria-hidden="true"></i>
                                                    </button>
                                                </form>
                                                <form method="POST" class="d-inline" data-whp-async data-whp-action="/api/announcement-ajax.php"
                                                      data-whp-remove-row
                                                      data-whp-confirm="Are you sure you want to delete this announcement? This action cannot be undone.">
                                                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                                    <input type="hidden" name="action" value="delete_announcement">
                                                    <input type="hidden" name="id" value="<?php echo $announcement['id']; ?>">
                                                    <button type="submit" class="btn btn-outline-danger btn-sm"
                                                            title="Delete <?php echo htmlspecialchars($announcement['title']); ?>"
                                                            aria-label="Delete <?php echo htmlspecialchars($announcement['title']); ?>">
                                                        <i class="fa fa-trash" aria-hidden="true"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<script src="/js/whp-table.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
<script src="/js/whp-async-forms.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>