<?php
require_once 'config.php';
require_admin();

$message = '';

// --- CRUD Operations ---
if (isset($_POST['add_notice'])) {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $image_url = null; // Optional image

    // Image upload logic
    if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/notices/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); }
        $fileName = uniqid('notice_') . '_' . basename($_FILES['image']['name']);
        $targetPath = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
            $image_url = $targetPath;
        } else {
            $message = 'Warning: Failed to upload notice image.';
        }
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO notices (title, description, image_url) VALUES (?, ?, ?)");
        $stmt->execute([$title, $description, $image_url]);
        $message = 'Notice posted successfully!';
    } catch (PDOException $e) {
        $message = 'Error posting notice: ' . $e->getMessage();
    }
}

// Fetch all notices for management view
$stmt = $pdo->query("SELECT id, title, created_at FROM notices ORDER BY created_at DESC");
$notices = $stmt->fetchAll();

require_once 'layouts.php';
render_header('Add Notice');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Manage Notices');
?>

<div class="space-y-8 p-4 sm:p-6 lg:p-8">
    <?php if ($message): ?>
        <!-- Clean Success/Warning Alert (No custom animation, using simple Unicode icons) -->
        <?php
        $is_success = strpos($message, 'successfully') !== false;
        // Determine color based on success status (green for success, red for error/warning)
        $color = $is_success ? 'green' : 'red'; // Success: green | Warning/Error: red
        $icon = $is_success ? '✓' : '⚠';        // Success: checkmark | Warning/Error: warning sign
        ?>
        <div class="bg-<?php echo $color; ?>-100 border-l-4 border-<?php echo $color; ?>-600 text-<?php echo $color; ?>-800 p-4 mb-6 rounded-lg shadow-md" role="alert">
            <div class="flex items-center">
                <span class="text-xl mr-3 font-bold text-<?php echo $color; ?>-600"><?php echo $icon; ?></span>
                <p class="font-medium"><?php echo htmlspecialchars($message); ?></p>
            </div>
        </div>
    <?php endif; ?>

    <!-- Add New Notice Form Card (Clean, professional look) -->
    <div class="bg-white p-6 md:p-8 rounded-xl shadow-xl border border-gray-100">
        <h2 class="text-2xl font-semibold text-gray-800 mb-6 border-b pb-4">Post New Announcement</h2>
        <form method="POST" action="addnotice.php" enctype="multipart/form-data" class="space-y-6">
            <!-- Title Field -->
            <div>
                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                <input type="text" name="title" id="title" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 transition-shadow duration-200" placeholder="Enter a concise title">
            </div>

            <!-- Description Field -->
            <div>
                <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Description / Details</label>
                <textarea name="description" id="description" rows="5" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 transition-shadow duration-200" placeholder="Provide full details of the announcement..."></textarea>
            </div>

            <!-- Image Upload Field (Standardized file input styling) -->
            <div>
                <label for="image" class="block text-sm font-medium text-gray-700 mb-1">Image (Optional)</label>
                <input type="file" name="image" id="image" accept="image/*" class="w-full text-sm text-gray-900 
                    file:mr-4 file:py-2 file:px-4
                    file:rounded-lg file:border-0
                    file:text-sm file:font-semibold
                    file:bg-indigo-50 file:text-indigo-700
                    hover:file:bg-indigo-100 transition duration-150
                    border border-gray-300 rounded-lg p-1.5
                    ">
            </div>

            <!-- Submit Button (Solid color, professional style) -->
            <button type="submit" name="add_notice" class="w-full sm:w-auto mt-4 py-2.5 px-6 bg-indigo-600 text-white rounded-lg font-medium text-base 
                hover:bg-indigo-700 transition duration-150 ease-in-out shadow-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                Publish Announcement
            </button>
        </form>
    </div>

    <!-- Existing Notices List -->
    <h2 class="text-2xl font-semibold text-gray-800 pt-6 border-t border-gray-200 mt-8">Existing Announcements</h2>
    <div class="bg-white rounded-xl shadow-xl overflow-hidden border border-gray-100">
        <ul class="divide-y divide-gray-100">
            <?php if ($notices): ?>
                <?php foreach ($notices as $notice): ?>
                    <!-- List Item (Subtle hover, no scale transformation) -->
                    <li class="p-4 md:p-5 transition duration-150 hover:bg-gray-50 flex justify-between items-center">
                        <div>
                            <p class="text-lg font-medium text-gray-900"><?php echo htmlspecialchars($notice['title']); ?></p>
                            <span class="text-sm text-gray-500 mt-1 block">Posted on: <span class="font-normal text-gray-600"><?php echo date('F d, Y', strtotime($notice['created_at'])); ?></span></span>
                        </div>
                        <!-- Actions (Simple text buttons - no embedded SVGs) -->
                        <div class="flex space-x-3 text-sm">
                            <button class="text-indigo-600 hover:text-indigo-800 font-medium transition duration-150" title="Edit">
                                Edit
                            </button>
                            <button class="text-red-600 hover:text-red-800 font-medium transition duration-150" title="Delete">
                                Delete
                            </button>
                        </div>
                    </li>
                <?php endforeach; ?>
            <?php else: ?>
                <li class="p-6 text-center text-gray-500 text-base py-8">
                    <p>No announcements have been posted yet.</p>
                </li>
            <?php endif; ?>
        </ul>
    </div>
</div>

<?php render_main_content_end(); ?>