<?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':
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                
                if ($name) {
                    $slug = generateSlug($name);
                    
                    // Check if category already exists
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE name = ? OR slug = ?");
                    $stmt->execute([$name, $slug]);
                    
                    if ($stmt->fetchColumn() > 0) {
                        $error = 'Category with this name already exists.';
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO categories (name, slug, description) VALUES (?, ?, ?)");
                        if ($stmt->execute([$name, $slug, $description])) {
                            $success = 'Category added successfully!';
                        } else {
                            $error = 'Error adding category.';
                        }
                    }
                } else {
                    $error = 'Category name is required.';
                }
                break;
                
            case 'edit':
                $id = (int)($_POST['id'] ?? 0);
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                
                if ($id && $name) {
                    $slug = generateSlug($name);
                    
                    // Check if category name already exists (excluding current category)
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE (name = ? OR slug = ?) AND id != ?");
                    $stmt->execute([$name, $slug, $id]);
                    
                    if ($stmt->fetchColumn() > 0) {
                        $error = 'Category with this name already exists.';
                    } else {
                        $stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ?, description = ? WHERE id = ?");
                        if ($stmt->execute([$name, $slug, $description, $id])) {
                            $success = 'Category updated successfully!';
                        } else {
                            $error = 'Error updating category.';
                        }
                    }
                } else {
                    $error = 'Category name is required.';
                }
                break;
        }
    }
}

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // Check if category has posts
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM posts WHERE category_id = ?");
    $stmt->execute([$id]);
    $post_count = $stmt->fetchColumn();
    
    if ($post_count > 0) {
        $error = "Cannot delete category. It has {$post_count} post(s) assigned to it.";
    } else {
        $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
        if ($stmt->execute([$id])) {
            $success = 'Category deleted successfully!';
        } else {
            $error = 'Error deleting category.';
        }
    }
}

// Get all categories
$categories = $pdo->query("SELECT c.*, COUNT(p.id) as post_count 
                          FROM categories c 
                          LEFT JOIN posts p ON c.id = p.category_id 
                          GROUP BY c.id 
                          ORDER BY c.name")->fetchAll();

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

$page_title = 'Manage Categories';
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="categories-management">
    <div class="categories-form-section">
        <div class="form-card">
            <div class="form-header">
                <h2>
                    <i class="fas fa-<?php echo $edit_category ? 'edit' : 'plus'; ?>"></i>
                    <?php echo $edit_category ? 'Edit Category' : 'Add New Category'; ?>
                </h2>
            </div>

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

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

                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" rows="3" 
                              placeholder="Enter category description (optional)"><?php echo htmlspecialchars($edit_category['description'] ?? ''); ?></textarea>
                </div>

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

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

        <div class="categories-table-wrapper">
            <table class="categories-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Description</th>
                        <th>Posts</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $category): ?>
                        <tr class="<?php echo $edit_category && $edit_category['id'] == $category['id'] ? 'editing' : ''; ?>">
                            <td>
                                <strong><?php echo htmlspecialchars($category['name']); ?></strong>
                                <div class="category-slug">
                                    <small>Slug: <?php echo htmlspecialchars($category['slug']); ?></small>
                                </div>
                            </td>
                            <td>
                                <span class="category-description">
                                    <?php echo htmlspecialchars($category['description'] ?: 'No description'); ?>
                                </span>
                            </td>
                            <td>
                                <span class="post-count-badge">
                                    <?php echo $category['post_count']; ?> posts
                                </span>
                            </td>
                            <td><?php echo formatDate($category['created_at']); ?></td>
                            <td class="actions">
                                <a href="?edit=<?php echo $category['id']; ?>" class="btn btn-sm">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="../category.php?cat=<?php echo urlencode($category['slug']); ?>" 
                                   class="btn btn-sm btn-secondary" target="_blank">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                <?php if ($category['post_count'] == 0): ?>
                                    <a href="?action=delete&id=<?php echo $category['id']; ?>" 
                                       class="btn btn-sm btn-danger" 
                                       onclick="return confirm('Are you sure you want to delete this category?')">
                                        <i class="fas fa-trash"></i> Delete
                                    </a>
                                <?php else: ?>
                                    <span class="btn btn-sm btn-disabled" title="Cannot delete category with posts">
                                        <i class="fas fa-trash"></i> Delete
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

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

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