<?php
/**
 * GOMAG to Mixbox JSON Feed Generator
 *
 * This script fetches products from GOMAG API and converts them
 * to the JSON format compatible with Mixbox JsonImportController
 *
 * Usage: Place this file in your web root and access via:
 * https://your-site.com/gomag-mixbox-feed.php
 */

// Configuration
$config = [
    'gomag_api_url' => 'https://api.gomag.ro/v1/products', // Replace with actual GOMAG API URL
    'gomag_api_key' => '', // Your GOMAG API key
    'limit' => isset($_GET['limit']) ? intval($_GET['limit']) : 10000,
    'cache_time' => 1800, // 30 minutes cache
    'debug' => isset($_GET['debug']) && $_GET['debug'] == '1'
];

// Set headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header("Cache-Control: max-age={$config['cache_time']}");

// Check cache
$cache_file = __DIR__ . '/cache/gomag_feed_cache.json';
$cache_dir = dirname($cache_file);

if (!is_dir($cache_dir)) {
    mkdir($cache_dir, 0755, true);
}

if (file_exists($cache_file) && (time() - filemtime($cache_file) < $config['cache_time'])) {
    header('X-Gomag-Feed-Cached: true');
    echo file_get_contents($cache_file);
    exit;
}

try {
    $products = fetchGomagProducts($config);

    if ($config['debug']) {
        // Debug mode - return raw API response
        echo json_encode([
            'debug' => true,
            'api_response' => $products,
            'config' => $config
        ], JSON_PRETTY_PRINT);
        exit;
    }

    $formatted_products = formatProductsForMixbox($products);

    // Cache the result
    file_put_contents($cache_file, json_encode($formatted_products, JSON_PRETTY_PRINT));

    echo json_encode($formatted_products, JSON_PRETTY_PRINT);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to fetch GOMAG products',
        'message' => $e->getMessage(),
        'config' => $config['debug'] ? $config : null
    ]);
}

/**
 * Fetch products from GOMAG API
 */
function fetchGomagProducts($config) {
    $url = $config['gomag_api_url'] . '?limit=' . $config['limit'];

    $headers = [
        'Content-Type: application/json'
    ];

    if (!empty($config['gomag_api_key'])) {
        $headers[] = 'Authorization: Bearer ' . $config['gomag_api_key'];
    }

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => implode("\r\n", $headers),
            'timeout' => 30
        ]
    ]);

    $response = file_get_contents($url, false, $context);

    if ($response === false) {
        throw new Exception('Failed to connect to GOMAG API');
    }

    $data = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON response from GOMAG API: ' . json_last_error_msg());
    }

    return $data;
}

/**
 * Alternative method: Fetch from GOMAG's product export URL
 */
function fetchGomagProductsAlternative($config) {
    // Some GOMAG installations might have direct export URLs
    $export_urls = [
        'https://your-store.gomag.ro/export/products/json',
        'https://your-store.gomag.ro/api/products/export',
        'https://api.gomag.ro/v1/your-store/products'
    ];

    foreach ($export_urls as $url) {
        try {
            $context = stream_context_create([
                'http' => [
                    'method' => 'GET',
                    'timeout' => 10
                ]
            ]);

            $response = file_get_contents($url, false, $context);

            if ($response !== false) {
                $data = json_decode($response, true);
                if (json_last_error() === JSON_ERROR_NONE && !empty($data)) {
                    return $data;
                }
            }
        } catch (Exception $e) {
            continue;
        }
    }

    throw new Exception('Could not fetch products from any GOMAG export URL');
}

/**
 * Format GOMAG products for Mixbox compatibility
 */
function formatProductsForMixbox($gomag_data) {
    $formatted_products = [];

    // Handle different GOMAG response formats
    $products = [];

    if (isset($gomag_data['products'])) {
        $products = $gomag_data['products'];
    } elseif (isset($gomag_data['data'])) {
        $products = $gomag_data['data'];
    } elseif (is_array($gomag_data) && !empty($gomag_data)) {
        $products = $gomag_data;
    }

    foreach ($products as $product) {
        $formatted_product = formatSingleProduct($product);
        if ($formatted_product) {
            $formatted_products[$formatted_product['sku']] = $formatted_product;
        }
    }

    return $formatted_products;
}

/**
 * Format a single GOMAG product for Mixbox
 */
function formatSingleProduct($product) {
    // Extract basic product info
    $sku = $product['sku'] ?? $product['code'] ?? $product['id'] ?? null;
    if (!$sku) {
        return null; // Skip products without SKU
    }

    $name = $product['name'] ?? $product['title'] ?? '';
    $description = $product['description'] ?? $product['content'] ?? '';
    $price = (float)($product['price'] ?? $product['selling_price'] ?? 0);
    $quantity = (int)($product['stock'] ?? $product['quantity'] ?? 0);
    $weight = $product['weight'] ?? null;

    // Handle images
    $images = [];
    if (isset($product['images']) && is_array($product['images'])) {
        foreach ($product['images'] as $image) {
            if (is_string($image)) {
                $images[] = ['src' => $image];
            } elseif (isset($image['url'])) {
                $images[] = ['src' => $image['url']];
            }
        }
    } elseif (isset($product['image'])) {
        $images[] = ['src' => $product['image']];
    }

    // Handle categories
    $categories_tree = [];
    $breadcrumbs = [];

    if (isset($product['categories']) && is_array($product['categories'])) {
        foreach ($product['categories'] as $category) {
            $cat_data = [
                'id' => $category['id'] ?? rand(1000, 9999),
                'uuid' => generateUUID(),
                'parent' => $category['parent_id'] ?? 0,
                'name' => $category['name'] ?? $category['title'] ?? '',
                'image' => $category['image'] ?? null,
                'subcategories' => []
            ];
            $categories_tree[] = $cat_data;

            if (isset($category['path'])) {
                $breadcrumbs[] = $category['path'];
            } else {
                $breadcrumbs[] = $cat_data['name'];
            }
        }
    }

    // Handle brands
    $brands = [];
    if (isset($product['brand'])) {
        $brands[] = [
            'name' => $product['brand']['name'] ?? $product['brand'],
            'image' => $product['brand']['image'] ?? null
        ];
    } elseif (isset($product['manufacturer'])) {
        $brands[] = [
            'name' => $product['manufacturer'],
            'image' => null
        ];
    }

    // Build final product data
    $formatted_product = [
        'sku' => $sku,
        'name' => $name,
        'qty' => (string)$quantity,
        'price' => $price,
        'sale_price' => null, // Will be set if there's a special price
        'last_update_date' => $product['updated_at'] ?? $product['modified'] ?? date('Y-m-d H:i:s'),
        'description' => $description,
        'weight' => $weight,
        'images' => $images,
        'permalink' => $product['url'] ?? $product['link'] ?? '',
        'categories_tree' => $categories_tree,
        'breadcrumbs' => $breadcrumbs,
        'brands' => $brands
    ];

    // Handle special/sale prices
    if (isset($product['special_price']) && $product['special_price'] > 0) {
        $formatted_product['sale_price'] = (float)$product['special_price'];
    } elseif (isset($product['discount_price']) && $product['discount_price'] > 0) {
        $formatted_product['sale_price'] = (float)$product['discount_price'];
    }

    return $formatted_product;
}

/**
 * Generate UUID for categories
 */
function generateUUID() {
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff)
    );
}
?>