<?php
/**
 * Shopify to Mixbox JSON Feed Generator
 *
 * This script fetches products from Shopify 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/shopify-mixbox-feed.php
 */

// Configuration
$config = [
    'shopify_store_url' => 'your-store.myshopify.com', // Your Shopify store URL
    'shopify_api_key' => '', // Your Shopify API key
    'shopify_password' => '', // Your Shopify API password (for private apps)
    'shopify_access_token' => '', // Your Shopify access token (for public apps)
    'limit' => isset($_GET['limit']) ? intval($_GET['limit']) : 10000,
    'cache_time' => 1800, // 30 minutes cache
    'debug' => isset($_GET['debug']) && $_GET['debug'] == '1',
    'include_metafields' => false, // Include product metafields
    'include_variants' => true // Include product variants
];

// 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/shopify_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-Shopify-Feed-Cached: true');
    echo file_get_contents($cache_file);
    exit;
}

try {
    $products = fetchShopifyProducts($config);

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

    $formatted_products = formatShopifyProductsForMixbox($products, $config);

    // 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 Shopify products',
        'message' => $e->getMessage(),
        'config' => $config['debug'] ? $config : null
    ]);
}

/**
 * Fetch products from Shopify API
 */
function fetchShopifyProducts($config) {
    $base_url = "https://{$config['shopify_store_url']}/admin/api/2023-10/products.json";

    // Build query parameters
    $params = [
        'limit' => min($config['limit'], 250), // Shopify API limit is 250
        'fields' => 'id,title,handle,vendor,product_type,variants,images,options,tags,published_at,updated_at,body_html,metafields'
    ];

    if ($config['include_metafields']) {
        $params['fields'] .= ',metafields';
    }

    $url = $base_url . '?' . http_build_query($params);

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

    // Authentication
    if (!empty($config['shopify_access_token'])) {
        // Public app authentication
        $headers[] = 'X-Shopify-Access-Token: ' . $config['shopify_access_token'];
    } elseif (!empty($config['shopify_api_key']) && !empty($config['shopify_password'])) {
        // Private app authentication
        $credentials = base64_encode($config['shopify_api_key'] . ':' . $config['shopify_password']);
        $headers[] = 'Authorization: Basic ' . $credentials;
    } else {
        throw new Exception('Shopify authentication not configured. Please set API key/password or access token.');
    }

    $all_products = [];
    $page_info = null;

    do {
        $current_url = $url;
        if ($page_info) {
            $current_url .= '&page_info=' . urlencode($page_info);
        }

        $response = makeShopifyRequest($current_url, $headers);

        if (!isset($response['products'])) {
            throw new Exception('Invalid response from Shopify API: ' . json_encode($response));
        }

        $all_products = array_merge($all_products, $response['products']);

        // Check for pagination
        $page_info = null;
        if (isset($response['page_info'])) {
            $page_info = $response['page_info'];
        }

        // Limit total products
        if (count($all_products) >= $config['limit']) {
            $all_products = array_slice($all_products, 0, $config['limit']);
            break;
        }

    } while ($page_info && count($all_products) < $config['limit']);

    return $all_products;
}

/**
 * Make HTTP request to Shopify API
 */
function makeShopifyRequest($url, $headers) {
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => implode("\r\n", $headers),
            'timeout' => 30,
            'ignore_errors' => true
        ]
    ]);

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

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

    $data = json_decode($response, true);

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

    return $data;
}

/**
 * Format Shopify products for Mixbox compatibility
 */
function formatShopifyProductsForMixbox($shopify_products, $config) {
    $formatted_products = [];

    foreach ($shopify_products as $product) {
        $formatted_product = formatShopifyProduct($product, $config);
        if ($formatted_product) {
            $formatted_products[$formatted_product['sku']] = $formatted_product;
        }
    }

    return $formatted_products;
}

/**
 * Format a single Shopify product for Mixbox
 */
function formatShopifyProduct($product, $config) {
    // Use the first variant for main product data
    $main_variant = null;
    if (!empty($product['variants'])) {
        $main_variant = $product['variants'][0];
    }

    if (!$main_variant) {
        return null; // Skip products without variants
    }

    $sku = $main_variant['sku'] ?: 'SHOPIFY-' . $product['id'];

    // Handle images
    $images = [];
    if (!empty($product['images'])) {
        foreach ($product['images'] as $image) {
            $images[] = ['src' => $image['src']];
        }
    }

    // Handle categories (Shopify uses product_type and tags)
    $categories_tree = [];
    $breadcrumbs = [];

    if (!empty($product['product_type'])) {
        $categories_tree[] = [
            'id' => crc32($product['product_type']), // Generate consistent ID
            'uuid' => generateUUID(),
            'parent' => 0,
            'name' => $product['product_type'],
            'image' => null,
            'subcategories' => []
        ];
        $breadcrumbs[] = $product['product_type'];
    }

    // Handle tags as additional categories
    if (!empty($product['tags'])) {
        $tags = explode(',', $product['tags']);
        foreach ($tags as $tag) {
            $tag = trim($tag);
            if (!empty($tag)) {
                $categories_tree[] = [
                    'id' => crc32($tag),
                    'uuid' => generateUUID(),
                    'parent' => 0,
                    'name' => $tag,
                    'image' => null,
                    'subcategories' => []
                ];
            }
        }
    }

    // Handle brands (vendor)
    $brands = [];
    if (!empty($product['vendor'])) {
        $brands[] = [
            'name' => $product['vendor'],
            'image' => null
        ];
    }

    // Build final product data
    $formatted_product = [
        'sku' => $sku,
        'name' => $product['title'],
        'qty' => (string)($main_variant['inventory_quantity'] ?? 0),
        'price' => (float)$main_variant['price'],
        'sale_price' => null,
        'last_update_date' => $product['updated_at'],
        'description' => $product['body_html'] ?: '',
        'weight' => $main_variant['weight'] ?? null,
        'images' => $images,
        'permalink' => "https://{$config['shopify_store_url']}/products/" . $product['handle'],
        'categories_tree' => $categories_tree,
        'breadcrumbs' => $breadcrumbs,
        'brands' => $brands
    ];

    // Handle compare_at_price as sale_price
    if (!empty($main_variant['compare_at_price']) && $main_variant['compare_at_price'] > $main_variant['price']) {
        $formatted_product['sale_price'] = (float)$main_variant['price'];
        $formatted_product['price'] = (float)$main_variant['compare_at_price'];
    }

    // Handle variants if enabled
    if ($config['include_variants'] && count($product['variants']) > 1) {
        // For now, we'll use the main variant data
        // You could extend this to create separate products for each variant
    }

    return $formatted_product;
}

/**
 * Generate UUID
 */
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)
    );
}
?>