<?php
/**
 * stock
 *
 * class for the stock
 *
 * @version    1.0
 * @author     Erik Timmers, amgate <erik.timmers@amgate.com>
 * @copyright  Amgate, 2010
 * @since      11-01-2010 - initial creation
 * @package    CDVB0100
 */

class stock extends stdModule
{
    var $_btvc_scans;
    var $_scannerId;
    var $_dateTime;
    var $_profile;
    var $_praktijk;

    function stock() {
        $this->stdModule('cdvb0100');
        $this->setVariable('modcode', 'cdvb0100');
    }

    /**
     * sessify
     *
     * fill the class from a (OPN2001) scan
     *
     * @access public
     * @return void
     */
    function sessify()
    {
        global $globalSettings;
        global $oCart;

        $this->_btvc_scans = array();

        $this->_dateTime  = $_REQUEST['_b_date'][0];
        $this->_scannerId = $_REQUEST['_scanner_id'];

        foreach ($_REQUEST['_b_val'] as $barcode) {
            $prd_code = $this->strip_prefix($barcode, $globalSettings->barcodePrefix);

            $prd_id = $oCart->getProductID($prd_code);

            if (is_numeric($prd_id)) {

                if (!isset($this->_btvc_scans[$prd_id])) {
                    $this->_btvc_scans[$prd_id] = 1;
                } else {
                    $this->_btvc_scans[$prd_id] += 1;
                }

            }

        }

    }
    
    function sessifyXml() 
    {
        global $globalSettings;
        global $oCart;
                
        preg_match_all('/<barcode>.*<code>(.*)<\/code>.*<amount>(.*)<\/amount>.*<date>(.*)<\/date>.*<\/barcode>/iU', $_REQUEST['_b_val'], $aMatches);

        foreach((array)$aMatches[1] as $key => $value) {

            $this->_scannerId = $_REQUEST['_scanner_id'];

            
            // strip DATA.XML from value
            // trim 
            // remove the trailing 2, why is there a 2?
            // and strip the prefix (+DTA)
            // replace is niet meer nodig aangepast senario
           // $sCode = substr(trim(str_replace('DATA.XML', '', $value)), 0, -2);
            $sCode = trim($value);
            
            $sCode = $this->strip_prefix($sCode, $globalSettings->barcodePrefix);
           // echo "<br>ben er niet";
            $nPrdId = $oCart->getProductID($sCode);   
           // var_dump($nPrdId);
                                            
            $nAmount = (int)trim($aMatches[2][$key]);

            if (is_numeric($nPrdId)) {

                if (!isset($this->_btvc_scans[$nPrdId])) {
                    $this->_btvc_scans[$nPrdId] = (int)$nAmount;
                } else {
                    $this->_btvc_scans[$nPrdId] += (int)$nAmount;
                }

            }            
            
        }

	$sTmpTime = $aMatches[3][0];
	$yr = substr($sTmpTime, 0, 4);
        $mn = substr($sTmpTime, 4, 2);
        $dy = substr($sTmpTime, 6, 2);
        $hr = substr($sTmpTime, 8, 2);
        $mi = substr($sTmpTime, 10, 2);
        $sc = substr($sTmpTime, 12, 2);

        $this->_dateTime = mktime($hr, $mi, $sc, $mn, $dy, $yr); //$hr . ':' . $mi . ':' . $sc . '  ' . $dy . '/' . $mn . '/' . $yr; 


	//var_dump($this->_dateTime);
	//var_dump($this->getDateTime());
}

    /**
     * make
     *
     * make a stock-object and set in session
     *
     * @access public
     * @return void
     */
    function make()
    {

        $oStock = new stock();
        if (is_array($_REQUEST['_b_val'])) {
            $oStock->sessify();
        } elseif(isset($_REQUEST['_b_val'])) {
            $oStock->sessifyXml();            
        }
        $_SESSION['cdvb_stock'] = $oStock;

    }

    /**
     * retrieve
     *
     * remake the session-object from aan object type __PHP_Incomplete_Class into type stock
     *
     * @access public
     * @return void
     */
    function retrieve()
    {
        $_SESSION['cdvb_stock'] = unserialize(serialize($_SESSION["cdvb_stock"]));
    }

    function remove()
    {
        unset($_SESSION['cdvb_stock']);
    }


    /**
     * strip_prefix
     *
     * strip prefix from barcode
     *
     * @access public
     * @param  string $barcode          barcode
     * @param  string $prefixToRemove   the prefix
     * @return string
     */
    function strip_prefix($barcode, $prefixToRemove)
    {
        return str_replace($prefixToRemove, '', $barcode);
    }

    function storeprofile()
    {
        $this->_profile  = $_REQUEST["prforgs"];
        $this->_praktijk = $_REQUEST["prkorgs_" . $_REQUEST["prforgs"]];
    }

    function setprofile($prf, $prk)
    {
        $this->_profile  = $prf;
        $this->_praktijk = $prk;
    }

    function getProfile()
    {
        return $this->_profile;
    }

    function getPraktijk()
    {
        return $this->_praktijk;
    }

    function getScannerId()
    {
        return $this->_scannerId;
    }

    function getDateTime()
    {
        return date('Y-m-d H:i:s', $this->_dateTime); // 'YYYY-MM-DD HH:MM:SS'
    }

    function getStock()
    {
        return $this->_btvc_scans;
    }

