<?php
/**
 * Category Actions Handler for AJAX
 * File: admin/category-actions.php
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

header('Content-Type: application/json');

try {
    $action = $_POST['action'] ?? '';
    
    $db = Database::getInstance();
    $category_model = new Category();
    
    switch ($action) {
        case 'create':
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $icon = trim($_POST['icon'] ?? '');
            $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
            $commission_percentage = !empty($_POST['commission_percentage']) ? floatval($_POST['commission_percentage']) : 10.00;
            $level = $_POST['level'] ?? 'medium';
            
            if (empty($name)) {
                echo json_encode(['success' => false, 'message' => 'Category name is required']);
                exit;
            }
            
            $slug = create_slug($name);
            
            $result = $category_model->create([
                'name' => $name,
                'slug' => $slug,
                'description' => $description,
                'icon' => $icon,
                'parent_id' => $parent_id,
                'commission_percentage' => $commission_percentage,
                'level' => $level,
                'status' => 'active'
            ]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Category created successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to create category']);
            }
            break;
            
        case 'update':
            $id = (int)$_POST['id'];
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $icon = trim($_POST['icon'] ?? '');
            $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
            $status = $_POST['status'] ?? 'active';
            $display_order = (int)($_POST['display_order'] ?? 0);
            $commission_percentage = !empty($_POST['commission_percentage']) ? floatval($_POST['commission_percentage']) : 10.00;
            $level = $_POST['level'] ?? 'medium';
            
            if (empty($name)) {
                echo json_encode(['success' => false, 'message' => 'Category name is required']);
                exit;
            }
            
            $result = $category_model->update($id, [
                'name' => $name,
                'description' => $description,
                'icon' => $icon,
                'parent_id' => $parent_id,
                'status' => $status,
                'display_order' => $display_order,
                'commission_percentage' => $commission_percentage,
                'level' => $level
            ]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Category updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update category']);
            }
            break;
            
        case 'delete':
            $id = (int)$_POST['id'];
            
            // Check if category has items
            $check_sql = "SELECT COUNT(*) as count FROM items WHERE category_id = ?";
            $result = $db->fetch($check_sql, [$id]);
            
            if ($result['count'] > 0) {
                echo json_encode(['success' => false, 'message' => 'Cannot delete category with existing items']);
                exit;
            }
            
            $result = $category_model->delete($id);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Category deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete category']);
            }
            break;
            
        case 'toggle_status':
            $id = (int)$_POST['id'];
            $status = $_POST['status'] ?? 'active';
            
            $result = $category_model->updateStatus($id, $status);
            
            if ($result) {
                $action_text = $status === 'active' ? 'activated' : 'deactivated';
                echo json_encode(['success' => true, 'message' => "Category {$action_text} successfully"]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update category status']);
            }
            break;
            
        case 'update_order':
            $id = (int)$_POST['id'];
            $display_order = (int)$_POST['display_order'];
            
            $result = $category_model->update($id, ['display_order' => $display_order]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Order updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update order']);
            }
            break;
            
        case 'bulk_action':
            $selected_categories = $_POST['selected_categories'] ?? [];
            $bulk_action = $_POST['bulk_action'] ?? '';
            
            if (!empty($selected_categories) && !empty($bulk_action)) {
                try {
                    $success_count = 0;
                    $error_count = 0;
                    
                    switch ($bulk_action) {
                        case 'activate':
                            foreach ($selected_categories as $cat_id) {
                                if ($category_model->updateStatus((int)$cat_id, 'active')) {
                                    $success_count++;
                                } else {
                                    $error_count++;
                                }
                            }
                            break;
                            
                        case 'deactivate':
                            foreach ($selected_categories as $cat_id) {
                                if ($category_model->updateStatus((int)$cat_id, 'inactive')) {
                                    $success_count++;
                                } else {
                                    $error_count++;
                                }
                            }
                            break;
                            
                        case 'delete':
                            foreach ($selected_categories as $cat_id) {
                                // Check for items before deletion
                                $check_sql = "SELECT COUNT(*) as count FROM items WHERE category_id = ?";
                                $result = $db->fetch($check_sql, [(int)$cat_id]);
                                if ($result['count'] == 0) {
                                    if ($category_model->delete((int)$cat_id)) {
                                        $success_count++;
                                    } else {
                                        $error_count++;
                                    }
                                } else {
                                    $error_count++;
                                }
                            }
                            break;
                    }
                    
                    $message = "Bulk action completed. {$success_count} successful, {$error_count} failed.";
                    echo json_encode(['success' => true, 'message' => $message]);
                } catch (Exception $e) {
                    echo json_encode(['success' => false, 'message' => 'Error processing bulk action: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'No categories selected or invalid action']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

function create_slug($string, $separator = '-')
{
    $string = strtolower(trim($string));
    $string = preg_replace('/[^a-z0-9]+/', $separator, $string);
    $string = trim($string, $separator);
    $string = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $string);
    if (empty($string)) {
        return 'category' . $separator . uniqid();
    }    
    return $string;
}
?>