<?php
/**
 * InterchangeSearch form
 *
 * @author Moises Heberle [moises@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 Roberto Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 20/02/2009
 *
 * \b Organization: \n
 * SOLIS - Cooperativa de Solucoes Livres \n
 * The Gnuteca3 Development Team
 *
 * \b CopyLeft: \n
 * CopyLeft (L) 2009 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 FrmInterchangeSearch extends GnutecaForm
{
	public $MIOLO;
	public $module;
	public $break;

	public $busExemplaryControl;
	public $busInterchange;
	public $busInterchangeItem;
	public $busInterchangeType;
	public $busInterchangeStatus;
    public $busSearchFormat;
	public $busSupplierTypeAndLocation;

    public $mail;

    const BUTTONHEIGHT = '30px';


    public function __construct()
    {
    	$this->MIOLO  = MIOLO::getInstance();
    	$this->module = MIOLO::getCurrentModule();

        $this->MIOLO->getClass($this->module, 'GnutecaPDF');
        $this->MIOLO->getClass($this->module, 'rptInterchangeLetterSend');
        $this->MIOLO->getClass($this->module, 'GnutecaSendMail');
        $this->mail   = new GnutecaSendMail();

        $this->busExemplaryControl        = $this->MIOLO->getBusiness($this->module, 'BusExemplaryControl');
        $this->busInterchangeItem         = $this->MIOLO->getBusiness($this->module, 'BusInterchangeItem');
    	$this->busInterchangeType         = $this->MIOLO->getBusiness($this->module, 'BusInterchangeType');
    	$this->busInterchangeStatus       = $this->MIOLO->getBusiness($this->module, 'BusInterchangeStatus');
    	$this->busSearchFormat            = $this->MIOLO->getBusiness($this->module, 'BusSearchFormat');
    	$this->busSupplierTypeAndLocation = $this->MIOLO->getBusiness($this->module, 'BusSupplierTypeAndLocation');

        $this->setAllFunctions('Interchange', array('interchangeIdS', 'supplierIdS'));
        $this->busInterchange = $this->business; //define nome BusInterchange para padronizacao

        parent::__construct();
        if ( $this->primeiroAcessoAoForm() && strlen(MIOLO::_REQUEST('event')) == 0 )
        {
            $this->setFocus('interchangeIdS');
        }
        $this->page->addJsCode
        ("
            changeStatus = function()
            {
                miolo.doAjax('changeStatus', '', 'frm__mainForm');
            }
        ");
    }


    public function createFields()
    {
        $defaultTypeId = ($v = MIOLO::_REQUEST('interchangeTypeId')) ? $v : 1;

        $fields[] = new MTextField('interchangeIdS', NULL, _M('Code', $this->module), FIELD_ID_SIZE);
        $validators[] = new MIntegerValidator('interchangeIdS');

        $type = new GnutecaSelection('typeS', $defaultType, _M('Type', $this->module), $this->business->listTypes(), null, null, null, FALSE);
        $type->addAttribute('onchange', "miolo.doAjax('changeType', '', 'frm__mainForm')");
        $fields[] = $type;
        $fields[] = new MDiv('divSupplier', $this->getSupplierField($defaultType));

        //$fields[] = new GnutecaSelection('supplierIdS', null, _M('Supplier', $this->module), $this->busSupplierTypeAndLocation->listSupplierTypeAndLocation());
        $lblDate             = new MLabel(_M('Date', $this->module) . ':');
        $lblDate->setWidth(FIELD_LABEL_SIZE);
        $beginDateS     = new MCalendarField('beginDateS', $this->beginDateS->value, null, FIELD_DATE_SIZE, null, 'calendar-win2k-1');
        $endDateS       = new MCalendarField('endDateS', $this->endDateS->value, null, FIELD_DATE_SIZE, null, 'calendar-win2k-1');
        $fields[] = new MHContainer('hctDates', array($lblDate, $beginDateS, $endDateS));
        $interchangeTypeId = new GnutecaSelection('interchangeTypeIdS', NULL, _M('Interchange type', $this->module), $this->busInterchangeType->listInterchangeType(), null, null, null, FALSE);
        $interchangeTypeId->addAttribute('onchange', "changeStatus()");
        $interchangeTypeId->addAttribute('onkeydown', "changeStatus()");
        $fields[] = $interchangeTypeId;
        $fields[] = new MHContainer('status', array($this->getInterchangeStatusField($defaultTypeId)));
        $this->setFields($fields);
        $this->setValidators($validators);
    }


    public function changeStatus($sender)
    {
        $this->setResponse($this->getInterchangeStatusField($sender->interchangeTypeIdS), 'm_status');
        $this->break = TRUE;
    }


    public function getInterchangeStatusField($interchangeTypeId)
    {
    	$lblES = new MLabel( _M('Status', $this->module) . ':' );
    	$lblES->setWidth(FIELD_LABEL_SIZE);
        $interchangeStatusId = new GnutecaSelection('interchangeStatusIdS', null, null, $this->busInterchangeStatus->listInterchangeStatus($interchangeTypeId));
        $hct = new MHContainer('hctInterchangeStatus', array($lblES, $interchangeStatusId));
        $hct->addBoxStyle('width', '100%');
        return $hct;
    }


    public function changeType($sender)
    {
        $fields[] = $this->getSupplierField($sender->typeS);
        $this->setResponse($fields, 'divSupplier');
    }


    public function getSupplierField($type = NULL)
    {
       /* $lbl = new MLabel( _M('Supplier', $this->module) . ':' );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $supplierId = new GnutecaSelection('supplierIdS', null, NULL, $this->busSupplierTypeAndLocation->listSupplierTypeAndLocation($type), NULL, NULL, NULL, FALSE);
        $hct = new MHContainer('hctSupplier', array($lbl, $supplierId));
        $hct->addBoxStyle('width', '100%');
        return $hct;*/

        $lbl = new MLabel (_M('Supplier:',$this->module));
        $lbl->width = FIELD_LABEL_SIZE;
        $supplierIdS = new MLookupTextField ('supplierIdS','','',FIELD_LOOKUPFIELD_SIZE);
        $supplierIdS->setContext($this->module, $this->module, 'supplierType', 'filler', 'supplierIdS,supplierIdDescriptionS');
        $supplierIdS->baseModule = 'gnuteca3';
        $supplierIdDescriptionS = new MTextField ('supplierIdDescriptionS','',null, FIELD_DESCRIPTION_LOOKUP_SIZE);
        $supplierIdDescriptionS->setReadOnly(true);
        $supplierIdContainerS = new MHcontainer('supplierIdContainerS', array ($lbl, $supplierIdS, $supplierIdDescriptionS,));
        return $supplierIdContainerS;
    }



    /**
     * Enter description here...
     *
     */
    public function showSupplierInformation()
    {
        if ($this->break)
        {
            return;
        }
    	$ui = $this->MIOLO->getUI();
    	$frm = $ui->getForm($this->module, 'FrmSupplier', 'information');
        $frm->addBoxStyle('overflow', 'auto');
        $frm->setTitle(_M('Supplier information', $this->module));
        $frm->loadFields();

		foreach ($frm->fields as $i => &$f)
		{
            $f->setReadOnly(TRUE);
		}

    	parent::_showDetail($frm);
    }



    /**
     * Enter description here...
     *
     */
    public function generateLetterSend()
    {
    	if ($this->break || !MIOLO::_REQUEST('interchangeId'))
    	{
    		return;
    	}

    	$this->busInterchange->interchangeIdS = MIOLO::_REQUEST('interchangeId');
    	$result = $this->busInterchange->searchInterchange(TRUE);
    	$args->supplier                = $result[0];
    	$args->supplierTypeAndLocation = $this->busSupplierTypeAndLocation->getSupplierTypeAndLocationValueForm($args->supplier->supplierId, $args->supplier->type);

    	$report    = new rptInterchangeLetterSend($args);
        $content = strtr($report->readModelFile(), array(
            '$MATERIALS'        => str_replace("\n", "<br>", $this->getFormatedMaterials()),
        ));

        //FIXME Verificar se devera ser mantido estas variaveis
        //$gf = new GnutecaFunction();
        //$gf->setVariable('$CONTACT_NAME', $supplier->contact);
        //$gf->setVariable('$MATERIALS', $this->getFormatedMaterials());
        //$gf->interpret($content);

    	$fields[] = $editor = new MEditor('reportContent', $content, '510px', '320px');
    	$fields[] = new MSeparator();
        $fields[] = new MDiv('divErrors');
        $fields[] = new MHiddenField('enableEnter'); //Nao desabilitar ENTER do teclado

        //:btnLetterSend_generate
        //FIXME Feito uma trampa para receber o valor do MEditor, ajustar quando o componente for atualizado.
        $js = "dojo.byId('reportContent').value = dijit.byId('reportContent_editor').getValue(false);
               miolo.doAjax('btnLetterSend_generate', '', 'frm__mainForm');";
        $btn = new MButton('btnGenerate', _M('Generate PDF', $this->module), $js, $this->MIOLO->getUI()->getImage($this->module, 'document-16x16.png'));
        $btn->addStyle('height', self::BUTTONHEIGHT);
        $btn->addStyle('margin-left', '85px');
        $btn->addStyle('margin-bottom', '-54px');
        $fields[] = $btn;

    	$this->setTitle(_M('Generate letter send', $this->module));
    	$this->setFields($fields, FALSE);
        parent::_showDetail($this);
    }



    /**
     * Enter description here...
     *
     * @param unknown_type $args
     */
    public function btnLetterSend_generate($args)
    {
        if ($this->break)
        {
            return;
        }
    	if (!$args->reportContent)
    	{
    		$errors[] = _M('The field "@1" is required.', $this->module, _M('Content', $this->module));
    	}
        $this->break = TRUE;

        $this->business->getInterchange( MIOLO::_REQUEST('interchangeId') );
        $supplier = $this->busSupplierTypeAndLocation->getSupplierTypeAndLocationValueForm( $this->business->supplierId, $this->business->type );

    	if (!$errors)
    	{
            //Generate PDF
            $args->supplier = $supplier;
            $report         = new rptInterchangeLetterSend($args);
            if ($report->generate())
            {
                $url  = $report->getDownloadURL();
                $link = new MLink('lnkDownload', _M('Click here', $this->module), $url, null, '_blank');
                $args->message  = _M("Arquivo gerado. @1 para fazer o download", $this->module, $link->generate());
                $args->message .= '<br><br>' . _M('Mudar para o estado Carta Enviada?', $this->module);
                $args->changeStatusIdTo = INTERCHANGE_STATUS_LETTER_SENT;
                $this->confirm($args);
                //$this->information(_M('File generated. Click on OK button to download', $this->module), "javascript:window.open('{$url}'); miolo.doAjax('btnLetterSend_changeStatus', '', 'frm__mainForm')", null, true);
                //$this->page->onload("dojo.byId('btnClose').setAttribute('onclick', 'gnuteca.searchAction(); gnuteca.closeAction()')");
            }
            else
            {
                $errors[] = _M('Error to generate report', $this->module);
            }
    	}

        if ($errors)
        {
            $m = new GnutecaMessages();
            foreach ($errors as $error)
            {
                $m->addError($error);
            }
            $this->setResponse($m->getMessagesTableRaw(), 'divErrors');
        }
    }

    public function btnLetterSend_changeStatus()
    {
        $interchangeId = MIOLO::_REQUEST('interchangeId');
        if ($this->break || !$interchangeId)
        {
            return;
        }
        $this->break = true;

        //Define estado como CARTA ENVIADA
        $this->business->getInterchange( $interchangeId );
        $this->business->interchangeStatusId = INTERCHANGE_STATUS_LETTER_SENT;
        $this->business->updateInterchange();

        $this->setResponse(null, 'divResponse');
    }



    /**
     * Enter description here...
     *
     * @param unknown_type $args
     */
    public function sendMail($args)
    {
        if ($this->break)
        {
            return;
        }

        //Define se é para abrir janela de detalhes do e-mail
        if (MUtil::getBooleanValue(INTERCHANGE_MAIL_RECEIPT_AUTOSEND) == TRUE) //Auto send mail
        {
            $this->sendReceiptMail();
            return;
        }

        $cnt = new MMultiLineField('content', INTERCHANGE_MAIL_RECEIPT_CONTENT, _M('Content', $this->module), NULL, 15, 50);
        $fields[] = $cnt;

        $fields[] = new MHiddenField('enableEnter'); //Enable ENTER keyboard
        $fields[] = new MSeparator();
        $fields[] = new MDiv('divMessages');

        $btn = new MButton('btnSend', _M('Send', $this->module), ':sendReceiptMail', $this->MIOLO->getUI()->getImage($this->module, 'save-16x16.png'));
        $btn->addStyle('height', self::BUTTONHEIGHT);
        $btn->addStyle('margin-left', '85px');
        $btn->addStyle('margin-bottom', '-54px');
        $fields[] = $btn;

        $this->setTitle(_M('Send mail interchange', $this->module));
        $this->setFields($fields, FALSE);
        parent::_showDetail($this);
    }



    /**
     * Enter description here...
     *
     * @param unknown_type $args
     */
    public function sendReceiptMail($args = NULL)
    {
    	$this->break = TRUE;
        $result = $this->mail->sendMailToSupplierInterchengeReceipt(MIOLO::_REQUEST('interchangeId'), $this->getFormatedMaterials(), $args->content);

        switch ($result)
        {
        	case 1:
                $this->error(_M('The email of the supplier not found.', $this->module), $this->getGotoCurrentActionAndSearchEventUrl());
                return false;

        	case 2:
                $this->error(_M('Error when send mail to @1', $this->module, $this->mail->mailTo), $this->getGotoCurrentActionAndSearchEventUrl());
                return false;

        	default:
                $args->message  = _M('Email was sent with sucess to supplier', $this->module) . " ({$this->mail->mailTo}).";
                $args->message .= '<br>' . _M('Gostaria de alterar o estado para @1?', $this->module, '<b>' . _M('Agradecido', $this->module) . '</b>');
                $args->changeStatusIdTo = INTERCHANGE_STATUS_GRATEFUL;
                $this->confirm($args);
                //$this->information(_M('Email was sent with sucess to supplier', $this->module) . " ({$this->mail->mailTo})", $this->getGotoCurrentActionAndSearchEventUrl());
                return true;

        }
    }



    /**
     * Enter description here...
     *
     * @return unknown
     */
    public function getFormatedMaterials()
    {
//        $this->busInterchangeItem->interchangeIdS = $this->business->interchangeId;
        $id = $this->business->getInterchange( MIOLO::_REQUEST('interchangeId') );
        $this->busInterchangeItem->interchangeIdS = $id->interchangeId;
        $search = $this->busInterchangeItem->searchInterchangeItem(TRUE);
        $materials = array();
        if ($search)
        {
            foreach ($search as $s)
            {
                $materials[] = $this->busSearchFormat->getFormatedString($s->controlNumber, INTERCHANGE_SEARCH_FORMAT_ID);
            }
        }
        return strip_tags(implode("\n", $materials));
    }

    public function confirm($args = null)
    {
        if ($this->break && !$args->message)
        {
            return;
        }

        $msg              = $args->message ? $args->message : _M('Really confirm?', $this->module);
        $event            = 'confirm_finish';
        $changeStatusIdTo = $args->changeStatusIdTo ? $args->changeStatusIdTo : INTERCHANGE_STATUS_CONFIRMED;
        $interchangeId    = MIOLO::_REQUEST('interchangeId');

        $gotoYes = $this->MIOLO->getActionURL($this->module, $this->action, null, compact('event', 'interchangeId', 'changeStatusIdTo'));
        $this->question($msg, $gotoYes);
    }

    public function confirm_finish()
    {
        $interchangeId    = MIOLO::_REQUEST('interchangeId');
        $changeStatusIdTo = MIOLO::_REQUEST('changeStatusIdTo');
        $mensage = $changeStatusIdTo == INTERCHANGE_STATUS_LETTER_SENT ? _M('Carta enviada') : _M('Confirmado');
        if ($interchangeId && $changeStatusIdTo && $this->business->updateStatus($interchangeId, $changeStatusIdTo))
        {
            $this->information(_M('@1 com sucesso', $this->module, $mensage), $this->getGotoCurrentActionAndSearchEventUrl());
        }
        else
        {
            $this->error(_M(MSG_RECORD_ERROR, $this->module), null, null, null, true);
        }
    }
}
?>