    /**
     * getReadable
     *
     * Make readable array par example for showing on a page
     *
     * @access public
     * @return array
     */
    function getReadable()
    {
        global $g_obj_i3a;
        global $g_obj_cart;

        // get name of inkooporganisations
	    $q = array( 'AND'
	    	      , array(I3A_FLD, 'ORG_ID', " = " . (int)$this->_profile )
	    	      , array(I3A_FLD, 'ORG_NAME')
                  );
	    $g_obj_i3a->searchOrganizations($aOrgs, $q);
	    $aReturn['profile'] = $aOrgs[0]['ORG_NAME'];

        // get name of praktijk
	    $q = array( 'AND'
	    	      , array(I3A_FLD, 'ORG_ID', " = " . (int)$this->_praktijk )
	    	      , array(I3A_FLD, 'ORG_NAME')
                  );
	    $g_obj_i3a->searchOrganizations($aOrgs, $q);

	    $aReturn['praktijk'] = $aOrgs[0]['ORG_NAME'];

        // get products-info
        $sIds = implode(',', array_keys($this->_btvc_scans));
        $aProds = $g_obj_cart->getProducts($sIds);
        // add count to product-info
        if (count($this->_btvc_scans) > 1) {
            foreach((array)$aProds as $id=>$prod) {
                $aProds[$id]['inStock'] = $this->_btvc_scans[$id];
            }
        } else {
            $rewrite[$aProds['id']] = $aProds;
            $rewrite[$aProds['id']]['inStock'] = $this->_btvc_scans[$aProds['id']];
            $aProds = $rewrite;
        }

        $aReturn['products'] = $aProds;

        return $aReturn;
    }

    function getAvailableStock($oid, $aDates)
    {
        $sSql = " SELECT invr_prd_id
                       , lbl_label
                       , date_format(inv_datetime, '%Y%m%d') as inv_datetime
                       , date_format(inv_datetime, '%Y-%m-%d') as inv_datetime_sql
                       , date_format(inv_datetime, '%d-%m-%Y') as inv_datetime_fm
                       , invr_number
                    FROM tbl_dvb_inventory
                        JOIN tbl_dvb_inventory_row
                          ON invr_inv_id = inv_id
                        JOIN tbl_ctl_labels
                          ON lbl_itm_tbl = 'tbl_ctl_products'
                         AND lbl_itm_col = 'prd_name'
                         AND lbl_itm_id = invr_prd_id
                   WHERE inv_clientele_id = " . (int)$oid . "
                     AND inv_datetime > '" . date('Y-m-d', $aDates['dateStart']) . "'
                     AND inv_datetime <= '" . date('Y-m-d', $aDates['dateEnd']) . "'
                ";
         $rst = $this->_db->Query($sSql);
         while (!$rst->EOF()) {
            $aBase[$rst->Row('invr_prd_id')][] = $rst->Row();
            $rst->MoveNext();
         }
         $rst->Close();

         foreach((array)$aBase as $pid => $aScans) {
            if (count($aScans) == 1) {
                // only one scan
                $aReturn[$pid]['name']             = $aScans[0]['lbl_label'];
                $aReturn[$pid]['startStock']       = $aScans[0]['invr_number'];
                $aReturn[$pid]['startStockDate']   = $aScans[0]['inv_datetime'];
                $aReturn[$pid]['startStockDateFm'] = $aScans[0]['inv_datetime_fm'];
                $aReturn[$pid]['orders']           = $this->getOrders($oid, $pid, $aScans[0]['inv_datetime_sql'], date('Y-m-d', $aDates['dateEnd']));

            } else {

                $aReturn[$pid]['name']             = $aScans[0]['lbl_label'];
                uasort($aScans, array($this, 'scanSort'));

                reset($aScans);
                $first = current($aScans);
                $aReturn[$pid]['startStock']       = $first['invr_number'];
                $aReturn[$pid]['startStockDate']   = $first['inv_datetime'];
                $aReturn[$pid]['startStockDateFm'] = $first['inv_datetime_fm'];

                end($aScans);
                $last = current($aScans);
                $aReturn[$pid]['endStock']         = $last['invr_number'];
                $aReturn[$pid]['endStockDate']     = $last['inv_datetime'];
                $aReturn[$pid]['endStockDateFm']   = $last['inv_datetime_fm'];

                $aReturn[$pid]['orders']           = $this->getOrders($oid, $pid, $first['inv_datetime_sql'], $last['inv_datetime_sql']);

                $aReturn[$pid]['consumption']      = $first['invr_number'] - $last['invr_number'] + $aReturn[$pid]['orders'];
                unset($first);
                unset($last);
            }

         }


         return $aReturn;

    }

    function getOrders($oid, $pid, $firstDate, $lastDate = null)
    {
        $sSql = " SELECT sum(orl_amount) as total
                    FROM tbl_dvb_order
                    JOIN tbl_dvb_orderline ON orl_ord_id = ord_id
                   WHERE ord_org_id = " . (int)$oid . "
                     AND orl_prd_id = " . (int)$pid . "
                     AND ord_datetime > '" . $firstDate . "'
                     AND ord_datetime <= '" . $lastDate . "'
               ";
        $rst = $this->_db->Query($sSql);
        $nAmount = $rst->Row('total');
        $rst->Close();
        return (int)$nAmount;
    }

    function scanSort($a, $b)
    {
        if ($a['inv_datetime'] == $b['inv_datetime']) {
            return 0;
        }

        return strcmp($a['inv_datetime'], $b['inv_datetime']);
    }


}


?>
