public function getVariationImageForASIN($asin, $account_id)
 {
     // init api
     $api = new WPLA_AmazonAPI($account_id);
     // get product details from amazon
     $result = $api->getMatchingProductForId($asin, 'ASIN');
     $this->request_count++;
     WPLA()->logger->debug('getMatchingProductForId() returned:' . print_r($result, 1));
     // handle empty result error
     if ($result->success && !empty($result->product->AttributeSets->ItemAttributes->SmallImage->URL)) {
         if (!empty($result->product->GetMatchingProductForIdResult->Error->Message)) {
             $this->lastError = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing['asin']) . '<br><code>' . $result->product->GetMatchingProductForIdResult->Error->Message . '</code>';
         }
         // fetch image URL
         $img_url = $result->product->AttributeSets->ItemAttributes->SmallImage->URL;
         // get 600px image instead of 75px
         $img_url = str_replace('_SL75_', '_SL600_', $img_url);
         WPLA()->logger->info("variation image for ASIN {$asin}: {$img_url}");
         return $img_url;
     }
     WPLA()->logger->warn("no variation image found for ASIN {$asin}");
     return '';
 }
 public function action_update_missing_asins()
 {
     WPLA()->logger->info("do_action: wpla_update_missing_asins");
     $accounts = WPLA_AmazonAccount::getAll();
     $listingsModel = new WPLA_ListingsModel();
     $batch_size = 10;
     // update 10 items at a time
     foreach ($accounts as $account) {
         $account_id = $account->id;
         $listings = $listingsModel->getAllOnlineWithoutASIN($account_id, 10, OBJECT_K);
         if (empty($listings)) {
             continue;
         }
         // process one listing at a time (for now)
         foreach ($listings as $listing) {
             WPLA()->logger->info('fetching ASIN for SKU ' . $listing->sku . ' (' . $listing->id . ') - type: ' . $listing->product_type);
             $api = new WPLA_AmazonAPI($account->id);
             $result = $api->getMatchingProductForId($listing->sku, 'SellerSKU');
             if ($result->success) {
                 if (!empty($result->product->ASIN)) {
                     // update listing ASIN
                     $listingsModel->updateWhere(array('id' => $listing->id), array('asin' => $result->product->ASIN));
                     WPLA()->logger->info('new ASIN for listing #' . $listing->id . ': ' . $result->product->ASIN);
                 } else {
                     // this is what happens when new products are listed but Amazon fails to assign an ASIN
                     // in which case the user might have to contact Amazon seller support...
                     $error_msg = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing->sku);
                     WPLA()->logger->error($error_msg . ' - empty product data!');
                     $error_msg .= ' This SKU does not seem to exist in your inventory on Seller Central. You can try to submit this listing again, but you may have to report this to Amazon Seller Support.';
                     // // build history array (overwrite)
                     // $history = array (
                     //   	'errors' => array (
                     // 	    array (
                     // 			'original-record-number' => '0',
                     // 			'sku'                    => $listing->sku,
                     // 			'error-code'             => '42',
                     // 			'error-type'             => 'Error',
                     // 			'error-message'          => $error_msg,
                     // 	    ),
                     // 	),
                     //   	'warnings' => array(),
                     // );
                     // load existing history data - or init new history array
                     $history = maybe_unserialize($listing->history);
                     if (!is_array($history) || !isset($history['errors'])) {
                         $history = array('errors' => array(), 'warnings' => array());
                     }
                     // add custom error to history array
                     $error_42 = array('original-record-number' => '0', 'sku' => $listing->sku, 'error-code' => '42', 'error-type' => 'Error', 'error-message' => $error_msg);
                     $history['errors'][] = $error_42;
                     // mark as failed - and include error message
                     $listingsModel->updateWhere(array('id' => $listing->id), array('status' => 'failed', 'history' => serialize($history)));
                 }
             } elseif ($result->Error->Message) {
                 $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing->sku) . '<br>Error: ' . $result->Error->Message;
                 WPLA()->logger->error($errors);
             } else {
                 $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing->sku);
                 WPLA()->logger->error($errors);
             }
         }
         // foreach listing
     }
     // each account
 }
 public function jobs_run_task()
 {
     // quit if no job name provided
     if (!isset($_REQUEST['job'])) {
         return false;
     }
     if (!isset($_REQUEST['task'])) {
         return false;
     }
     $job = $_REQUEST['job'];
     $task = $_REQUEST['task'];
     // register shutdown handler
     global $wpla_shutdown_handler_enabled;
     $wpla_shutdown_handler_enabled = true;
     register_shutdown_function(array($this, 'shutdown_handler'));
     WPLA()->logger->info('running task: ' . print_r($task, 1));
     // handle job name
     switch ($task['task']) {
         // update listing from Amazon (current used for new listings without ASIN)
         case 'updateProduct':
             // init
             $lm = new WPLA_ListingsModel();
             $listing = $lm->getItem($task['id']);
             $account = WPLA_AmazonAccount::getAccount($listing['account_id']);
             $api = new WPLA_AmazonAPI($account->id);
             // get product attributes
             // $product = $api->getProduct( $listing['asin'] );
             $result = $api->getMatchingProductForId($listing['sku'], 'SellerSKU');
             // echo "<pre>";print_r($product);echo"</pre>";#die();
             // echo "<pre>";print_r($product);echo"</pre>";die();
             if ($result->success) {
                 if (!empty($result->product->ASIN)) {
                     // update listing attributes
                     $listing_id = $listing['id'];
                     // $lm->updateItemAttributes( $product, $listing_id );
                     // $listing = $lm->getItem( $listing_id ); // update values
                     $lm->updateWhere(array('id' => $listing_id), array('asin' => $result->product->ASIN));
                     WPLA()->logger->info('new ASIN for listing #' . $listing['id'] . ': ' . $result->product->ASIN);
                     // update product
                     // $woo = new WPLA_ProductBuilder();
                     // $woo->updateProducts( array( $listing ) );
                     $success = true;
                     $errors = '';
                 } else {
                     $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing['asin']);
                     $errors .= ' The product data received from Amazon was empty.';
                     $success = false;
                 }
             } elseif ($result->Error->Message) {
                 $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing['asin']) . '<br>Error: ' . $result->Error->Message;
                 $success = false;
             } else {
                 $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $listing['asin']);
                 $success = false;
             }
             // build response
             $response = new stdClass();
             $response->job = $job;
             $response->task = $task;
             $response->errors = empty($errors) ? array() : array(array('HtmlMessage' => $errors));
             $response->success = $success;
             $this->returnJSON($response);
             exit;
             // create new WooCommerce product from imported listing
         // create new WooCommerce product from imported listing
         case 'createProduct':
             // init
             $lm = new WPLA_ListingsModel();
             // $listing = $lm->getItem( $task['id'] );
             $listing_id = $task['id'];
             // create product
             $ProductsImporter = new WPLA_ProductsImporter();
             $success = $ProductsImporter->createProductFromAmazonListing($listing_id);
             $error = $ProductsImporter->lastError;
             $delay = $ProductsImporter->request_count * 1000;
             // ms
             // build response
             $response = new stdClass();
             $response->job = $job;
             $response->task = $task;
             $response->errors = empty($error) ? array() : array(array('HtmlMessage' => $error));
             $response->success = $success;
             $response->delay = $delay;
             $this->returnJSON($response);
             exit;
             // fetch full product description from Amazon and update WooCommerce product
         // fetch full product description from Amazon and update WooCommerce product
         case 'fetchFullProductDescription':
             $webHelper = new WPLA_AmazonWebHelper();
             $webHelper->loadListingDetails($task['id']);
             // echo "<pre>";print_r($webHelper->images);echo"</pre>";#die();
             $lm = new WPLA_ListingsModel();
             $item = $lm->getItem($task['id']);
             if (!empty($webHelper->description)) {
                 // update product
                 $post_id = $item['post_id'];
                 $post_data = array('ID' => $post_id, 'post_content' => trim($webHelper->description));
                 wp_update_post($post_data);
                 $success = true;
                 $errors = '';
             } else {
                 $errors = sprintf(__('There was a problem fetching product details for %s.', 'wpla'), $item['asin']);
                 $errors .= ' The product description received from Amazon was empty.';
                 $success = false;
             }
             // build response
             $response = new stdClass();
             $response->job = $job;
             $response->task = $task;
             $response->errors = empty($errors) ? array() : array(array('HtmlMessage' => $errors));
             $response->success = $success;
             $this->returnJSON($response);
             exit;
             // process Merchant or FBA Report and create / update listings
         // process Merchant or FBA Report and create / update listings
         case 'processReportPage':
             // process report page - both Merchant and FBA reports
             $response = WPLA_ImportHelper::ajax_processReportPage($job, $task);
             $this->returnJSON($response);
             exit;
             // process single row (SKU) Merchant or FBA Report - and create / update listings
         // process single row (SKU) Merchant or FBA Report - and create / update listings
         case 'processSingleSkuFromReport':
             // process report page - both Merchant and FBA reports
             $response = WPLA_ImportHelper::ajax_processReportPage($job, $task, true);
             $this->returnJSON($response);
             exit;
         default:
             // echo "unknown task";
             // exit();
     }
 }