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

requireLogin();

function handleImageUpload($file, $upload_dir = '../assets/images/') {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 5 * 1024 * 1024; // 5MB

    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception('Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed.');
    }

    if ($file['size'] > $max_size) {
        throw new Exception('File size too large. Maximum size is 5MB.');
    }

    // Create upload directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'category_' . time() . '_' . uniqid() . '.' . $extension;
    $filepath = $upload_dir . $filename;

    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return 'assets/images/' . $filename; // Return relative path for database
    } else {
        throw new Exception('Failed to upload file.');
    }
}

$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 = createSlug($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 {
                        $thumbnail = null;
                        try {
                            if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] !== UPLOAD_ERR_NO_FILE) {
                                $thumbnail = handleImageUpload($_FILES['thumbnail']);
                            }

                            $stmt = $pdo->prepare("INSERT INTO categories (name, slug, description, thumbnail) VALUES (?, ?, ?, ?)");
                            if ($stmt->execute([$name, $slug, $description, $thumbnail])) {
                                $success = 'Category added successfully!';
                            } else {
                                $error = 'Error adding category.';
                            }
                        } catch (Exception $e) {
                            $error = 'Error uploading thumbnail: ' . $e->getMessage();
                        }
                    }
                } 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 = createSlug($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 {
                        $thumbnail = null;
                        try {
                            if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] !== UPLOAD_ERR_NO_FILE) {
                                $thumbnail = handleImageUpload($_FILES['thumbnail']);
                            }

                            if ($thumbnail !== null) {
                                // New thumbnail uploaded
                                $stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ?, description = ?, thumbnail = ? WHERE id = ?");
                                $stmt->execute([$name, $slug, $description, $thumbnail, $id]);
                            } else {
                                // No new thumbnail, keep existing
                                $stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ?, description = ? WHERE id = ?");
                                $stmt->execute([$name, $slug, $description, $id]);
                            }

                            $success = 'Category updated successfully!';
                        } catch (Exception $e) {
                            $error = 'Error uploading thumbnail: ' . $e->getMessage();
                        }
                    }
                } 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" enctype="multipart/form-data" 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-group">
                    <label for="thumbnail">Thumbnail Image</label>
                    <input type="file" id="thumbnail" name="thumbnail" accept="image/*">
                    <small class="form-help">Upload a thumbnail image for this category (optional). Recommended size: 400x300px.</small>
                    <?php if ($edit_category && !empty($edit_category['thumbnail'])): ?>
                        <div class="current-thumbnail">
                            <p><strong>Current thumbnail:</strong></p>
                            <img src="<?php echo htmlspecialchars($edit_category['thumbnail']); ?>" alt="Current thumbnail" class="thumbnail-preview">
                        </div>
                    <?php endif; ?>
                </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" style="padding: 4px 6px; font-size: 12px;" title="Edit">
                                    <i class="fas fa-edit" style="font-size: 14px;"></i>
                                </a>
                                <a href="../category.php?cat=<?php echo urlencode($category['slug']); ?>" 
                                   class="btn btn-sm btn-secondary" target="_blank" style="padding: 4px 6px; font-size: 12px;" title="View">
                                    <i class="fas fa-eye" style="font-size: 14px;"></i>
                                </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?')" style="padding: 4px 6px; font-size: 12px;" title="Delete">
                                        <i class="fas fa-trash" style="font-size: 14px;"></i>
                                    </a>
                                <?php else: ?>
                                    <span class="btn btn-sm btn-disabled" title="Cannot delete category with posts" style="padding: 4px 6px; font-size: 12px;">
                                        <i class="fas fa-trash" style="font-size: 14px;"></i>
                                    </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'; ?>