<?php

// Magento API credentials
$apiUrl = "https://maisonpink.me/rest/V1/products?searchCriteria[pageSize]=100";
$accessToken = "bjp8sm7ivq7crliycer45wvt9omyeop1"; // Replace with your actual token

// Set file path
$filePath = "/home/webinprogress/public_html/tiktok /tiktok_catalog_products.csv";

// Open file for writing
$output = fopen($filePath, 'w');
if (!$output) {
    die("Failed to open file for writing");
}

// Add CSV headers as per TikTok catalog requirements
fputcsv($output, ['sku_id', 'title', 'description', 'availability', 'condition', 'price', 'link', 'image_link', 'brand', 'category']);

// Base URL for media images
$baseMediaUrl = "https://maisonpink.me/media/catalog/product";

// Cache for category information to avoid repeated API calls
$categoryCache = [];

// Function to get category name from Magento API
function getCategoryName($categoryId) {
    global $accessToken, $categoryCache;
    
    // Check if category is already in cache
    if (isset($categoryCache[$categoryId])) {
        return $categoryCache[$categoryId];
    }
    
    // Magento API endpoint for category
    $categoryApiUrl = "https://maisonpink.me/rest/V1/categories/{$categoryId}";
    
    // Fetch category data using cURL
    $ch = curl_init($categoryApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken"
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // Handle HTTP errors
    if ($httpCode !== 200) {
        error_log("Error fetching category data: HTTP $httpCode for category ID $categoryId");
        return '';
    }
    
    // Decode JSON response
    $categoryData = json_decode($response, true);
    
    // Check for valid data
    if (!isset($categoryData['name'])) {
        error_log("Invalid category data for ID $categoryId");
        return '';
    }
    
    // Store in cache
    $categoryCache[$categoryId] = $categoryData['name'];
    
    return $categoryData['name'];
}

// Function to get full category path
function getCategoryPath($categoryId) {
    global $accessToken, $categoryCache;
    
    // Check if we already have the full path cached
    $cacheKey = "path_" . $categoryId;
    if (isset($categoryCache[$cacheKey])) {
        return $categoryCache[$cacheKey];
    }
    
    // Magento API endpoint for category
    $categoryApiUrl = "https://maisonpink.me/rest/V1/categories/{$categoryId}";
    
    // Fetch category data using cURL
    $ch = curl_init($categoryApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken"
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // Handle HTTP errors
    if ($httpCode !== 200) {
        error_log("Error fetching category path: HTTP $httpCode for category ID $categoryId");
        return '';
    }
    
    // Decode JSON response
    $categoryData = json_decode($response, true);
    
    // Check for valid data
    if (!isset($categoryData['name'])) {
        error_log("Invalid category data for ID $categoryId");
        return '';
    }
    
    // Build category path
    $path = $categoryData['name'];
    
    // If this category has a parent (not root), get parent path
    if (isset($categoryData['parent_id']) && $categoryData['parent_id'] > 1) {
        $parentPath = getCategoryPath($categoryData['parent_id']);
        if (!empty($parentPath)) {
            $path = $parentPath . ' > ' . $path;
        }
    }
    
    // Store in cache
    $categoryCache[$cacheKey] = $path;
    
    return $path;
}

// Initialize variables for pagination
$currentPage = 1;

do {
    // Fetch data using cURL
    $ch = curl_init("{$apiUrl}&searchCriteria[currentPage]={$currentPage}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken"
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Handle HTTP errors
    if ($httpCode !== 200) {
        error_log("Error fetching data: HTTP $httpCode");
        break;
    }

    // Decode JSON response
    $data = json_decode($response, true);

    // Check for valid data
    if (!isset($data['items']) || empty($data['items'])) {
        break; // Exit if no products are returned
    }

    // Process items and populate CSV
    foreach ($data['items'] as $item) {
        $sku_id = $item['sku'] ?? ''; // Using SKU as the sku_id for TikTok
        $title = $item['name'] ?? '';
        
        // Get description from custom attributes
        $description = '';
        if (isset($item['custom_attributes'])) {
            foreach ($item['custom_attributes'] as $attr) {
                if ($attr['attribute_code'] === 'short_description') {
                    $description = strip_tags($attr['value']); // Strip HTML tags for CSV
                    break;
                }
            }
        }

        // TikTok uses specific availability format: in stock, out of stock
        $availability = $item['status'] == 1 ? 'in stock' : 'out of stock';
        $condition = 'new';
        $price = number_format((float)$item['price'], 2) . ' USD';
        $link = "https://maisonpink.me/catalog/product/view/id/{$item['id']}";

        // Retrieve the image link
        $image_link = '';
        if (isset($item['media_gallery_entries']) && is_array($item['media_gallery_entries'])) {
            foreach ($item['media_gallery_entries'] as $media) {
                if ($media['media_type'] === 'image') {
                    $image_link = $baseMediaUrl . $media['file'];
                    break;
                }
            }
        }

        // Get brand and category information from custom attributes
        $brand = '';
        $category = '';
        
        if (isset($item['custom_attributes'])) {
            foreach ($item['custom_attributes'] as $attr) {
                if ($attr['attribute_code'] === 'brand') {
                    $brand = $attr['value'];
                }
                
                // Look for category-related attributes
                if ($attr['attribute_code'] === 'category_ids') {
                    $category_ids = is_array($attr['value']) ? $attr['value'] : explode(',', $attr['value']);
                    
                    // Get category names using the first category ID
                    if (!empty($category_ids)) {
                        $categoryId = $category_ids[0];
                        // Get full category path instead of just the name
                        $category = getCategoryPath($categoryId);
                    }
                }
            }
        }

        // Write row to CSV
        fputcsv($output, [$sku_id, $title, $description, $availability, $condition, $price, $link, $image_link, $brand, $category]);
    }

    $currentPage++;
} while (count($data['items']) === 100);

// Close file
fclose($output);

echo "TikTok catalog CSV file generated successfully: " . $filePath;
exit();