/*
 Theme Name:   Woodmart Child
 Description:  Woodmart Child Theme
 Author:       XTemos
 Author URI:   http://xtemos.com
 Template:     woodmart
 Version:      1.0.0
 Text Domain:  woodmart
add_filter('wp_handle_upload_prefilter', 'n8n_custom_media_upload_router');
function n8n_custom_media_upload_router($file) {
    // Only run this logic when files are uploaded natively via the n8n REST API
    if (defined('REST_REQUEST') && REST_REQUEST) {
        add_filter('upload_dir', 'n8n_dynamic_sku_directory_routing');
    }
    return $file;
}

function n8n_dynamic_sku_directory_routing($param) {
    // Retrieve the file name passed by n8n from the query request context
    if (isset($_REQUEST['name'])) {
        $filename = sanitize_file_name($_REQUEST['name']);
    } elseif (isset($_FILES['file']['name'])) {
        $filename = sanitize_file_name($_FILES['file']['name']);
    } else {
        return $param; // Fallback to default if no name metadata is provided
    }

    // Regex to capture the base SKU folder (e.g., matching "PET-602907" from "PET-602907-01.jpg")
    if (preg_match('/^([A-Z]{3}-\d+)/i', $filename, $matches)) {
        $skuFolder = strtoupper($matches[1]); // Normalizes to uppercase folder names
        
        // Rewrite the internal server write paths and clean URLs
        $param['path']   = WP_CONTENT_DIR . '/uploads/products/' . $skuFolder;
        $param['url']    = WP_CONTENT_URL . '/uploads/products/' . $skuFolder;
        $param['subdir'] = '/products/' . $skuFolder;
    } else {
        // Fallback catch-all for items that don't match the specific code pattern
        $param['path']   = WP_CONTENT_DIR . '/uploads/products';
        $param['url']    = WP_CONTENT_URL . '/uploads/products';
        $param['subdir'] = '/products';
    }

    return $param;
}
*/
