<?php
/**
 *
 *
 * @author Luiz Gilberto Gregory Filho [luiz@solis.coop.br]
 *
 * @version $Id$
 *
 * \b Maintainers: \n
 * Eduardo Bonfandini [eduardo@solis.coop.br]
 * Jamiel Spezia [jamiel@solis.coop.br]
 * Luiz Gregory Filho [luiz@solis.coop.br]
 * Moises Heberle [moises@solis.coop.br]
 * Sandro R. Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 08/12/2008
 *
 * \b Organization: \n
 * SOLIS - Cooperativa de Solucoes Livres \n
 * The Gnuteca3 Development Team
 *
 * \b CopyLeft: \n
 * CopyLeft (L) 2007 SOLIS - Cooperativa de Solucoes Livres \n
 *
 * \b License: \n
 * Licensed under GPL (for further details read the COPYING file or http://www.gnu.org/copyleft/gpl.html )
 *
 * \b History: \n
 * See history in SVN repository: http://gnuteca.solis.coop.br
 *
 **/
class FrmKardexControlDetails extends GnutecaForm
{
    /**
     * Enter description here...
     *
     * @var unknown_type
     */
    public  $MIOLO,
            $module,
            $action;

    public  $function,
            $business,
            $home,
            $closeButton,
            $tabValue,
            $controlNumber;

    public  $businessMaterial,
            $businessSupplier,
            $businessTag,
            $businessKardexControl,
            $businessExemplaryStatus,
            $businessMaterialType,
            $businessLibraryUnit,
            $businessMaterialGender,
            $busSupplierTypeAndLocation,
            $businessMarcTagListing,
            $busPrefixSuffix;

    public  $imagePlusUrl   = null,
            $imageMinusUrl  = null;

    /**
     * Class constructor
     **/
    function __construct($controlNumber = null)
    {
        $this->controlNumber = $controlNumber;

        $this->MIOLO    = MIOLO::getInstance();
        $this->module   = MIOLO::getCurrentModule();
        $this->function = MIOLO::_REQUEST('function');
        $this->action   = MIOLO::getCurrentAction();

        $this->businessMaterial             = $this->MIOLO->getBusiness( $this->module, 'BusMaterial');
        $this->businessKardexControl        = $this->MIOLO->getBusiness( $this->module, 'BusKardexControl');
        $this->businessSupplier             = $this->MIOLO->getBusiness( $this->module, 'BusSupplier');
        $this->businessTag                  = $this->MIOLO->getBusiness( $this->module, 'BusTag');
        $this->businessLibraryUnit          = $this->MIOLO->getBusiness( $this->module, 'BusLibraryUnit');
        $this->businessMaterialGender       = $this->MIOLO->getBusiness( $this->module, 'BusMaterialGender');
        $this->businessMaterialType         = $this->MIOLO->getBusiness( $this->module, 'BusMaterialType');
        $this->businessExemplaryStatus      = $this->MIOLO->getBusiness( $this->module, 'BusExemplaryStatus');
        $this->businessMarcTagListing       = $this->MIOLO->getBusiness( $this->module, 'BusMarcTagListing');
    	$this->busSupplierTypeAndLocation   = $this->MIOLO->getBusiness( $this->module, "BusSupplierTypeAndLocation");
    	$this->busPrefixSuffix              = $this->MIOLO->getBusiness( $this->module, "BusPrefixSuffix");

        $this->imagePlusUrl             = $this->MIOLO->getUI()->getImage($this->module, 'plus-8x8.png');
        $this->imageMinusUrl            = $this->MIOLO->getUI()->getImage($this->module, 'minus-8x8.png');

        parent::__construct( _M('Kardex control details', $this->module) );
        $this->setWidth("90%");
        //$this->setWidth("800px");

        $this->eventHandler();
        $this->defineFields();
        $this->tabValue = null;

        /*
        $this->MIOLO->page->onload("

            if(document.getElementById('tableSupplierInfos'))
            {
                document.getElementById('tableSupplierInfos').style.border  = '1px solid ". CATALOGE_TAG_LABEL_COLOR ."';
            }

            if(document.getElementById('tableWorkInfos'))
            {
                document.getElementById('tableWorkInfos').style.border = '1px solid ". CATALOGE_TAG_LABEL_COLOR ."';
            }

            if(document.getElementById('divKardex'))
            {
                divsKardex = document.getElementById('divKardex').getElementsByTagName('TABLE');

                for(x=0; x < divsKardex.length; x++)
                {
                    if(divsKardex[x].id.indexOf('kardexControlTableRaw_') > -1 || divsKardex[x].id.indexOf('ColectionInfosTableRaw') > -1)
                    {
                        divsKardex[x].style.border = '1px solid ". CATALOGE_TAG_LABEL_COLOR ."';
                    }
                }
            }

        ");
        */
    }




