<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

$pdo = getDB();
$success = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $title = trim($_POST['title'] ?? '');
                $content = trim($_POST['content'] ?? '');
                $type = $_POST['type'] ?? 'info';
                $status = $_POST['status'] ?? 'inactive';
                $show_on_home = isset($_POST['show_on_home']) ? 1 : 0;

                if ($title && $content) {
                    $stmt = $pdo->prepare("INSERT INTO announcements (title, content, type, status, show_on_home, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                    if ($stmt->execute([$title, $content, $type, $status, $show_on_home, $_SESSION['user_id']])) {
                        $success = 'Announcement added successfully!';
                    } else {
                        $error = 'Error adding announcement.';
                    }
                } else {
                    $error = 'Title and content are required.';
                }
                break;

            case 'edit':
                $id = (int)($_POST['id'] ?? 0);
                $title = trim($_POST['title'] ?? '');
                $content = trim($_POST['content'] ?? '');
                $type = $_POST['type'] ?? 'info';
                $status = $_POST['status'] ?? 'inactive';
                $show_on_home = isset($_POST['show_on_home']) ? 1 : 0;

                if ($id && $title && $content) {
                    $stmt = $pdo->prepare("UPDATE announcements SET title = ?, content = ?, type = ?, status = ?, show_on_home = ? WHERE id = ?");
                    if ($stmt->execute([$title, $content, $type, $status, $show_on_home, $id])) {
                        $success = 'Announcement updated successfully!';
                    } else {
                        $error = 'Error updating announcement.';
                    }
                } else {
                    $error = 'Title and content are required.';
                }
                break;
        }
    }
}

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];

    $stmt = $pdo->prepare("DELETE FROM announcements WHERE id = ?");
    if ($stmt->execute([$id])) {
        $success = 'Announcement deleted successfully!';
    } else {
        $error = 'Error deleting announcement.';
    }
}

// Get all announcements
$announcements = $pdo->query("SELECT * FROM announcements ORDER BY created_at DESC")->fetchAll();

// Get announcement for editing
$edit_announcement = null;
if (isset($_GET['edit']) && $_GET['edit']) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM announcements WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_announcement = $stmt->fetch();
}

$page_title = 'Manage Announcements';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="announcements-management">
    <div class="announcements-form-section">
        <div class="form-card">
            <div class="form-header">
                <h2>
                    <i class="fas fa-<?php echo $edit_announcement ? 'edit' : 'plus'; ?>"></i>
                    <?php echo $edit_announcement ? 'Edit Announcement' : 'Add New Announcement'; ?>
                </h2>
            </div>

            <form method="POST" class="announcement-form">
                <input type="hidden" name="action" value="<?php echo $edit_announcement ? 'edit' : 'add'; ?>">
                <?php if ($edit_announcement): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_announcement['id']; ?>">
                <?php endif; ?>

                <div class="form-group">
                    <label for="title">Title *</label>
                    <input type="text" id="title" name="title" required
                           value="<?php echo htmlspecialchars($edit_announcement['title'] ?? ''); ?>"
                           placeholder="Enter announcement title">
                </div>

                <div class="form-group">
                    <label for="content">Content *</label>
                    <textarea id="content" name="content" rows="5" required
                              placeholder="Enter announcement content"><?php echo htmlspecialchars($edit_announcement['content'] ?? ''); ?></textarea>
                </div>

                <div class="form-group">
                    <label for="type">Type</label>
                    <select id="type" name="type">
                        <option value="info" <?php echo ($edit_announcement['type'] ?? 'info') == 'info' ? 'selected' : ''; ?>>Info</option>
                        <option value="warning" <?php echo ($edit_announcement['type'] ?? 'info') == 'warning' ? 'selected' : ''; ?>>Warning</option>
                        <option value="success" <?php echo ($edit_announcement['type'] ?? 'info') == 'success' ? 'selected' : ''; ?>>Success</option>
                        <option value="error" <?php echo ($edit_announcement['type'] ?? 'info') == 'error' ? 'selected' : ''; ?>>Error</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="status">Status</label>
                    <select id="status" name="status">
                        <option value="inactive" <?php echo ($edit_announcement['status'] ?? 'inactive') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        <option value="active" <?php echo ($edit_announcement['status'] ?? 'inactive') == 'active' ? 'selected' : ''; ?>>Active</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="show_on_home" value="1" <?php echo ($edit_announcement['show_on_home'] ?? 1) ? 'checked' : ''; ?>>
                        Show on home page
                    </label>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i>
                        <?php echo $edit_announcement ? 'Update Announcement' : 'Add Announcement'; ?>
                    </button>
                    <?php if ($edit_announcement): ?>
                        <a href="announcements.php" class="btn btn-secondary">Cancel</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <div class="announcements-list-section">
        <div class="announcements-header">
            <h2>All Announcements</h2>
            <span class="announcements-count"><?php echo count($announcements); ?> announcements</span>
        </div>

        <div class="announcements-table-wrapper">
            <table class="announcements-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Show on Home</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($announcements as $announcement): ?>
                        <tr class="<?php echo $edit_announcement && $edit_announcement['id'] == $announcement['id'] ? 'editing' : ''; ?>">
                            <td>
                                <strong><?php echo htmlspecialchars($announcement['title']); ?></strong>
                            </td>
                            <td>
                                <span class="type-badge type-<?php echo $announcement['type']; ?>">
                                    <?php echo ucfirst($announcement['type']); ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $announcement['status']; ?>">
                                    <?php echo ucfirst($announcement['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo $announcement['show_on_home'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'; ?>
                            </td>
                            <td><?php echo formatDate($announcement['created_at']); ?></td>
                            <td class="actions">
                                <a href="?edit=<?php echo $announcement['id']; ?>" class="btn btn-sm">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="?action=delete&id=<?php echo $announcement['id']; ?>"
                                   class="btn btn-sm btn-danger"
                                   onclick="return confirm('Are you sure you want to delete this announcement?')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($announcements)): ?>
            <div class="no-announcements">
                <i class="fas fa-bullhorn"></i>
                <p>No announcements found. Create your first announcement above.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include 'includes/admin_footer.php'; ?>