<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login with edit permission for registrations
requirePermission('registrations', 'edit');

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

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $categoryId = $input['category_id'] ?? null;
    $excludeProductId = $input['exclude_product_id'] ?? null;
    
    if (!$categoryId) {
        throw new Exception('Category ID is required');
    }
    
    $pdo = getDBConnection();
    
    // Get active products in the same category, excluding the current product
    $sql = "
        SELECT id, name, product_code, base_price, description, available_stock
        FROM products 
        WHERE category_id = ? 
        AND is_active = 1 
        AND (sale_start_date IS NULL OR sale_start_date <= NOW()) 
        AND (sale_end_date IS NULL OR sale_end_date >= NOW())
    ";
    
    $params = [$categoryId];
    
    if ($excludeProductId) {
        $sql .= " AND id != ?";
        $params[] = $excludeProductId;
    }
    
    $sql .= " ORDER BY display_order ASC, name ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Filter out products with zero availability (if stock management is enabled)
    $availableProducts = array_filter($products, function($product) {
        return $product['available_stock'] === null || $product['available_stock'] > 0;
    });
    
    echo json_encode([
        'success' => true,
        'products' => array_values($availableProducts),
        'category_id' => $categoryId
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