    /**
     * Default method to define fields
     **/
    public function defineFields()
    {
        $tabControl   = new ATabControl('tabDetail');
        $tabControl->addTab( 'tabWork',         _M('Work info', $this->module),     $this->getWorkInfos());
        $tabControl->addTab( 'tabSupplier',     _M('Supplier', $this->module),      $this->getSupplierInfos());
        $tabControl->addTab( 'tabKardexInfo' ,  _M('Kardex info', $this->module),   $this->getKardexInfos());

        $fields[] = new MDiv("geralContent", $tabControl, null);

        $this->setFields($fields);
        $this->setShowPostButton(FALSE);
    }



    /**
     * Enter description here...
     *
     * @return unknown
     */
    public function getSupplierInfos()
    {
        $this->businessMaterial->clean();

        $fornecedor     = $this->businessMaterial->getContentTag($this->controlNumber, MARC_SUPPLIER_TAG);
        if(!$fornecedor)
        {
            return array(new MDiv('', _M("Supplier has not.", $this->module)));
        }

        $supplierInfos  = $this->businessSupplier->getSupplierCompleteData($fornecedor);
        if(!$supplierInfos)
        {
            return array(new MDiv('', _M("Without information on the supplier.", $this->module)));
        }

        $tabControl = new ATabControl('supplierTypeAndLocation');

        $tabControl->addTab('tabBuy',          _M('Buy',          $this->module), $this->getTabFields("C", $supplierInfos));
        $tabControl->addTab('tabInterchange',  _M('Interchange',  $this->module), $this->getTabFields("P", $supplierInfos));
        $tabControl->addTab('tabDonation',     _M('Donation',     $this->module), $this->getTabFields("D", $supplierInfos));

        return array($tabControl);
    }


    private function getTabFields($type, $supplierInfos)
    {

        $table = new MTableRaw(_M("Supplier Infos", $this->module), null , null, 'tableSupplierInfos');
        $table->setAlternate(true);
        //$table->addAttribute("style", "width:100%");
        $table->setWidth("100%");
        $table->setCellAttribute(0, 0, "width", "10%");
        $table->setCellAttribute(0, 1, "width", "60%");

        foreach($supplierInfos->TypeLocation as $conteudo)
        {
            $typeMinuscula = strtolower($type);

            if ($conteudo->type ==  $typeMinuscula)
            {
                $table->array[] = array(_M("Name",              $this->module), $supplierInfos->supplier->name);
                $table->array[] = array(_M("Company name",      $this->module), $conteudo->companyName);
                $table->array[] = array(_M("CNPJ",              $this->module), $conteudo->cnpj);
                $table->array[] = array(_M("Location",          $this->module), $conteudo->location);
                $table->array[] = array(_M("Neighborhood",      $this->module), $conteudo->neighborhood);
                $table->array[] = array(_M("City",              $this->module), $conteudo->city);
                $table->array[] = array(_M("Zip code",          $this->module), $conteudo->zipCode);
                $table->array[] = array(_M("Phone",             $this->module), $conteudo->phone);
                $table->array[] = array(_M("Alternative phone", $this->module), $conteudo->alternativePhone);
                $table->array[] = array(_M("Fax",               $this->module), $conteudo->fax);
                $table->array[] = array(_M("Email",             $this->module), $conteudo->email);
                $table->array[] = array(_M("Alternative email", $this->module), $conteudo->alternativeEmail);
                $table->array[] = array(_M("Contact",           $this->module), $conteudo->contact);
                $table->array[] = array(_M("Site",              $this->module), $conteudo->site);
                $table->array[] = array(_M("Observation",       $this->module), $conteudo->observation);
                $table->array[] = array(_M("Bank deposit",      $this->module), $conteudo->bankDeposit);
                $table->array[] = array(_M("Date",              $this->module), GnutecaDate::toUser($conteudo->date, 'DATE'));
                return array($table);
            }
        }
    }


