<?php
/**
 * Product API for attached products functionality
 * XChange 2025 Registration System
 */

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

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

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

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'get_attached_products':
            $productId = intval($_GET['product_id'] ?? 0);
            
            if (!$productId) {
                throw new Exception('Product ID is required');
            }
            
            $sql = "SELECT pa.*, p.name as product_name, p.product_code, p.base_price, pc.name as category_name
                    FROM product_attachments pa
                    JOIN products p ON pa.attached_product_id = p.id
                    LEFT JOIN product_categories pc ON p.category_id = pc.id
                    WHERE pa.parent_product_id = ? AND pa.is_active = 1
                    ORDER BY pa.display_order, p.name";
            
            $stmt = $conn->prepare($sql);
            $stmt->execute([$productId]);
            $attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'attachments' => $attachments
            ]);
            break;
            
        case 'get_available_products':
            $excludeId = intval($_GET['exclude_id'] ?? 0);
            
            $sql = "SELECT id, name, product_code, base_price, category_id
                    FROM products 
                    WHERE is_active = 1";
            
            $params = [];
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $sql .= " ORDER BY name";
            
            $stmt = $conn->prepare($sql);
            $stmt->execute($params);
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'products' => $products
            ]);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
