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

// Handle Add Subcategory
if (isset($_POST['add_subcategory'])) {
    $category_id = (int)$_POST['category_id'];
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    $status = $_POST['status'];
    
    if (!empty($name) && $category_id > 0) {
        try {
            $stmt = $pdo->prepare("INSERT INTO portfolio_subcategories (category_id, name, slug, status) VALUES (?, ?, ?, ?)");
            $stmt->execute([$category_id, $name, $slug, $status]);
            $success = "Subcategory added successfully.";
        } catch (PDOException $e) {
            $error = "Error adding subcategory. Slug might already exist.";
        }
    } else {
        $error = "Name and Parent Category are required.";
    }
}

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

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

// Fetch all categories for the dropdown
$cat_stmt = $pdo->query("SELECT id, name FROM portfolio_categories WHERE status = 'active' ORDER BY name ASC");
$active_categories = $cat_stmt->fetchAll();

// Fetch all subcategories with their parent category name
$stmt = $pdo->query("
    SELECT s.*, c.name as category_name 
    FROM portfolio_subcategories s
    LEFT JOIN portfolio_categories c ON s.category_id = c.id
    ORDER BY s.created_at DESC
");
$subcategories = $stmt->fetchAll();

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

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-layer-group"></i> Portfolio Subcategories</h2>
        <p>Manage nested subcategories to further organize your projects.</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_sub ? 'Edit Subcategory' : 'Add Subcategory' ?></h3>
            <form action="portfolio_subcategories.php" method="POST" style="margin-top: 15px;">
                <?php if ($edit_sub): ?>
                    <input type="hidden" name="id" value="<?= $edit_sub['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;">Parent Category</label>
                    <select name="category_id" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="">-- Select Parent Category --</option>
                        <?php foreach($active_categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= ($edit_sub && $edit_sub['category_id'] == $cat['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Subcategory Name</label>
                    <input type="text" name="name" required value="<?= $edit_sub ? htmlspecialchars($edit_sub['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_sub && $edit_sub['status'] == 'active') ? 'selected' : '' ?>>Active</option>
                        <option value="inactive" <?= ($edit_sub && $edit_sub['status'] == 'inactive') ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
                
                <?php if ($edit_sub): ?>
                    <button type="submit" name="update_subcategory" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Update Subcategory</button>
                    <a href="portfolio_subcategories.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_subcategory" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Add Subcategory</button>
                <?php endif; ?>
            </form>
        </div>

        <!-- Subcategories List -->
        <div class="recent-activity">
            <h3>Existing Subcategories</h3>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Parent Category</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($subcategories) > 0): ?>
                            <?php foreach ($subcategories as $sub): ?>
                                <tr>
                                    <td style="font-weight:600;"><?= htmlspecialchars($sub['name']) ?></td>
                                    <td style="color:#64748b;"><?= htmlspecialchars($sub['category_name']) ?></td>
                                    <td>
                                        <?php if($sub['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_subcategories.php?edit=<?= $sub['id'] ?>" style="color:var(--primary); margin-right:10px;"><i class="fa-solid fa-pen-to-square"></i></a>
                                        <a href="portfolio_subcategories.php?delete=<?= $sub['id'] ?>" onclick="return confirm('Are you sure you want to delete this subcategory? Portfolio items attached to it will not be deleted, but unlinked.');" 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 subcategories found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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