<?php
// admin/categories.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Check for session messages
$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

// Get all categories
$stmt = $pdo->query("SELECT c.*, 
                     (SELECT COUNT(*) FROM subcategories WHERE category_id = c.id) as sub_count,
                     (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count
                     FROM categories c 
                     ORDER BY c.created_at DESC");
$categories = $stmt->fetchAll();

include 'header.php';
?>

<div class="admin-card">
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="card-title">Categories (<?php echo count($categories); ?>)</h5>
        <a href="add-category.php" class="btn btn-primary">
            <i class="fa-solid fa-plus"></i> Add Category
        </a>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert" id="successAlert">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert" id="errorAlert">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <div class="table-responsive mt-3">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Slug</th>
                    <th>Subcategories</th>
                    <th>Products</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="categoriesTableBody">
                <?php if (empty($categories)): ?>
                <tr id="noDataRow"><td colspan="8" class="text-center">No categories found</td></tr>
                <?php else: ?>
                <?php foreach ($categories as $cat): ?>
                <tr id="categoryRow_<?php echo $cat['id']; ?>">
                    <td><?php echo $cat['id']; ?></td>
                    <td>
                        <?php if ($cat['image']): ?>
                        <img src="../assets/images/categories/<?php echo $cat['image']; ?>" 
                             alt="<?php echo $cat['name']; ?>" 
                             style="width:50px; height:50px; object-fit:cover; border-radius:8px;">
                        <?php else: ?>
                        <span class="text-muted">No image</span>
                        <?php endif; ?>
                    </td>
                    <td><strong><?php echo $cat['name']; ?></strong></td>
                    <td><code><?php echo $cat['slug']; ?></code></td>
                    <td><span class="badge bg-info"><?php echo $cat['sub_count']; ?></span></td>
                    <td><span class="badge bg-primary"><?php echo $cat['product_count']; ?></span></td>
                    <td>
                        <span class="badge bg-<?php echo $cat['status'] ? 'success' : 'danger'; ?>">
                            <?php echo $cat['status'] ? 'Active' : 'Inactive'; ?>
                        </span>
                    </td>
                    <td>
                        <a href="edit-category.php?id=<?php echo $cat['id']; ?>" class="btn btn-sm btn-warning">
                            <i class="fa-solid fa-edit"></i>
                        </a>
                        <button onclick="deleteCategory(<?php echo $cat['id']; ?>, '<?php echo addslashes($cat['name']); ?>')" class="btn btn-sm btn-danger">
                            <i class="fa-solid fa-trash"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this category?</p>
                <p class="text-danger"><strong>Warning:</strong> This will also delete all subcategories and products under this category.</p>
                <p><strong>Category:</strong> <span id="deleteCategoryName"></span></p>
                <input type="hidden" id="delete_category_id">
            </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" id="confirmDeleteBtn">Delete Permanently</button>
            </div>
        </div>
    </div>
</div>

<script>
function deleteCategory(id, name) {
    document.getElementById('delete_category_id').value = id;
    document.getElementById('deleteCategoryName').textContent = name;
    var modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}

// Handle delete confirmation with AJAX
document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    var id = document.getElementById('delete_category_id').value;
    var btn = this;
    var originalText = btn.innerHTML;
    
    // Disable button and show loading
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Deleting...';
    
    // Create form data
    var formData = new FormData();
    formData.append('id', id);
    
    // Send AJAX request
    fetch('delete-category-ajax.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        // Check if response is OK
        if (!response.ok) {
            throw new Error('Network response was not ok: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        // Close modal
        var modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
        modal.hide();
        
        if (data.success) {
            // Remove the row from table
            var row = document.getElementById('categoryRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    // Check if no rows left
                    var tbody = document.getElementById('categoriesTableBody');
                    if (tbody.children.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="8" class="text-center">No categories found</td></tr>';
                    }
                }, 500);
            }
            
            // Show success message
            showAlert('success', data.name ? 'Category "' + data.name + '" deleted successfully!' : 'Category deleted successfully!');
        } else {
            showAlert('danger', data.message || 'Failed to delete category');
        }
        
        // Reset button
        btn.disabled = false;
        btn.innerHTML = originalText;
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong. Please try again.');
        
        // Reset button
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
});

// Function to show alert
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    var alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show mt-3" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    alertContainer.innerHTML = alertHtml;
    
    // Auto dismiss after 5 seconds
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() {
                alert.remove();
            }, 500);
        }
    }, 5000);
}

// Auto hide session alerts after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            }
        }, 5000);
    });
});
</script>

<?php include 'footer.php'; ?>