<?php

namespace Softsat\Locacao\Controller\Admin;

use Hwapx\Admin\Controller\Admin\Admin;
use Hwapx\Core\Library\Template;
use Hwapx\Core\Library\Validator;
use HwapX\Admin\Library\Builder\TableBuilder;
use HwapX\Admin\Library\Builder\FormBuilder;
use HwapX\Core\Library\DB\SQL\Mapper;

use Softsat\Locacao\Model\Relatorio AS RelatorioModel;

class Relatorio extends Admin {
    protected $validator = null;
    protected $mapper    = null;
    protected $form = array(
        'name'   => 'Marca',
        'table'  => 'softsat_locacao_admin_relatorio',
        'depends'=> array(
            'softsat_locacao_veiculo' => array(
                'name' => 'Veículos',
                'foreignkey' => 'marca_id'
            ),
        ),
        'fields' =>  array(
            'nome' => array(
                'label' => 'Nome',
                'type'  => 'text',
                'width' => 12,
                'rules' => array(
                    'required'
                )
            ),
        )
    );

    public function __construct($f3) {
        parent::__construct($f3);
    }

    public function index($f3) {
        $this->module->checkRole('softsat.locacao.relatorio');

        $db   = $f3->get('db');

        $data = array(
            'marcas'       => $db->exec('SELECT * FROM softsat_locacao_marca'),
            'grupos'       => $db->exec('SELECT * FROM softsat_locacao_grupo'),
            'veiculos'     => $db->exec('SELECT * FROM softsat_locacao_veiculo_detalhe'),
            'plano_contas' => $db->exec('SELECT * FROM softsat_locacao_plano_conta ORDER BY conta'),
        );
        
        echo Template::instance()->render('softsat/locacao/relatorio/form.html', null, $data);
    }

    public function pdf($f3) {
        $this->module->checkRole('softsat.locacao.relatorio');

        $model = new RelatorioModel($f3);

        if($f3->get('POST.detalhe') == 'resumo') {
            $data  = $model->faturamentoResumoPdf($f3->get('POST'));
        } elseif($f3->get('POST.detalhe') == 'detalhe') {
            $data  = $model->faturamentoDetalhePdf($f3->get('POST'));
        } elseif($f3->get('POST.detalhe') == 'veiculo_plano') {
            $data  = $model->faturamentoVeiculoPlanoPdf($f3->get('POST'));
        } elseif($f3->get('POST.detalhe') == 'plano_veiculo') {
            $data  = $model->faturamentoPlanoVeiculoPdf($f3->get('POST'));
        } else {
            $f3->error(404);
        }

        if(!$data) {
            $this->f3->error(404);
            return;
        }

        header('content-type: application/pdf');
        echo $data;
    }
}
