<?php
require_once '../config.php';

$conn = get_db_connection();
$message = '';
$message_type = '';

// Helper function to create slug from name
if (!function_exists('create_slug')) {
    function create_slug($name)
    {
        $slug = strtolower(trim($name));
        $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
        $slug = preg_replace('/-+/', '-', $slug);
        return trim($slug, '-');
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $display_order = intval($_POST['display_order'] ?? 0);

            if (empty($name)) {
                $message = 'Category name is required!';
                $message_type = 'danger';
            } else {
                $slug = create_slug($name);

                if ($_POST['action'] === 'add') {
                    $stmt = $conn->prepare("INSERT INTO service_categories (name, slug, description, display_order) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("sssi", $name, $slug, $description, $display_order);
                    if ($stmt->execute()) {
                        $message = 'Category added successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error adding category: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                } else {
                    $id = intval($_POST['id']);
                    $stmt = $conn->prepare("UPDATE service_categories SET name = ?, slug = ?, description = ?, display_order = ? WHERE id = ?");
                    $stmt->bind_param("sssii", $name, $slug, $description, $display_order, $id);
                    if ($stmt->execute()) {
                        $message = 'Category updated successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating category: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = intval($_POST['id']);

            // Check if category is being used
            $check_stmt = $conn->prepare("SELECT COUNT(*) as count FROM services WHERE category_id = ?");
            $check_stmt->bind_param("i", $id);
            $check_stmt->execute();
            $result = $check_stmt->get_result();
            $row = $result->fetch_assoc();
            $check_stmt->close();

            if ($row['count'] > 0) {
                $message = 'Cannot delete category: It is being used by ' . $row['count'] . ' service(s).';
                $message_type = 'danger';
            } else {
                $stmt = $conn->prepare("DELETE FROM service_categories WHERE id = ?");
                $stmt->bind_param("i", $id);
                if ($stmt->execute()) {
                    $message = 'Category deleted successfully!';
                    $message_type = 'success';
                } else {
                    $message = 'Error deleting category: ' . $stmt->error;
                    $message_type = 'danger';
                }
                $stmt->close();
            }
        }
    }
}

// Get all categories
$categories_result = $conn->query("SELECT c.*, COUNT(s.id) as service_count 
    FROM service_categories c 
    LEFT JOIN services s ON c.id = s.category_id 
    GROUP BY c.id 
    ORDER BY c.display_order ASC, c.id ASC");
$categories = [];
if ($categories_result) {
    while ($row = $categories_result->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Get category for editing
$edit_category = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM service_categories WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        $edit_category = $row;
    }
    $stmt->close();
}

$page_title = 'Service Categories';
require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $edit_category ? 'Edit Category' : 'Add New Category'; ?></h2>
        <?php if ($edit_category): ?>
            <a href="service-categories" class="btn btn-secondary btn-sm">Cancel</a>
        <?php endif; ?>
    </div>

    <form method="POST" action="">
        <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-row">
            <div class="form-group">
                <label for="name">Category Name *</label>
                <input type="text" id="name" name="name" class="form-control" required
                    value="<?php echo htmlspecialchars($edit_category['name'] ?? ''); ?>"
                    placeholder="e.g. Chimney Services">
            </div>

            <div class="form-group">
                <label for="display_order">Display Order</label>
                <input type="number" id="display_order" name="display_order" class="form-control"
                    value="<?php echo $edit_category['display_order'] ?? count($categories) + 1; ?>" min="0">
            </div>
        </div>

        <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" name="description" class="form-control" style="min-height: 100px;"
                placeholder="Optional description..."><?php echo htmlspecialchars($edit_category['description'] ?? ''); ?></textarea>
        </div>

        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> <?php echo $edit_category ? 'Update Category' : 'Add Category'; ?>
        </button>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">All Categories (<?php echo count($categories); ?>)</h2>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Category Name</th>
                    <th>Slug</th>
                    <th>Services</th>
                    <th>Order</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($categories)): ?>
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 40px; color: var(--text-muted);">No categories
                            found. Add your first category above.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($categories as $category): ?>
                        <tr>
                            <td>
                                <div style="font-weight: 700;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <div style="font-size: 12px; color: var(--text-muted);">
                                    <?php echo htmlspecialchars(substr($category['description'], 0, 50)) . (strlen($category['description']) > 50 ? '...' : ''); ?>
                                </div>
                            </td>
                            <td><code><?php echo htmlspecialchars($category['slug']); ?></code></td>
                            <td>
                                <span
                                    class="badge <?php echo $category['service_count'] > 0 ? 'badge-success' : 'badge-warning'; ?>">
                                    <?php echo $category['service_count']; ?> Services
                                </span>
                            </td>
                            <td><?php echo $category['display_order']; ?></td>
                            <td>
                                <div style="display: flex; gap: 8px;">
                                    <a href="?edit=<?php echo $category['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure you want to delete this category?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" <?php echo $category['service_count'] > 0 ? 'disabled title="Cannot delete category with services"' : ''; ?>>
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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