<?php

  class pad_base {
    var $products_id;
    var $products_tax_class_id;
    var $show_out_of_stock;
    var $mark_out_of_stock;
    var $out_of_stock_msgline;
    var $no_add_out_of_stock;

    function pad_base($products_id=0) {


      $this->products_id  = $products_id;

      if ($this->products_id != 0) {
        $tax_class_query = tep_db_query('SELECT products_tax_class_id
                                         FROM ' . TABLE_PRODUCTS . "
                                         WHERE products_id = '" . (int)$products_id . "'");
        $tax_class_array = tep_db_fetch_array($tax_class_query);
        $this->products_tax_class_id = $tax_class_array['products_tax_class_id'];
      }

      $this->_SetConfigurationProperties('PRODINFO_ATTRIBUTE_');

    }

    function _SetConfigurationProperties($prefix) {

      $this->show_out_of_stock    = constant($prefix . 'SHOW_OUT_OF_STOCK');
      $this->mark_out_of_stock    = constant($prefix . 'MARK_OUT_OF_STOCK');
      $this->out_of_stock_msgline = constant($prefix . 'OUT_OF_STOCK_MSGLINE');
      $this->no_add_out_of_stock  = constant($prefix . 'NO_ADD_OUT_OF_STOCK');

    }

    function draw() {

      $out=$this->_draw_table_start();

      $out.=$this->_draw_stocked_attributes();

      $out.=$this->_draw_nonstocked_attributes();

      $out.=$this->_draw_table_end();

      return $out;

    }

    function _draw_table_start() {
	  $out = '           <table border="0" cellspacing="2" cellpadding="5" width="100%">';
	  $out .= '			 <tr><td class="ProductHead"><strong>' . TEXT_PRODUCT_OPTIONS . '</strong></td></tr>';
	  $out .='           <tr><td align="left">';
      $out .='           <table border="0" cellspacing="0" cellpadding="3">';
      return $out;
    }

    function _draw_stocked_attributes() {
      $out = '';

      $attributes = $this->_build_attributes_array(true, false);
      if (sizeof($attributes)>0) {
        foreach ($attributes as $stocked) {
          if (OPTIONS_AS_IMAGES_ENABLED == 'true') {
               $simg_query = tep_db_query("select products_options_images_enabled from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id = '".(int)$stocked['oid']."'");
               $simgs = tep_db_fetch_array($simg_query);
               if ($simgs['products_options_images_enabled'] == 'true') {
                    $out .= '<tr><td align="left" class="main"><b>' . $stocked['oname'] . ":</b></td><td class='main'>" . tep_draw_radio_cecha('id['.$stocked['oid'].']',array_values($stocked['ovals']),$stocked['default'], "onChange=\"showPrice(this.form);\"") . "</td></tr>\n";
                 } else {
                   $out .= '<tr><td align="left" class="main"><b>' . $stocked['oname'] . ":</b></td><td class='main'>" . tep_draw_pull_down_menu('id['.$stocked['oid'].']',array_values($stocked['ovals']),$stocked['default'], "onChange=\"showPrice(this.form);\"") . "</td></tr>\n";
               }
             } else {
               $out .= '<tr><td align="left" class="main"><b>' . $stocked['oname'] . ":</b></td><td class='main'>" . tep_draw_pull_down_menu('id['.$stocked['oid'].']',array_values($stocked['ovals']),$stocked['default'], "onChange=\"showPrice(this.form);\"") . "</td></tr>\n";
          }
        }
      }
      return $out;
    }

    function _draw_nonstocked_attributes() {
      $out='';
      $nonstocked_attributes = $this->_build_attributes_array(false, true);
      foreach($nonstocked_attributes as $nonstocked)
      {
        if (OPTIONS_AS_IMAGES_ENABLED == 'true') {
           $simg_query = tep_db_query("select products_options_images_enabled from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id = '".(int)$nonstocked['oid']."'");
           $simgs = tep_db_fetch_array($simg_query);
           if ($simgs['products_options_images_enabled'] == 'true') {
               $out.='<tr><td align="left" class="main"><b>'.$nonstocked['oname'].":</b></td><td class='main'>".tep_draw_radio_cecha('id['.$nonstocked['oid'].']',$nonstocked['ovals'],$nonstocked['default'], "onClick=\"showPrice(this.form);\"")."</td></tr>\n";
             } else {
               $out.='<tr><td align="left" class="main"><b>'.$nonstocked['oname'].":</b></td><td class='main'>".tep_draw_pull_down_menu('id['.$nonstocked['oid'].']',$nonstocked['ovals'],$nonstocked['default'], "onChange=\"showPrice(this.form);\"")."</td></tr>\n";
           }
        } else {
           $out.='<tr><td align="left" class="main"><b>'.$nonstocked['oname'].":</b></td><td class='main'>".tep_draw_pull_down_menu('id['.$nonstocked['oid'].']',$nonstocked['ovals'],$nonstocked['default'], "onChange=\"showPrice(this.form);\"")."</td></tr>\n";
       }
      }
      return $out;
    }


    function _draw_table_end() {
      return '           </table></td></tr></table>';
    }

    function _build_attributes_array($build_stocked, $build_nonstocked) {
      global $languages_id;
      global $currencies;
      global $cart;

      if (!($build_stocked | $build_nonstocked)) return null;

      if ($build_stocked && $build_nonstocked) {
        $stocked_where='';
      }
      elseif ($build_stocked) {
        $stocked_where="and popt.products_options_track_stock = '1'";
      }
      elseif ($build_nonstocked) {
        $stocked_where="and popt.products_options_track_stock = '0'";
      }

      $products_options_name_query = tep_db_query("select distinct popt.products_options_id, popt.products_options_name, popt.products_options_track_stock from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . (int)$this->products_id . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "' " . $stocked_where . " order by popt.products_options_sort_order");
      $attributes=array();
      //
      while ($products_options_name = tep_db_fetch_array($products_options_name_query)) {
        $products_options_array = array();
        if ( PRODUCTS_OPTIONS_SORT_BY_PRICE !='1' ) {
           $products_options_query = tep_db_query("select pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . (int)$this->products_id . "' and pa.options_id = '" . (int)$products_options_name['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . (int)$languages_id . "'" . " order by pa.products_options_sort_order, pov.products_options_values_name");
 			  } else {
           $products_options_query = tep_db_query("select pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . (int)$this->products_id . "' and pa.options_id = '" . (int)$products_options_name['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . (int)$languages_id . "'" . " order by pa.products_options_sort_order, pa.options_values_price");
        }

        while ($products_options = tep_db_fetch_array($products_options_query)) {
          $products_options_array[] = array('id' => $products_options['products_options_values_id'], 'text' => $products_options['products_options_values_name']);
          if ($products_options['options_values_price'] != '0') {
		    //$rto = $currencies->display_price($products_options['products_options_id'], $products_options['options_values_price'], tep_get_tax_rate($this->products_tax_class_id));
            //$products_options_array[sizeof($products_options_array)-1]['text'] .= ' (' . $products_options['price_prefix'] . $currencies->display_price($products_options['products_options_id'], $products_options['options_values_price'], tep_get_tax_rate($this->products_tax_class_id),1,$display_nb) .')';
		    if (DISPLAY_PRICE_BRUTTO_NETTO == 'true') {
		 	    $display_nb = 1;

				$rto = $currencies->display_price($products_options['products_options_id'], $products_options['options_values_price'], tep_get_tax_rate($this->products_tax_class_id),1,$display_nb);
				$rto = str_replace('<br>', '#', $rto);	//zamienia <br> na #
				$rto_dlugosc = strlen($rto);			//sprawdza dlugosc tekstu
				$rto_pierwsze_wystapienie = strpos($rto, "#");
				$rto_cz1 = substr($rto, 0, $rto_pierwsze_wystapienie) ;		// dzieli lancuch na 2 czesci zeby zamienic
				$rto_cz2 = substr($rto, $rto_pierwsze_wystapienie, $rto_dlugosc) ;
				$rto = $rto_cz2 . ' /' . $rto_cz1;							// najpierw brutto pozniej netto

				$rto = str_replace('<span class="smallText">', '', $rto);	// usuwa zbedne znaki
				$rto = str_replace('</span>', '', $rto);
				$rto = str_replace('#', '', $rto);
				$rto = str_replace('(', '', $rto);
				$rto = str_replace(')', '', $rto);
                $rto = str_replace(']', '', $rto);
                $rto = str_replace('[', '', $rto);

				$products_options_array[sizeof($products_options_array)-1]['text'] .= ' [' . $products_options['price_prefix'] . ' ' .strip_tags($rto) .']';
		 	  } else {
			    $products_options_array[sizeof($products_options_array)-1]['text'] .= ' [' . $products_options['price_prefix'] . ' ' .$currencies->display_price($products_options['products_options_id'], $products_options['options_values_price'], tep_get_tax_rate($this->products_tax_class_id)) .']';
		    }
          }
        }
        //if (isset($cart->contents[$this->products_id]['attributes'][$products_options_name['products_options_id']])) {
        //  $selected = $cart->contents[$this->products_id]['attributes'][$products_options_name['products_options_id']];
        // } else {
        //  $selected = 0;
        //}
        // dodatkowe - zeby podswietalo cechy nie tylko z koszyka
        $selected = 0;
        $rts = $this->products_id;
        if (strpos($rts,'{') > 0) {
            $cechy_produkt = substr($rts,strpos($rts,'{'),strlen($rts));
        }
        $idm = substr($cechy_produkt,1,strlen($cechy_produkt)); $idm = str_replace('{',',',$idm); $idm = str_replace('}',':',$idm);
        $ceszki = explode(',',$idm);
        foreach ($ceszki as $ed) {
           $dfa = explode(':',$ed);
           if ($dfa[0] == $products_options_name['products_options_id']) {
               $selected = (int)$dfa[1];
           }
        }
        // dodatkowe - zeby podswietalo cechy nie tylko z koszyka   - KONIEC
        $attributes[]=array('oid'=>$products_options_name['products_options_id'],
                            'oname'=>$products_options_name['products_options_name'],
                            'ovals'=>$products_options_array,
                            'default'=>$selected);
      }
      return $attributes;
    }

    function _build_attributes_combinations($attributes, $showoos, $markoos, &$combinations, &$selected_combination, $oidindex=0, $comb=array(), $id="", $text='', $isselected=true) {
      global $cart;

      foreach ($attributes[$oidindex]['ovals'] as $attrib) {
        $newcomb = $comb;
        $newcomb[$attributes[$oidindex]['oid']] = $attrib['id'];
        $newid=$id.','.$attributes[$oidindex]['oid'].'-'.$attrib['id'];
        $newtext = $text.", ".$attrib['text'];
        if (isset($cart->contents[$this->products_id]['attributes'][$attributes[$oidindex]['oid']]))
          $newisselected = ($cart->contents[$this->products_id]['attributes'][$attributes[$oidindex]['oid']] == $attrib['id']) ? $isselected : false;
        else
          $newisselected = false;
        if (isset($attributes[$oidindex+1])) {
          $this->_build_attributes_combinations($attributes, $showoos, $markoos, $combinations, $selected_combination, $oidindex+1, $newcomb, $newid, $newtext, $newisselected);
        }
        else {
          $is_out_of_stock=tep_check_stock(tep_get_prid($this->products_id),1,$newcomb);
          if (!$is_out_of_stock | ($showoos == true)) {
            switch ($markoos) {
              case 'Left':   $newtext=($is_out_of_stock ? TEXT_OUT_OF_STOCK.' - ' : '').substr($newtext,2);
                             break;
              case 'Right':  $newtext=substr($newtext,2).($is_out_of_stock ? ' - '.TEXT_OUT_OF_STOCK : '');
                             break;
              default:       $newtext=substr($newtext,2);
                             break;
            }
            $combinations[] = array('comb'=>$newcomb, 'id'=>substr($newid,1), 'text'=>$newtext);
            if ($newisselected) $selected_combination = sizeof($combinations)-1;
          }
        }
      }
    }


    function _draw_js_stock_array($combinations) {
      if (!((isset($combinations)) && (is_array($combinations)) && (sizeof($combinations) > 0))){
        return '{}';
      }
      $out='';
      foreach ($combinations[0]['comb'] as $oid=>$ovid) {
        $out.='{'.$ovid.':';
        $opts[]=$oid;
      }
      $out.='1';

      for ($combindex=1; $combindex<sizeof($combinations); $combindex++) {
        $comb=$combinations[$combindex]['comb'];
        for ($i=0; $i<sizeof($opts)-1; $i++) {
          if ($comb[$opts[$i]]!=$combinations[$combindex-1]['comb'][$opts[$i]]) break;
        }
        $out.=str_repeat('}',sizeof($opts)-1-$i).',';
        if ($i<sizeof($opts)-1) {
          for ($j=$i; $j<sizeof($opts)-1; $j++)
            $out.=$comb[$opts[$j]].':{';
        }
        $out.=$comb[$opts[sizeof($opts)-1]].':1';
      }
      $out.=str_repeat('}',sizeof($opts));

      return $out;
    }

  }
?>
