<?php
include 'layout.php';
include 'db.php';
include 'auth.php';
require_right('View Categories');

// Handle Add Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_category_name'])) {
    $stmt = $conn->prepare("INSERT INTO categories (name) VALUES (?)");
    $stmt->bind_param("s", $_POST['new_category_name']);
    $stmt->execute();
    header("Location: category_list.php");
    exit;
}

// Handle Add Sub Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_sub_category_name'])) {
    $stmt = $conn->prepare("INSERT INTO sub_categories (category_id, name) VALUES (?, ?)");
    $stmt->bind_param("is", $_POST['new_sub_category_category_id'], $_POST['new_sub_category_name']);
    $stmt->execute();
    header("Location: category_list.php");
    exit;
}

// Fetch all categories with their sub-categories
$query = "
    SELECT 
        c.id AS category_id,
        c.name AS category_name
    FROM categories c
    ORDER BY c.name ASC
";

// Fetch sub-categories separately
$sub_categories_query = "
    SELECT 
        sc.id AS sub_category_id,
        sc.name AS sub_category_name,
        sc.category_id,
        c.name AS category_name
    FROM sub_categories sc
    JOIN categories c ON sc.category_id = c.id
    ORDER BY c.name, sc.name
";

$result = $conn->query($query);
$catOptions = $conn->query("SELECT id, name FROM categories");

// Get all sub-categories for display
$sub_result = $conn->query($sub_categories_query);
$sub_categories = [];
while ($sub = $sub_result->fetch_assoc()) {
    $sub_categories[$sub['category_id']][] = $sub;
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>📂 Category Management</h4>
                <h6>Organize your products with categories and sub-categories</h6>
            </div>
            <div class="page-btn">
                <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                    <i class="fa fa-plus"></i> Add Category
                </button>
                <button class="btn btn-secondary me-2" data-bs-toggle="modal" data-bs-target="#addSubCategoryModal">
                    <i class="fa fa-plus"></i> Add Sub Category
                </button>
                <a href="sub_category_list.php" class="btn btn-info">
                    <i class="fa fa-list"></i> Manage Sub-Categories
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fa fa-folder"></i> Categories & Sub-Categories</h5>
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Category Name</th>
                            <th>Sub-Categories</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        while ($row = $result->fetch_assoc()): 
                            $has_sub_categories = isset($sub_categories[$row['category_id']]) && count($sub_categories[$row['category_id']]) > 0;
                        ?>
                        <tr>
                            <td>
                                <span class="badge bg-primary"><?= $row['category_id'] ?></span>
                            </td>
                            <td>
                                <strong><?= htmlspecialchars($row['category_name']) ?></strong>
                            </td>
                            <td>
                                <?php if ($has_sub_categories): ?>
                                    <?php foreach ($sub_categories[$row['category_id']] as $sub): ?>
                                        <div class="d-flex align-items-center mb-1">
                                            <span class="badge bg-secondary me-2"><?= $sub['sub_category_id'] ?></span>
                                            <span><?= htmlspecialchars($sub['sub_category_name']) ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <span class="text-muted">No sub-categories</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-warning" onclick="editCategory(<?= $row['category_id'] ?>, '<?= htmlspecialchars($row['category_name']) ?>')">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteCategory(<?= $row['category_id'] ?>, '<?= htmlspecialchars($row['category_name']) ?>')">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="category_list.php" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-plus"></i> Add New Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="new_category_name" class="form-label">Category Name</label>
                    <input type="text" id="new_category_name" name="new_category_name" placeholder="Enter category name" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> Save Category
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Add Sub Category Modal -->
<div class="modal fade" id="addSubCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="category_list.php" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-plus"></i> Add New Sub-Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="form-group mb-3">
                    <label for="new_sub_category_category_id" class="form-label">Parent Category</label>
                    <select id="new_sub_category_category_id" name="new_sub_category_category_id" class="form-select" required>
                        <option value="">Select a category</option>
                        <?php 
                        $catOptions->data_seek(0);
                        while ($cat = $catOptions->fetch_assoc()): 
                        ?>
                            <option value="<?= $cat['id'] ?>"><?= $cat['name'] ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="new_sub_category_name" class="form-label">Sub-Category Name</label>
                    <input type="text" id="new_sub_category_name" name="new_sub_category_name" placeholder="Enter sub-category name" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> Save Sub-Category
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-edit"></i> Edit Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editCategoryForm">
                    <input type="hidden" id="editCategoryId" name="category_id">
                    <div class="form-group">
                        <label for="editCategoryName" class="form-label">Category Name</label>
                        <input type="text" id="editCategoryName" name="category_name" class="form-control" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveCategoryEdit()">
                    <i class="fa fa-save"></i> Update
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Category Modal -->
<div class="modal fade" id="deleteCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-exclamation-triangle text-danger"></i> Delete Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete the category "<strong id="deleteCategoryName"></strong>"?</p>
                <div class="alert alert-warning">
                    <i class="fa fa-info-circle"></i> <strong>Warning:</strong> This will also delete all sub-categories under this category.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" onclick="confirmDeleteCategory()">
                    <i class="fa fa-trash"></i> Delete
                </button>
            </div>
        </div>
    </div>
</div>





<script>
let currentCategoryId = null;

function editCategory(categoryId, categoryName) {
    document.getElementById('editCategoryId').value = categoryId;
    document.getElementById('editCategoryName').value = categoryName;
    new bootstrap.Modal(document.getElementById('editCategoryModal')).show();
}

function saveCategoryEdit() {
    const formData = new FormData(document.getElementById('editCategoryForm'));
    fetch('ajax_edit_category.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    });
}

function deleteCategory(categoryId, categoryName) {
    currentCategoryId = categoryId;
    document.getElementById('deleteCategoryName').textContent = categoryName;
    new bootstrap.Modal(document.getElementById('deleteCategoryModal')).show();
}

function confirmDeleteCategory() {
    if (!currentCategoryId) return;
    
    fetch(`ajax_delete_category.php?category_id=${currentCategoryId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    });
}
</script>