    /**
     * Enter description here...
     *
     * @return unknown
     */
    function getKardexInfos()
    {
        $this->businessMaterial->clean();
        $kardex = $this->businessMaterial->getContent($this->controlNumber, MARC_KARDEX_FIELD, null, null, true, true, "line, subfieldid");

        if(!$kardex)
        {
            return array(new MDiv('', _M("Without information on the kardex.", $this->module)));
        }

        $units = null;
        foreach ($kardex as $content)
        {
            if($content->subfieldid == MARC_KARDEX_LIBRARY_UNIT_ID_SUBFIELD)
            {
                $units[$content->content] = $content->line;
            }
        }

        $kardexUnits = null;
        foreach($units as $unit => $line)
        {
            foreach ($kardex as $content)
            {
                if($line == $content->line)
                {
                    $kardexUnits[$unit][$content->subfieldid] = $content->content;
                }
            }
        }
        
        foreach($units as $unit => $line)
        {
            $libraryName = $this->businessLibraryUnit->getLibraryName($unit);
            $buttons[]   = new MButton("kardexControlButtons_$unit", $libraryName, "javascript:displayKardexControlDetailsInfo('kardexControlTableRaw_$unit')");
        }

        //Collection infos
        $referenciados = null;
        if($r = $this->businessKardexControl->getReferenced($this->controlNumber))
        {
            foreach ($r as $c)
            {
                $_controlNumber = $c[0];
                list($fieldId, $subFieldId) = explode('.', MARC_EXEMPLARY_LIBRARY_UNIT_ID_TAG);
                $libraryUnits = $this->businessMaterial->getContent($_controlNumber, $fieldId, $subFieldId, null, null, TRUE);
                if ($libraryUnits)
                {
                    foreach ($libraryUnits as $key => $val)
                    {
                        $libraryUnitId = $val[0];
                        if (!in_array($_controlNumber, $referenciados[$libraryUnitId]))
                        {
                            $referenciados[$libraryUnitId][] = $_controlNumber;
                        }
                    }
                }
            }
        }
        
        $divButtons = new MDiv("kardexControlDivButtons", $buttons);

        $tables     = null;
        $display    = 'block';
        foreach ($kardexUnits as $i => $content)
        {
            
            $table = new MTableRaw(_M("Kardex Infos", $this->module), null , null, "kardexControlTableRawT_$i");
            $table->setAlternate(true);
            $table->setWidth("100%");
            $table->setCellAttribute(0, 0, "width", "20%");
            $table->setCellAttribute(0, 1, "width", "80%");

            foreach($content as $subF => $conteudo)
            {
                $tagName = $this->businessTag->getTagName(MARC_KARDEX_FIELD, $subF);
                if(ereg(MARC_KARDEX_FIELD.".$subF", CATALOGUE_DATE_FIELDS))
                {
                    $conteudo = GnutecaDate::identifyDateMask($conteudo, GnutecaDate::getUserMask("DATE"));
                }
                else
                {
                    $value = $this->getContentDescription(MARC_KARDEX_FIELD.".$subF", $conteudo);
                    $conteudo = $value ?  $value : $conteudo;
                }

                $table->array[] = array($tagName, $conteudo);
            }
            
            
            //Collection info
            $colunas = 0;
            $detalhamento = null;
            foreach ($referenciados[$i] as $controlNumber)
            {
                list($f,$s) = explode(".", MARC_PERIODIC_INFORMATIONS);
                if(ereg ("(v\. [^,]*,)?( ?n\. [^,]*,)?( ?[^ ]* )?([0-9]{4})", $this->businessMaterial->getContent($controlNumber, $f, $s), $regs))
                {
                    $fasciculo[] = $regs;
    
                    $ano    = (int) trim($regs[4]);
                    $volume = trim(str_replace('v.', '', $regs[1]));
                    $numero = trim(str_replace('n.', '', $regs[2]));
    
                    $detalhamento[$ano][$volume][] = $numero;
    
                    $numCol = count($detalhamento[$ano][$volume]);
                    if ($numCol > $colunas)
                    {
                        $colunas = $numCol;
                    }
                }
            }
            $collectionTable = new MTableRaw(_M("Colection Infos", $this->module), null , array(_M('Year', $this->module), _M('Bulk', $this->module), _M('Number', $this->module)), "ColectionInfosTableRaw");
            $collectionTable->setAlternate(true);
            $collectionTable->setWidth("100%");    
            $collectionArray = null;
            $linha = 0;
            //Ordena por ano
            krsort($detalhamento);
            foreach ($detalhamento as $ano => $n1)
            {
                $collectionArray[$linha][0] = $ano;
    
                //Ordena por volume
                ksort($n1);
                foreach ($n1 as $volume => $n2)
                {
                    if ($ano == $anoOld) //Se tiver dois volumes no mesmo ano
                    {
                        //$linha++;
                        //$array[$linha][0] = $ano;
                    }
                    $anoOld = $ano;
    
                    $collectionArray[$linha][1].= $volume;
    
                    //Ordena por volume
                    sort($n2);
                    for ($x=0; $x < $colunas; $x++)
                    {
                        $collectionArray[$linha][2].= $n2[$x] ? $n2[$x] : '&nbsp;';
                    }
                }
    
                $linha ++;
            }
    
            $collectionTable->array = $collectionArray;
    
            $divX = new MDiv("noname", $collectionTable);

            $divTable[] = new MDiv("kardexControlTableRaw_$i", array($table, $collectionTable), null, array("style" => "display:$display;"));
            $display = 'none';
            $table = null;
        }

        $divs = array_merge(array($divButtons), $divTable);

        $this->addJsCode($this->getJsCode());

        $divKardex = new MDiv("divKardex", $divs, null, array("style" => "margin-top: 10px;"));

        $tablesGroup = new MDiv('tableKardesInfos', new MVContainer("tableKardesInfos", array($divKardex)), null, array('style' => 'overflow:auto'));

        $containerTagGroup = new MBaseGroup ("bgKardexInfos", null, null, 'vertical');
        $containerTagGroup->setAttribute    ('style', "display: block; border:0; ");
        $containerTagGroup->setBorder       (0);
        $containerTagGroup->addControl      ($tablesGroup);

        return array($containerTagGroup);
    }


