<?php

/**
 * @package attrib for ajax
 * @copyright Copyright 2006 rainer langheiter, http://edv.langheiter.com
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: products_with_attributes_stock_ajax.php 389 2008-11-14 16:02:14Z hugo13 $
 * 
 * Stock by Attributes 1.5.2
 */
require 'includes/application_top.php';
require DIR_WS_CLASSES . 'currencies.php';
require DIR_WS_CLASSES . 'products_with_attributes_stock.php';
include DIR_WS_LANGUAGES . $_SESSION['language'] . '/products_with_attributes_stock.php';
$stock = new products_with_attributes_stock();
if ($_GET['save'] == 1) {
    if (isset($_GET['page']) && $_GET['page']) {
        $parameters = 'page=' . $_GET['page'];
    } else {
        $parameters = '';
    }
    $x = $stock->saveAttrib();
    //This does not seem to have a purpose, need to look closer.
    if (is_numeric($_GET['pid']) && $_GET['pid'] > 0) {
        zen_redirect(zen_href_link(FILENAME_PRODUCTS_WITH_ATTRIBUTES_STOCK, 'updateReturnedPID=' . $_GET['pid'] . '&amp;' . $parameters, 'NONSSL'));
    } else {
        zen_redirect(zen_href_link(FILENAME_PRODUCTS_WITH_ATTRIBUTES_STOCK, $parameters, 'NONSSL'));
    }
} else {
    $x = $stock->displayFilteredRows();
    print_r($x);
            <td class="dataTableHeadingContent" align="right"><?php 
    echo TABLE_HEADING_TOTAL_EXCLUDING_TAX;
    ?>
</td>
            <td class="dataTableHeadingContent" align="right"><?php 
    echo TABLE_HEADING_TOTAL_INCLUDING_TAX;
    ?>
</td>
          </tr>
<?php 
    // START "Stock by Attributes"
    //include language file
    include DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . 'products_with_attributes_stock.php';
    //new object from class
    require_once DIR_WS_CLASSES . 'products_with_attributes_stock.php';
    $stock = new products_with_attributes_stock();
    // END "Stock by Attributes"
    for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
        if (DISPLAY_PRICE_WITH_TAX_ADMIN == 'true') {
            $priceIncTax = $currencies->format(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $currencies->get_decimal_places($order->info['currency'])) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']);
        } else {
            $priceIncTax = $currencies->format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']);
        }
        echo '          <tr class="dataTableRow">' . "\n" . '            <td class="dataTableContent" valign="top" align="right">' . $order->products[$i]['qty'] . '&nbsp;x</td>' . "\n" . '            <td class="dataTableContent" valign="top">' . $order->products[$i]['name'];
        if (isset($order->products[$i]['attributes']) && sizeof($order->products[$i]['attributes']) > 0) {
            $attributes = array();
            // mc12345678 Moved to within if statement otherwise doesn't apply elsewhere.
            for ($j = 0, $k = sizeof($order->products[$i]['attributes']); $j < $k; $j++) {
                // kuroi: SbA //this bit of code does not seem to be used on this page, need to see if it is dead code or used elseware!
                $option_name_array = explode(":", $order->products[$i]['attributes'][$j]['option']);
                $option_Name = $option_name_array[0];
function importSBAtableData()
{
    global $db, $resultMmessage, $failed;
    require DIR_WS_CLASSES . 'products_with_attributes_stock.php';
    $stock = new products_with_attributes_stock();
    //new object from class
    $separater = ',';
    //set the list separation character ',' to whatever is needed.
    $separater2 = ';';
    //set the list separation character ';' to whatever is needed.
    $SBAtableReport = DIR_FS_BACKUP . 'tableSBAdata.csv';
    //path 'backups/' and filename 'tableSBAdata' for export
    $stockResult = null;
    $qtyResult = null;
    $ReportFile = null;
    $customid = null;
    //Use these settings only if needed.
    //ini_set('memory_limit','96M'); //Increase only if you are having a memory low issue, then change back when done
    //ini_set('max_execution_time','0'); //If set to zero, no time limit is imposed, remove when done
    //ini_set('max_input_time','0'); //If set to zero, no time limit is imposed, remove when done
    if (checkSBAtable(TABLE_PRODUCTS_WITH_ATTRIBUTES_STOCK)) {
        $ReportFile = file($SBAtableReport);
        //get file data
    } else {
        array_push($resultMmessage, 'FAILED table products_with_attributes_stock not found!');
        $failed = true;
    }
    /* Only update the QTY and Custom ID fields
     * checks input file data prior to loading to database, only numeric is allowed for QTY
     */
    if ($ReportFile) {
        $i = -1;
        //Count; adjust for skipping first line in file
        foreach ($ReportFile as $line_num => $line) {
            //skip line 0 as it is the header row
            if ($line_num > 0) {
                //decide what separater was used i.e., a comma or a semicolon
                //some programs save the CSV with a comma, others use a semicolon
                if (count(explode($separater, $line)) == 10) {
                    $line = explode($separater, $line);
                } elseif (count(explode($separater2, $line)) == 10) {
                    $line = explode($separater2, $line);
                } else {
                    $line = null;
                }
                //checks done on the input data prior to loading to database
                $stockResult = doubleval(trim($line[0]));
                $qtyResult = doubleval(trim($line[7]));
                $customid = trim($line[9]);
                $customid = str_replace('"', '', $customid);
            }
            $i++;
            //increment count
            if (!empty($stockResult) && $qtyResult >= 0) {
                $saveResult = $stock->updateAttribQty($stockResult, $qtyResult);
                if ($saveResult != 1 && $line_num > 0 || !is_numeric($line[0]) && $line_num > 0 || !is_numeric($line[7]) && $line_num > 0) {
                    $failed = true;
                    array_push($resultMmessage, 'FAILURE during save Qty process! stock_id: ' . $i . ' Bad Quantity value, error:' . $saveResult);
                    //report any line error
                }
            }
            if (!empty($stockResult) && !empty($customid)) {
                $saveResult = $stock->updateCustomIDAttrib($stockResult, $customid);
                //echo "Stock ID: $stockResult  Custom ID: $customid <br />";//Debug Line, comment this out to remove from displaying on web page
                if ($saveResult != 1 && $line_num > 0 || !is_numeric($line[0]) && $line_num > 0) {
                    $failed = true;
                    array_push($resultMmessage, 'FAILURE during save Custom ID process! Record: ' . $i . ' error:' . $saveResult);
                    //report any line error
                }
            }
        }
        array_push($resultMmessage, 'Updated ' . $i . ' Quantities from: ' . $SBAtableReport);
    } else {
        array_push($resultMmessage, 'Update FAILED no file found!');
        $failed = true;
    }
    return;
}
 // if Detailed Stock By Attributes Import
 // Import stock quantity knowing that cart has SBA installed:
 // FOR RESYNC, THEN THE FOLLOWING APPLIES and will need to get/carry over the
 // $stock class:
 // require(DIR_WS_CLASSES . 'products_with_attributes_stock.php');
 // $stock = new products_with_attributes_stock;
 // 		if(is_numeric((int)$_GET['products_id'])){
 //			$stock->update_parent_products_stock((int)$_GET['products_id']);
 //		$messageStack->add_session('Parent Product Quantity Updated', 'success');
 if (strtolower(substr($file['name'], 0, 12)) == "sba-stock-ep" && $ep_4_SBAEnabled != false) {
     $sync = false;
     if (isset($_GET['sync']) && $_GET['sync'] == '1') {
         $query = array();
         $sync = true;
         require DIR_WS_CLASSES . 'products_with_attributes_stock.php';
         $stock = new products_with_attributes_stock();
     }
     while ($items = fgetcsv($handle, 0, $csv_delimiter, $csv_enclosure)) {
         // read 1 line of data
         //IF STANDARD STOCK, then Update the standard stock
         if ($items[$filelayout['v_SBA_tracked']] == '') {
             $sql = "UPDATE " . TABLE_PRODUCTS . " SET \n\t\t\t\t\tproducts_quantity\t\t\t\t\t    = " . $items[(int) $filelayout['v_products_quantity']] . "\n\t\t\t\t\tWHERE (\n\t\t\t\t\tproducts_id = " . $items[(int) $filelayout['v_table_tracker']] . " )";
             if ($sync) {
                 $query[$items[(int) $filelayout['v_products_model']]] = $items;
                 //Need to capture all of the product model/product number/quantity counts so that can do a comparison in the SBA section and remove the data point.  Once all done, then cycle through this data and update with it.
             } elseif (!$sync) {
                 if ($result = ep_4_query($sql)) {
                     zen_record_admin_activity('Updated product ' . (int) $items[(int) $filelayout['v_table_tracker']] . ' via EP4.', 'info');
                     $ep_update_count++;
                     $display_output .= sprintf(EASYPOPULATE_4_DISPLAY_RESULT_UPDATE_PRODUCT, $items[(int) $filelayout['v_products_model']]) . $items[(int) $filelayout['v_products_quantity']];
                 } else {
 function updateTitleAttrib($stockid = null, $skuTitle = null)
 {
     global $db;
     $stock = new products_with_attributes_stock();
     $skuTitle = addslashes($skuTitle);
     $skuTitle = $stock->nullDataEntry($skuTitle);
     //sets proper quoting for input
     if ($skuTitle && is_numeric($stockid)) {
         $query = 'update ' . TABLE_PRODUCTS_WITH_ATTRIBUTES_STOCK . ' set title = ' . $skuTitle . ' where stock_id = ' . $stockid . ' limit 1';
         $result = $db->execute($query);
     }
     return $result;
 }