<?php
// File: /admin/articles.php
include 'header.php';

// --- LOGIC TO HANDLE EDIT MODE ---
$edit_mode = false;
$article_to_edit = null;

if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
    $edit_mode = true;
    $article_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
    
    // CHANGE 1: Added 'video_url' to this query
    $stmt = $conn->prepare("SELECT id, title, content, category, image_path, video_url FROM articles WHERE id = ?");
    $stmt->bind_param("i", $article_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $article_to_edit = $result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch all articles to display in the table
$articles = [];
$result = $conn->query("SELECT id, title, category, created_at, video_url FROM articles ORDER BY created_at DESC");
if ($result) {
    $articles = $result->fetch_all(MYSQLI_ASSOC);
}
?>

<div class="p-6 md:p-8">
    <h1 class="text-3xl font-bold text-ucf-charcoal mb-6">Manage News & Articles</h1>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-1 bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">
                <?php echo $edit_mode ? 'Edit Article' : 'Add New Article'; ?>
            </h2>

            <?php if (!$edit_mode): ?>
                <p class="text-sm text-gray-600 mb-4">
                    Fill out the form below to publish a new post. It will be visible to the public on the 'News' page immediately.
                </p>
            <?php endif; ?>

            <form action="article_handler.php" method="POST" enctype="multipart/form-data" class="space-y-4">
                
                <?php if ($edit_mode && $article_to_edit): ?>
                    <input type="hidden" name="article_id" value="<?php echo htmlspecialchars($article_to_edit['id']); ?>">
                    <input type="hidden" name="existing_image_path" value="<?php echo htmlspecialchars($article_to_edit['image_path']); ?>">
                <?php endif; ?>

                <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">Title</label>
                    <input type="text" name="title" id="title" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green" value="<?php echo $edit_mode ? htmlspecialchars($article_to_edit['title']) : ''; ?>">
                </div>

                <div>
                    <label for="category" class="block text-sm font-medium text-gray-700">Category</label>
                    <select name="category" id="category" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green">
                        <option value="News" <?php if($edit_mode && $article_to_edit['category'] == 'News') echo 'selected'; ?>>News</option>
                        <option value="Competition" <?php if($edit_mode && $article_to_edit['category'] == 'Competition') echo 'selected'; ?>>Competition</option>
                        <option value="Exhibition" <?php if($edit_mode && $article_to_edit['category'] == 'Exhibition') echo 'selected'; ?>>Exhibition</option>
                        <option value="Interview" <?php if($edit_mode && $article_to_edit['category'] == 'Interview') echo 'selected'; ?>>Interview</option>
                    </select>
                </div>

                <div>
                    <label for="video_url" class="block text-sm font-medium text-gray-700">YouTube Video URL (Optional)</label>
                    <input type="url" name="video_url" id="video_url" placeholder="https://www.youtube.com/watch?v=..." 
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green" 
                           value="<?php echo $edit_mode ? htmlspecialchars($article_to_edit['video_url'] ?? '') : ''; ?>">
                    <p class="text-xs text-gray-500 mt-1">If provided, the video thumbnail will appear automatically.</p>
                </div>

                <div>
                    <label for="content" class="block text-sm font-medium text-gray-700">Content</label>
                    <textarea name="content" id="content" rows="8" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green"><?php echo $edit_mode ? htmlspecialchars($article_to_edit['content']) : ''; ?></textarea>
                </div>

                <div>
                    <label for="featured_image" class="block text-sm font-medium text-gray-700">Featured Image</label>
                    <input type="file" name="featured_image" id="featured_image" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-ucf-green-light file:text-ucf-green-dark hover:file:bg-green-100">
                    <?php if ($edit_mode && !empty($article_to_edit['image_path'])): ?>
                        <p class="text-xs text-gray-500 mt-2">Current image (click to enlarge):</p>
                        <img id="image-thumbnail" src="/<?php echo htmlspecialchars($article_to_edit['image_path']); ?>" class="h-20 w-auto mt-1 rounded-md cursor-pointer hover:opacity-80 transition-opacity" alt="Current Image Thumbnail">
                    <?php endif; ?>
                </div>

                <div>
                    <?php if ($edit_mode): ?>
                        <button type="submit" name="edit_article" class="w-full bg-ucf-green text-white font-bold py-2 px-4 rounded-lg hover:bg-ucf-green-dark transition-colors">Update Article</button>
                        <a href="articles.php" class="block text-center mt-2 text-sm text-gray-600 hover:text-ucf-charcoal">Cancel Edit</a>
                    <?php else: ?>
                        <button type="submit" name="add_article" class="w-full bg-ucf-green text-white font-bold py-2 px-4 rounded-lg hover:bg-ucf-green-dark transition-colors">Publish Article</button>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <div class="lg:col-span-2 bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">Published Articles</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Category</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($articles as $article): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    <?php echo htmlspecialchars($article['title']); ?>
                                    <?php if(!empty($article['video_url'])): ?>
                                        <span class="ml-2 text-red-600" title="Video Article">🎥</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($article['category']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('M d, Y', strtotime($article['created_at'])); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                                    <a href="articles.php?action=edit&id=<?php echo $article['id']; ?>" class="text-indigo-600 hover:text-indigo-900">Edit</a>
                                    
                                    <form action="article_handler.php" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this article?');">
                                        <input type="hidden" name="article_id" value="<?php echo $article['id']; ?>">
                                        <button type="submit" name="delete_article" class="text-red-600 hover:text-red-900">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div id="image-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden items-center justify-center z-50 p-4">
    <span id="close-modal" class="absolute top-4 right-6 text-white text-4xl font-bold cursor-pointer hover:text-gray-300">&times;</span>
    <img id="modal-image-content" class="max-w-[90vw] max-h-[90vh] rounded-lg shadow-lg">
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Get elements for the modal functionality
    const thumbnail = document.getElementById('image-thumbnail');
    const modal = document.getElementById('image-modal');
    const modalImage = document.getElementById('modal-image-content');
    const closeModalBtn = document.getElementById('close-modal');

    // Show the modal when the thumbnail is clicked
    if (thumbnail) {
        thumbnail.addEventListener('click', () => {
            modalImage.src = thumbnail.src; 
            modal.style.display = 'flex';
        });
    }

    // Hide the modal when the close button is clicked
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', () => {
            modal.style.display = 'none';
        });
    }
    
    // Hide the modal when clicking on the background overlay
    if (modal) {
        modal.addEventListener('click', (event) => {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        });
    }
});
</script>

<?php include 'footer.php'; ?>