    /**
     * Enter description here...
     *
     * @return unknown
     */
    function getWorkInfos()
    {
        $this->businessMaterial->clean();
        $this->businessMaterial->controlNumber = $this->controlNumber;
        $material = $this->businessMaterial->getMaterial(true);

        $table = new MTableRaw(_M("Work Infos", $this->module), null , null, 'tableWorkInfos');
        $table->setAlternate(true);
        $table->setCellAttribute(0, 0, "width", "40%");
        $table->setCellAttribute(0, 1, "width", "60%");
        $table->setWidth("100%");

        foreach($material as $content)
        {
            if(MARC_KARDEX_FIELD == $content[1])
            {
                continue;
            }

            $value = $this->getContentDescription("{$content[1]}.{$content[2]}", $content[6]);

            if(strlen($content[6]))
            {
                $v = ($value ? $value : $content[6]);

                if(strlen($content[9]))
                {
                    $suffix = $this->busPrefixSuffix->getPrefixSuffix($content[9]);
                    $v.= $suffix->content;
                }
                if(strlen($content[8]))
                {
                    $prefix = $this->busPrefixSuffix->getPrefixSuffix($content[8]);
                    $v = $prefix->content . $v;
                }

                $table->array[] = array("{$content[1]}.{$content[2]} - ".$this->businessTag->getTagName($content[1], $content[2]), $v);
            }
        }

        $div = new MDiv(null, $table, null, array('style' => 'max-height:250px;overflow:auto;'));

        $containerTagGroup = new MBaseGroup ("bgWorkInfos", null, null, 'vertical');
        $containerTagGroup->setAttribute    ('style', "display: block; border:0;");
        $containerTagGroup->setBorder       (0);
        $containerTagGroup->addControl      ($div);

        return array($containerTagGroup);
    }



    /**
     * Enter description here...
     *
     * @param unknown_type $tag
     * @param unknown_type $content
     * @return unknown
     */
    function getContentDescription($tag, $content)
    {
        if(!strlen($tag) || !strlen($content))
        {
            return false;
        }

        if($opts = $this->businessMaterial->relationOfFieldsWithTable($tag, $content, true))
        {
            return $opts;
        }

        return false;
    }



    /**
     * Enter description here...
     *
     * @return unknown
     */
    function getJsCode()
    {
        $code = " displayKardexControlDetailsInfo = function(divOK)
                    {
                        divs = document.getElementsByTagName('DIV');

                        for(x=0; x< divs.length; x++)
                        {
                            if(divs[x].id.indexOf('kardexControlTableRaw_') > -1 && divs[x].id != divOK)
                            {
                                divs[x].style.display = 'none';
                            }
                            else if(divs[x].id == divOK)
                            {
                                divs[x].style.display   = 'block';
                            }
                        }
                    }";

        $code.= "
                    imageMinusURL   = '{$this->imageMinusUrl}';
                    imagePlusURL    = '{$this->imagePlusUrl}';
                ";

        return $code;
    }

}
?>
