<?php
require_once 'config/db.php';
require_once 'includes/header.php';

// Handle Add Category
if (isset($_POST['add_category'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    $status = $_POST['status'];
    
    if (!empty($name)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO portfolio_categories (name, slug, status) VALUES (?, ?, ?)");
            $stmt->execute([$name, $slug, $status]);
            $success = "Category added successfully.";
        } catch (PDOException $e) {
            $error = "Error adding category. Slug might already exist.";
        }
    } else {
        $error = "Category name cannot be empty.";
    }
}

// Handle Delete Category
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM portfolio_categories WHERE id = ?");
        $stmt->execute([$id]);
        $success = "Category deleted successfully.";
    } catch (PDOException $e) {
        $error = "Error deleting category: " . $e->getMessage();
    }
}

// Handle Update Category
if (isset($_POST['update_category'])) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    $status = $_POST['status'];
    
    if (!empty($name)) {
        try {
            $stmt = $pdo->prepare("UPDATE portfolio_categories SET name=?, slug=?, status=? WHERE id=?");
            $stmt->execute([$name, $slug, $status, $id]);
            $success = "Category updated successfully.";
        } catch (PDOException $e) {
            $error = "Error updating category.";
        }
    }
}

// Fetch all categories
$stmt = $pdo->query("SELECT * FROM portfolio_categories ORDER BY created_at DESC");
$categories = $stmt->fetchAll();

// Edit Mode Check
$edit_category = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM portfolio_categories WHERE id = ?");
    $stmt->execute([$id]);
    $edit_category = $stmt->fetch();
}
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-folder-tree"></i> Portfolio Categories</h2>
        <p>Manage the top-level categories for your portfolio items.</p>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="about-grid" style="align-items: start;">
        <!-- Add / Edit Form -->
        <div class="recent-activity">
            <h3><?= $edit_category ? 'Edit Category' : 'Add New Category' ?></h3>
            <form action="portfolio_categories.php" method="POST" style="margin-top: 15px;">
                <?php if ($edit_category): ?>
                    <input type="hidden" name="id" value="<?= $edit_category['id'] ?>">
                <?php endif; ?>
                
                <div style="margin-bottom: 15px;">
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Category Name</label>
                    <input type="text" name="name" required value="<?= $edit_category ? htmlspecialchars($edit_category['name']) : '' ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Status</label>
                    <select name="status" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="active" <?= ($edit_category && $edit_category['status'] == 'active') ? 'selected' : '' ?>>Active</option>
                        <option value="inactive" <?= ($edit_category && $edit_category['status'] == 'inactive') ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
                
                <?php if ($edit_category): ?>
                    <button type="submit" name="update_category" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Update Category</button>
                    <a href="portfolio_categories.php" style="display:block; text-align:center; margin-top:10px; color:var(--text); text-decoration:none; font-size:0.9rem;">Cancel</a>
                <?php else: ?>
                    <button type="submit" name="add_category" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Add Category</button>
                <?php endif; ?>
            </form>
        </div>

        <!-- Categories List -->
        <div class="recent-activity">
            <h3>Existing Categories</h3>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Slug</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($categories) > 0): ?>
                            <?php foreach ($categories as $cat): ?>
                                <tr>
                                    <td style="font-weight:600;"><?= htmlspecialchars($cat['name']) ?></td>
                                    <td style="color:#94a3b8; font-size:0.85rem;"><?= htmlspecialchars($cat['slug']) ?></td>
                                    <td>
                                        <?php if($cat['status'] == 'active'): ?>
                                            <span class="badge badge-completed">Active</span>
                                        <?php else: ?>
                                            <span class="badge badge-pending">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="portfolio_categories.php?edit=<?= $cat['id'] ?>" style="color:var(--primary); margin-right:10px;"><i class="fa-solid fa-pen-to-square"></i></a>
                                        <a href="portfolio_categories.php?delete=<?= $cat['id'] ?>" onclick="return confirm('Are you sure you want to delete this category? This will also delete all subcategories and unlink items associated with it.');" style="color:var(--danger);"><i class="fa-solid fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: #94a3b8;">No categories found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
