<?php
/**
 * SystemPreferenceForm
 *
 * @version    7.6
 * @package    control
 * @subpackage admin
 * @author     Pablo Dall'Oglio
 * @copyright  Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
 * @license    https://adiantiframework.com.br/license-template
 */
class ConfigForm extends TStandardForm
{
    protected $form; // formulário

    /**
     * método construtor
     * Cria a página e o formulário de cadastro
     */
    function __construct()
    {
        parent::__construct();

        $this->setDatabase('unit_database');
        $this->setActiveRecord('config');

        // cria o formulário
        $this->form = new BootstrapFormBuilder('form_config');
        $this->form->setFormTitle('Configuração');

        // cria os campos do formulário
        $titulo          = new TEntry('titulo');
        $pagamento       = new TDateTime('pagamento');
        $equips          = new TEntry('equips');
        $txcard1         = new TEntry('txcard1');
        $txcard2         = new TEntry('txcard2');
        $txcard3         = new TEntry('txcard3');
        $txcard4         = new TEntry('txcard4');
        $semana          = new TCombo('semana');
        $socios          = new TEntry('socios');
        $passacaixa      = new TCombo('passacaixa');
        $valesclientes   = new TCombo('valesclientes');
        $contasatendente = new TCombo('contasatendente');
        $limitepagamento = new TEntry('LimitePagamento');
        $qtdecxant       = new TEntry('QtdeCxAnt');
        $atecredval      = new TCombo('AteCredVal');
        $usafoto         = new TCombo('UsaFoto');

        $yesno = array();
        $yesno['1'] = _t('Yes');
        $yesno['0'] = _t('No');
        $passacaixa->addItems($yesno);
        $valesclientes->addItems($yesno);
        $contasatendente->addItems($yesno);
        $usafoto->addItems($yesno);

        $yesno = array();
        $yesno['0'] = 'Valor';
        $yesno['1'] = 'Crédito';
        $atecredval->addItems($yesno);

        $dias_semana = array(0=>'Domingo',1=>'Segunda',2=>'Terça',3=>'Quarta',4=>'Quinta',5=>'Sexta',6=>'Sábado');
        $semana->addItems($dias_semana);

        $this->form->addFields( [new TLabel('Título')], [$titulo],[new TLabel('Vencimento Mensalidade')], [$pagamento] );
        $this->form->addFields( [new TLabel('Equipamentos')], [$equips],[new TLabel('Qtde Sócios')], [$socios] );
        $this->form->addFields( [new TLabel('Taxa Cartão 1')], [$txcard1],
                                [new TLabel('Taxa Cartão 2')], [$txcard2]);
        $this->form->addFields( [new TLabel('Taxa Cartão 3')], [$txcard3],
                                [new TLabel('Taxa Cartão 4')], [$txcard4] );
        $this->form->addFields( [new TLabel('Início da Semana')], [$semana],[new TLabel('Qtde de Cx Anteriores')], [$qtdecxant] );
        $this->form->addFields( [new TLabel('Usa Passa Caixa')], [$passacaixa],[new TLabel('Usa Vales Clientes')], [$valesclientes] );
        $this->form->addFields( [new TLabel('Mostra Conta Atendentes')], [$contasatendente],[new TLabel('Limite de Pagamento')], [$limitepagamento] );
        $this->form->addFields( [new TLabel('Atendente Crédito/Valor')], [$atecredval],
                                [new TLabel('Usa Foto Leitura')], [$usafoto] );

        $titulo->setSize('50%');
        $pagamento->setSize('50%');
        $equips->setSize('50%');
        $txcard1->setSize('50%');
        $txcard2->setSize('50%');
        $txcard3->setSize('50%');
        $txcard4->setSize('50%');
        $semana->setSize('50%');
        $socios->setSize('50%');
        $passacaixa->setSize('50%');
        $valesclientes->setSize('50%');
        $contasatendente->setSize('50%');
        $limitepagamento->setSize('50%');
        $qtdecxant->setSize('50%');
        $atecredval->setSize('50%');
        $usafoto->setSize('50%');


        $btn = $this->form->addAction(_t('Save'), new TAction(array($this, 'onSave')), 'far:save');
        $btn->class = 'btn btn-sm btn-primary';

        $container = new TVBox;
        $container->{'style'} = 'width: 100%;';
        $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $container->add($this->form);
        parent::add($container);
    }

    /**
     * Carrega o formulário de preferências
     */
    function onEdit($param)
    {
        try
        {
            // open a transaction with database
            TTransaction::open($this->database);

            $preferences = config::getAllConfigs();
            if ($preferences)
            {
                $this->form->setData((object) $preferences);
            }

            // close the transaction
            TTransaction::close();
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * method onSave()
     * Executed whenever the user clicks at the save button
     */
    function onSave()
    {
        try
        {
            // open a transaction with database
            TTransaction::open($this->database);

            // get the form data
            $data = $this->form->getData();
            $data_array = (array) $data;

            foreach ($data_array as $property => $value)
            {
                $object = new config;
                $object->{'id'}    = $property;
                $object->{'value'} = $value;
                $object->store();
            }

            // fill the form with the active record data
            $this->form->setData($data);

            // close the transaction
            TTransaction::close();

            // shows the success message
            TToast::show('success', 'Configurações Atualizadas', 'top right', 'far:check-circle' );
            // reload the listing
        }
        catch (Exception $e) // in case of exception
        {
            // get the form data
            $object = $this->form->getData($this->activeRecord);

            // fill the form with the active record data
            $this->form->setData($object);

            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }
}
