<?php
namespace src\handlers;

use \core\Controller;
use \src\controllers\UtilsController;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\models\Bills_to_pay;
use \src\models\City;
use \src\models\Client;
use \src\models\Purchase;
use \src\models\Product;
use \src\models\Provider;

class ReportsHandler extends Controller {
	private $loggedUser;    
    private $paramsName;

	public function __construct()
    {
        $this->loggedUser = LoginHandler::checkLogin();

        if ($this->loggedUser == false) {
            $this->redirect('/login');
        }

        $this->paramsName = PermissionHandler::getPermissions($this->loggedUser->group);

        if (!in_array('reports_view', $this->paramsName)) {
            $this->redirect('/');
        }
    }

    // Geração de relatórios de clientes PDF/EXCEL
	public function prepareClientPdf($clientsList, $headerInfo) {
		$generalInfo = self::breakLines($headerInfo['other_information']);
		$clientsRows = self::prepareClientToShow($clientsList);

        $headHtml = self::getHeadHtml('Relatório de Clientes - Supporte Agronegócios');
		$footer = self::getFooter();

		$contentBody = '
        <html>
            '.$headHtml.'
            <body>

                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Cliente(s)</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Status</td>
                            <td scope="col">Classe</td>
                            <td scope="col">Tipo</td>
                            <td scope="col">Nome do Cliente</td>
                            <td scope="col">Nome do Responsável</td>
                            <td scope="col">Fone Contato</td>
                            <td scope="col">Cidade-UF</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$clientsRows.'
                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
	}

    private static function prepareClientToShow($parameters) {
        $table = array();
        $response = '';

        foreach($parameters as $key => $client) {
        	$city_name = City::getName($client['city']);

            $status = ($client["status"] == 1)?'Ativo':'Inativo';
            $type = ($client["type"] == 1)?"PF":"PJ";

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$client["classification"].'</td>';
            $table[$key] .= '<td>'.$type.'</td>';
            $table[$key] .= '<td>'.$client["name"].'</td>';
            $table[$key] .= '<td>'.$client["buyer"].'</td>';
            $table[$key] .= '<td>'.$client["first_phone"].'</td>';
            $table[$key] .= '<td>'.$city_name.'-'.$client["state"].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareClientCsv($clients) {
    	$clientsData = array();

    	foreach ($clients as $key => $client) {    		
    		$clientsData[$key]['item'] = ($key + 1);
    		$clientsData[$key]['status'] = ($client["status"] == 1)?'Ativo':'Inativo';
    		$clientsData[$key]['classification'] = $client['classification'];
    		$clientsData[$key]['type'] = ($client["type"] == 1)?'PF':'PJ';
    		$clientsData[$key]['name'] = mb_convert_encoding($client["name"], 'ISO-8859-1');
    		$clientsData[$key]['buyer'] = mb_convert_encoding($client["buyer"], 'ISO-8859-1');
    		$clientsData[$key]['first_phone'] = $client["first_phone"];
    		$clientsData[$key]['location'] = mb_convert_encoding(City::getName($client['city']), 'ISO-8859-1').'-'.$client["state"];
    	}

    	return $clientsData;
    }
    // Fim Geração de relatórios de clientes PDF/EXCEL


    // Geração de relatórios de Fazendas PDF/EXCEL
    public function prepareFarmPdf($farmsList, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $farmsRows = self::prepareFarmsToShow($farmsList);
        
        $headHtml = self::getHeadHtml('Relatório de Fazendas - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Fazendas por Cliente(s)</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Status</td>
                            <td scope="col">Cliente</td>
                            <td scope="col">Fazenda</td>
                            <td scope="col">Inscrição Estadual</td>
                            <td scope="col">Responsável na Fazenda</td>
                            <td scope="col">Fone resp na Fazenda</td>
                            <td scope="col">Cidade-UF</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$farmsRows.'
                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareFarmsToShow($parameters) {
        $table = array();
        $response = '';

        foreach($parameters as $key => $farm) {
            $city_name = City::getName($farm['city']);
            $client_name = Client::getName($farm['id_client']);

            $status = ($farm["status"] == 1)?'Ativo':'Inativo';

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$client_name.'</td>';
            $table[$key] .= '<td>'.$farm["name"].'</td>';
            $table[$key] .= '<td>'.$farm['state_registration'].'</td>';            
            $table[$key] .= '<td>'.$farm["responsible"].'</td>';
            $table[$key] .= '<td>'.$farm["phone"].'</td>';            
            $table[$key] .= '<td>'.$city_name.'-'.$farm["state"].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareFarmsCsv($farms) {
        $farmsData = array();

        foreach ($farms as $key => $farm) {         
            $farmsData[$key]['item'] = ($key + 1);
            $farmsData[$key]['status'] = ($farm["status"] == 1)?'Ativo':'Inativo';
            $farmsData[$key]['client_name'] = mb_convert_encoding(Client::getName($farm['id_client']), 'ISO-8859-1');
            $farmsData[$key]['name'] = mb_convert_encoding($farm["name"], 'ISO-8859-1');
            $farmsData[$key]['state_registration'] = mb_convert_encoding($farm["state_registration"], 'ISO-8859-1');
            $farmsData[$key]['responsible'] = mb_convert_encoding($farm["responsible"], 'ISO-8859-1');            
            $farmsData[$key]['phone'] = $farm["phone"];
            $farmsData[$key]['location'] = mb_convert_encoding(City::getName($farm['city']), 'ISO-8859-1').'-'.$farm["state"];
        }

        return $farmsData;
    }
    // Fim Geração de relatórios de Fazendas PDF/EXCEL

    // Geração de relatórios de Produtos por Fornecedor PDF/EXCEL
    public function prepareProductsPdf($productsList, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $productsRows = self::prepareProductsToPdf($productsList);
        
        $headHtml = self::getHeadHtml('Relatório de Produtos por Fornecedor(es) - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Produtos por Fornecedor(es)</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col" style="width:100px;">Status do Fornecedor</td>
                            <td scope="col">Fornecedor</td>
                            <td scope="col">Cidade-UF</td>
                            <td scope="col">Grupo de Produto</td>
                            <td scope="col" style="width:100px;">Status do Produto</td>
                            <td scope="col">Produto</td>
                            <td scope="col">Estoque</td>
                            <td scope="col">Custo R$</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$productsRows.'
                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareProductsToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters as $key => $product) {
            $status = ($product["status"] == 1)?'Ativo':'Inativo';

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$product['provider_status'].'</td>';
            $table[$key] .= '<td>'.$product['provider_name'].'</td>';
            $table[$key] .= '<td>'.$product["provider_location"].'</td>';
            $table[$key] .= '<td>'.$product['group_product']['name'].'</td>';            
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$product["name"].'</td>';
            $table[$key] .= '<td>'.$product["amount"].'</td>';
            $table[$key] .= '<td>'.$product['cost_price'].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareProductsCsv($products) {
        $productsData = array();

        foreach ($products as $key => $product) {
            $productsData[$key]['item'] = ($key + 1);
            $productsData[$key]['provider_status'] = $product['provider_status'];
            $productsData[$key]['provider_name'] = mb_convert_encoding($product['provider_name'], 'ISO-8859-1');
            $productsData[$key]['provider_location'] = mb_convert_encoding($product["provider_location"], 'ISO-8859-1');
            $productsData[$key]['group_product'] = mb_convert_encoding($product['group_product']['name'], 'ISO-8859-1');
            $productsData[$key]['status'] = ($product["status"] == 1)?'Ativo':'Inativo';
            $productsData[$key]['name'] = mb_convert_encoding($product["name"], 'ISO-8859-1');
            $productsData[$key]['amount'] = $product["amount"];
            $productsData[$key]['cost_price'] = $product['cost_price'];
        }

        return $productsData;
    }
    // Fim Geração de relatórios de Produtos por Fornecedor PDF/EXCEL


    // Geração de relatórios de Compras PDF/EXCEL
    public function preparePurchasesPdf($productsList, $headerInfo, $title) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        
        $headTable = self::getHeadReportPurchase($productsList['type']);
        $headHtml = self::getHeadHtml($title);
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>'.$title.'</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>                        
                        '.$headTable['pdf'].'
                    </thead>
                    <tbody>
                        '.$productsList['body'].'
                        <tr>
                            <td style="text-align:right;" '.$productsList['colspan'].'>'.$productsList['total_title'].'<strong> '.$productsList['total'].'</strong></td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    public function preparePurchasesCsv($purchases, $by) {
        $purchaseData = array();

        if($by == 'provider') {

            foreach ($purchases as $key => $item) {
                $items = Purchase::getProductsPurchase($item['id']);
                $productGroup = Product::getProductGroup($items[0]['id_product_group']);
                
                $purchaseData[$key]['item'] = ($key + 1);
                $purchaseData[$key]['provider_name'] = mb_convert_encoding(Provider::getProviderName($item['id_provider']), 'ISO-8859-1');
                $purchaseData[$key]['payment_form'] = mb_convert_encoding(Bills_to_pay::getPaymentForm($item['id_payment_form']), 'ISO-8859-1');
                $purchaseData[$key]['product_group'] = $productGroup['name'];
                $purchaseData[$key]['release_date'] = UtilsController::convertDate($item['release_date']);
                $purchaseData[$key]['note_number'] = $item['note_number'];
                $purchaseData[$key]['total_amount'] = UtilsController::convertToRealBr($item['total_amount']);                
            }

        } else {

            foreach ($purchases as $key => $item) {
                $items = Purchase::getProductsPurchase($item['id']);
                $productGroup = Product::getProductGroup($items[0]['id_product_group']);
                
                $purchaseData[$key]['item'] = ($key + 1);
                $purchaseData[$key]['product_group'] = $productGroup['name'];
                $purchaseData[$key]['payment_form'] = mb_convert_encoding(Bills_to_pay::getPaymentForm($item['id_payment_form']), 'ISO-8859-1');
                $purchaseData[$key]['product_name'] = mb_convert_encoding(Product::getName($items[0]['id_product']), 'ISO-8859-1');
                $purchaseData[$key]['provider_name'] = mb_convert_encoding(Provider::getProviderName($item['id_provider']), 'ISO-8859-1');
                $purchaseData[$key]['release_date'] = UtilsController::convertDate($item['release_date']);
                $purchaseData[$key]['note_number'] = $item['note_number'];
                $purchaseData[$key]['total_amount'] = UtilsController::convertToRealBr($item['total_amount']);                
            }
        }

        return $purchaseData;
    }


    public static function getHeadReportPurchase($type) {
        $response = array();

        if($type == 1) {
            $response['pdf'] = '
            <tr>
                <td scope="col">Item</td>
                <td scope="col">Fornecedor</td>
                <td scope="col">Orig. Pag</td>
                <td scope="col">Grupo de produto</td>
                <td scope="col">Data de compra</td>
                <td scope="col">Nr Nota</td>
                <td scope="col" style="width:150px;">Valor Total da Compra-Nota R$</td>
            </tr>
            ';

            $response['csv'] = [
            'Item',
            'Fornecedor',
            'Orig. Pag',
            'Grupo de produto',
            'Data de compra',
            'Nr Nota',
            'Valor Total da Compra-Nota R$'
            ];

        } elseif($type == 2) {
            $response['pdf'] = '
            <tr>
                <td scope="col">Item</td>
                <td scope="col">Grupo de Produto</td>
                <td scope="col">Orig. Pag</td>
                <td scope="col">Produto</td>
                <td scope="col">Fornecedor</td>
                <td scope="col">Data da Compra</td>
                <td scope="col">Nr Nota</td>
                <td scope="col">Valor do item da Compra R$</td>
            </tr>
            ';

            $response['csv'] = [
            'Item',
            'Grupo de Produto',
            'Orig. Pag',
            'Produto',
            'Fornecedor',
            'Data da Compra',
            'Nr Nota',
            'Valor do item da Compra R$'
            ];
        }

        return $response;
    }
    // Fim Geração de relatórios de Compras PDF/EXCEL

    // Geração de relatórios de Aniversariantes PDF/EXCEL
    public function prepareBirthdaysPdf($dataBirthdays, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $birthdaysRows = self::prepareBirthdaysToPdf($dataBirthdays);
        
        $headHtml = self::getHeadHtml('Relatório de Aniversariantes - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Aniversariantes</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Data do aniversário</td>
                            <td scope="col">Nome</td>
                            <td scope="col">Módulo</td>
                            <td scope="col">Status</td>
                            <td scope="col">Fone de contato</td>
                            <td scope="col">E-mail</td>
                            <td scope="col">Cidade-UF</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$birthdaysRows.'
                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareBirthdaysToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters['result'] as $key => $birtdays) {
            $status = ($birtdays["status"] == 1)?'Ativo':'Inativo';
            $model = (isset($birtdays['model']))?$birtdays['model']:$parameters['model'];

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$birtdays['birth_date'].'</td>';
            $table[$key] .= '<td>'.$birtdays['name'].'</td>';
            $table[$key] .= '<td>'.$model.'</td>';
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$birtdays["first_phone"].'</td>';
            $table[$key] .= '<td>'.$birtdays["email"].'</td>';
            $table[$key] .= '<td>'.$birtdays['city'] .'-'. $birtdays['state'].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareBirthdaysToCsv($birtdays) {
        $birthdaysData = array();

        foreach ($birtdays['result'] as $key => $item) {
            $status = ($item["status"] == 1)?'Ativo':'Inativo';
            $model = (isset($item['model']))?$item['model']:$birtdays['model'];
            $location = (!empty($item['city']))?mb_convert_encoding($item['city'], 'ISO-8859-1') .'-'. $item['state']:'';
            
            $birthdaysData[$key]['item'] = ($key + 1);
            $birthdaysData[$key]['birth_date'] = $item['birth_date'];
            $birthdaysData[$key]['name'] = mb_convert_encoding($item['name'], 'ISO-8859-1');
            $birthdaysData[$key]['model'] = mb_convert_encoding($model, 'ISO-8859-1');
            $birthdaysData[$key]['status'] = $status;
            $birthdaysData[$key]['first_phone'] = $item['first_phone'];
            $birthdaysData[$key]['email'] = $item['email'];
            $birthdaysData[$key]['location'] = $location;
        }

        return $birthdaysData;
    }
    // Fim Geração de relatórios de Aniversariantes PDF/EXCEL

    // Geração de relatórios de pedidos PDF/EXCEL
    public function prepareRequestsPdf($requestsContent, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $requestsRows = self::prepareRequestsToPdf($requestsContent);
        
        $headHtml = self::getHeadHtml('Relatório de Pedido(s) - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Pedido(s)</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Data</td>
                            <td scope="col">Nº</td>
                            <td scope="col">Status do Pedido</td>
                            <td scope="col">Cliente</td>
                            <td scope="col">Fornecedor</td>
                            <td scope="col">Produto de item</td>
                            <td scope="col">Vendedor intermediário</td>
                            <td scope="col">Peso</td>
                            <td scope="col">Saldo</td>
                            <td scope="col">Total do Pedido</td>
                            <td scope="col" style="width: 60px!important;">Resultado Estimado</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$requestsRows.'

                        <tr>
                            <td style="text-align:right;" colspan="12">Total em R$ de Pedidos: R$<strong> '.UtilsController::convertToRealBr($requestsContent['total_requests']).'</strong></td>
                        </tr>

                        <tr>
                            <td style="text-align:right;" colspan="12">Resultado estimado: R$<strong> '.UtilsController::convertToRealBr($requestsContent['total_estimative']).'</strong></td>
                        </tr>

                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareRequestsToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters['data'] as $key => $request) {
            $salesman = (!empty($request['salesman_name']))?$request['salesman_name']:'Supporte Agro';
            $created = date('d/m/Y', strtotime($request['date_created']));

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$created.'</td>';
            $table[$key] .= '<td>'.$request['id'].'</td>';
            $table[$key] .= '<td>'.$request['status_name'].'</td>';
            $table[$key] .= '<td>'.$request['client'].'</td>';
            $table[$key] .= '<td>'.$request["provider_name"].'</td>';
            $table[$key] .= '<td>'.$request["product"]['name'].'</td>';
            $table[$key] .= '<td>'.$salesman.'</td>';
            $table[$key] .= '<td>'.number_format($request['amount'], 2).'</td>';
            $table[$key] .= '<td>'.number_format($request['balance'], 2).'</td>';
            $table[$key] .= '<td>'.UtilsController::convertToRealBr($request["total"]).'</td>';
            $table[$key] .= '<td>'.UtilsController::convertToRealBr($request["estimative_real"]).'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareRequestsCsv($parameters) {
        $requestsData = array();

        foreach ($parameters['data'] as $key => $item) {
            $salesman = (!empty($item['salesman_name']))?mb_convert_encoding($item['salesman_name'], 'ISO-8859-1'):'Supporte Agro';
            $created = date('d/m/Y', strtotime($item['date_created']));
            
            $requestsData[$key]['item'] = ($key + 1);
            $requestsData[$key]['date_created'] = $created;
            $requestsData[$key]['request_id'] = $item['id'];
            $requestsData[$key]['status_name'] = $item['status_name'];
            $requestsData[$key]['client'] = mb_convert_encoding($item['client'], 'ISO-8859-1');
            $requestsData[$key]['provider_name'] = mb_convert_encoding($item['provider_name'], 'ISO-8859-1');
            $requestsData[$key]['product_name'] = mb_convert_encoding($item['product']['name'], 'ISO-8859-1');
            $requestsData[$key]['salesman'] = $salesman;
            $requestsData[$key]['amount'] = number_format($item['amount'], 2);
            $requestsData[$key]['balance'] = number_format($item['balance'], 2);
            $requestsData[$key]['total'] = UtilsController::convertToRealBr($item["total"]);
            $requestsData[$key]['estimative_real'] = UtilsController::convertToRealBr($item["estimative_real"]);
        }

        return $requestsData;
    }
    // Fim Geração de relatórios de pedidos PDF/EXCEL

    // Geração de relatórios de entregas PDF/EXCEL
    public function prepareDeliveiresPdf($deliveriesContent, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $deliveriesRows = self::prepareDeliveriesToPdf($deliveriesContent);
        
        $headHtml = self::getHeadHtml('Relatório de Entregas - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Entregas</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Dt da Entrega</td>
                            <td scope="col">Situação da entrega</td>
                            <td scope="col">Nr do pedido</td>
                            <td scope="col">Nr da entrega</td>
                            <td scope="col">Fornecedor</td>
                            <td scope="col">Cliente</th>d               
                            <td scope="col">Produto</td>
                            <td scope="col">Transportadora</td>
                            <td scope="col">Qtde</td>
                            <td scope="col">Nº Documento</td>
                            <td scope="col" style="width: 160px!important;">Valor da entrega R$</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$deliveriesRows.'

                        <tr>
                            <td style="text-align:right;" colspan="12">Soma das Quantides:<strong> '.UtilsController::convertToRealBr($deliveriesContent['total_balance']).'</strong></td>
                        </tr>

                        <tr>
                            <td style="text-align:right;" colspan="12">Soma Valor de Entrega: R$<strong> '.UtilsController::convertToRealBr($deliveriesContent['total_vdelivery']).'</strong></td>
                        </tr>

                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareDeliveriesToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters['result'] as $key => $deliverie) {
            $amount = (!empty($deliverie['amount_balance']))?$deliverie['amount_balance']:$deliverie['amount'];
            $value = (!empty($deliverie['value_delivery_balance']))?$deliverie['value_delivery_balance']:$deliverie['value_delivery'];

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.UtilsController::convertDate($deliverie['date_deliverie']).'</td>';
            $table[$key] .= '<td>'.$deliverie['situation_name'].'</td>';
            $table[$key] .= '<td>'.$deliverie['deliveryInfo']['id_request'].'</td>';
            $table[$key] .= '<td>'.$deliverie['delivery_number'].'</td>';
            $table[$key] .= '<td>'.$deliverie["provider"].'</td>';
            $table[$key] .= '<td>'.$deliverie["client"].'</td>';
            $table[$key] .= '<td>'.$deliverie["product"].'</td>';
            $table[$key] .= '<td>'.$deliverie["shipping_company"].'</td>';
            $table[$key] .= '<td>'.$amount.'</td>';
            $table[$key] .= '<td>'.$deliverie["shipping_invoice"].'</td>';
            $table[$key] .= '<td>'.$value.'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareDeliveriesCsv($parameters) {
        $requestsData = array();

        foreach ($parameters['result'] as $key => $item) {
            $amount = (!empty($item['amount_balance']))?$item['amount_balance']:$item['amount'];
            $value = (!empty($item['value_delivery_balance']))?$item['value_delivery_balance']:$item['value_delivery'];
            
            $requestsData[$key]['item'] = ($key + 1);
            $requestsData[$key]['date_deliverie'] = UtilsController::convertDate($item['date_deliverie']);
            $requestsData[$key]['situation'] = mb_convert_encoding($item['situation_name'], 'ISO-8859-1');
            $requestsData[$key]['id_request'] = $item['deliveryInfo']['id_request'];
            $requestsData[$key]['delivery_number'] = $item['delivery_number'];
            $requestsData[$key]['provider'] = mb_convert_encoding($item["provider"], 'ISO-8859-1');
            $requestsData[$key]['client'] = mb_convert_encoding($item["client"], 'ISO-8859-1');
            $requestsData[$key]['product'] = mb_convert_encoding($item["product"], 'ISO-8859-1');
            $requestsData[$key]['shippingcompany'] = mb_convert_encoding($item["shipping_company"], 'ISO-8859-1');
            $requestsData[$key]['amount'] = $amount;
            $requestsData[$key]['shipping_invoice'] = $item["shipping_invoice"];
            $requestsData[$key]['value_delivery'] = $value;
        }

        return $requestsData;
    }
    // Fim Geração de relatórios de entregas PDF/EXCEL

    // Geração de relatórios de Contas a Pagar PDF/EXCEL
    public function prepareBillsToPayPdf($billstopayContent, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $billstopayRows = self::prepareBillstopayToPdf($billstopayContent);
        
        $headHtml = self::getHeadHtml('Relatório de Contas a Pagar - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Contas a Pagar</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Dt de vencimento</td>
                            <td scope="col">Status</td>
                            <td scope="col">Nr Documento</td>
                            <td scope="col">Nr Pedido</td>
                            <td scope="col">Descrição do Recebedor</td>
                            <td scope="col">Tipo de conta</td>
                            <td scope="col">Situação da Conta</td>
                            <td scope="col">Data do Pgto</td>
                            <td scope="col">Valor a pagar</td>
                            <td scope="col" style="width: 160px!important;">Valor pago R$</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$billstopayRows.'

                        <tr>
                            <td style="text-align:right;" colspan="11">Total a Pagar R$<strong> '.UtilsController::convertToRealBr($billstopayContent['total_pay']).'</strong></td>
                        </tr>
                        <tr>
                            <td style="text-align:right;" colspan="11">Total Pago R$<strong> '.UtilsController::convertToRealBr($billstopayContent['total']).'</strong></td>
                        </tr>

                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareBillstopayToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters['result'] as $key => $billstopay) {
            $status = ($billstopay['status'] == 1)?'Ativo':'Inativo';

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$billstopay['expirate_date'].'</td>';
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$billstopay['document_number'].'</td>';
            $table[$key] .= '<td>'.$billstopay['id_request'].'</td>';
            $table[$key] .= '<td>'.$billstopay['provider_description'].'</td>';
            $table[$key] .= '<td>'.$billstopay["type_name"].'</td>';
            $table[$key] .= '<td>'.$billstopay['situation']['name'].'</td>';
            $table[$key] .= '<td>'.$billstopay["payment_date"].'</td>';
            $table[$key] .= '<td>'.$billstopay["value_to_pay"].'</td>';
            $table[$key] .= '<td>'.$billstopay["paid_out_value"].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareBillstopayCsv($parameters) {
        $requestsData = array();

        foreach ($parameters['result'] as $key => $item) {
            $status = ($item['status'] == 1)?'Ativo':'Inativo';
            
            $requestsData[$key]['item'] = ($key + 1);
            $requestsData[$key]['expirate_date'] = $item['expirate_date'];
            $requestsData[$key]['status'] = $status;
            $requestsData[$key]['document_number'] = $item['document_number'];
            $requestsData[$key]['id_request'] = $item['id_request'];
            $requestsData[$key]['provider_description'] = mb_convert_encoding($item['provider_description'], 'ISO-8859-1');
            $requestsData[$key]['type_name'] = mb_convert_encoding($item["type_name"], 'ISO-8859-1');
            $requestsData[$key]['formpay_name'] = mb_convert_encoding($item["formpay_name"], 'ISO-8859-1');
            $requestsData[$key]['situation'] = mb_convert_encoding($item['situation']['name'], 'ISO-8859-1');
            $requestsData[$key]['payment_date'] = $item["payment_date"];
            $requestsData[$key]['value_to_pay'] = $item["value_to_pay"];
            $requestsData[$key]['paid_out_value'] = $item["paid_out_value"];
        }

        return $requestsData;
    }
    // Fim Geração de relatórios de Contas a Pagar PDF/EXCEL

    // Geração de relatórios de Contas a Receber PDF/EXCEL
    public function prepareBillsToReceiverPdf($billstoreceiverContent, $headerInfo) {
        $generalInfo = self::breakLines($headerInfo['other_information']);
        $billstoreceiverRows = self::prepareBillstoreceiverToPdf($billstoreceiverContent);
        
        $headHtml = self::getHeadHtml('Relatório de Contas a Receber - Supporte Agronegócios');
        $footer = self::getFooter();

        $contentBody = '
        <html>
            '.$headHtml.'
            <body>
                '.$footer.'

                <ul style="list-style: none; float: left; width: 100%; margin: 0; padding: 0; border-bottom: 2px solid #CCC;">
                    <li style="float: left; width: 35%;"><img src="'.$headerInfo['img_soon'].'" style="width: 250px;"></li>
                    <li style="float: left; width: 65%;">
                        <strong>'.$headerInfo['title'].'</strong>
                        '.$generalInfo.'                      
                    </li>
                </ul>

                <h3>Relatório de Contas a Receber</h3>
                <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; ">
                    <thead>
                        <tr>
                            <td scope="col">Item</td>
                            <td scope="col">Dt a receber</td>
                            <td scope="col">Status</td>
                            <td scope="col">Descrição do pagador</td>
                            <td scope="col">Nr Documento</td>
                            <td scope="col">Nr Pedido</td>
                            <td scope="col">Origem do recebimento</td>
                            <td scope="col">Situação da Conta</td>
                            <td scope="col">Data do recebimento</td>
                            <td scope="col">Valor a receber R$</td>
                            <td scope="col" style="width: 160px!important;">Valor recebido R$</td>
                        </tr>
                    </thead>
                    <tbody>
                        '.$billstoreceiverRows.'

                        <tr>
                            <td style="text-align:right;" colspan="11">Total a Receber R$<strong> '.UtilsController::convertToRealBr($billstoreceiverContent['total_pay']).'</strong></td>
                        </tr>
                        <tr>
                            <td style="text-align:right;" colspan="11">Total Recebido R$<strong> '.UtilsController::convertToRealBr($billstoreceiverContent['total']).'</strong></td>
                        </tr>

                    </tbody>
                </table>
            </body>
        </html>
        ';

        return $contentBody;
    }

    private static function prepareBillstoreceiverToPdf($parameters) {
        $table = array();
        $response = '';

        foreach($parameters['result'] as $key => $billstopay) {
            $status = ($billstopay['status'] == 1)?'Ativo':'Inativo';

            $table[$key] = '<tr style="text-align:center">';
            $table[$key] .= '<td>'.($key + 1).'</td>';
            $table[$key] .= '<td>'.$billstopay['expirate_date'].'</td>';
            $table[$key] .= '<td>'.$status.'</td>';
            $table[$key] .= '<td>'.$billstopay['provider_description'].'</td>';
            $table[$key] .= '<td>'.$billstopay['document_number'].'</td>';
            $table[$key] .= '<td>'.$billstopay['id_request'].'</td>';
            $table[$key] .= '<td>'.$billstopay['origin']['name'].'</td>';
            $table[$key] .= '<td>'.$billstopay['situation']['name'].'</td>';
            $table[$key] .= '<td>'.$billstopay["payment_date"].'</td>';
            $table[$key] .= '<td>'.$billstopay["value_to_pay"].'</td>';
            $table[$key] .= '<td>'.$billstopay["paid_out_value"].'</td>';
            $table[$key] .= '</tr>';
        }

        foreach($table as $tr) {
            $response.=$tr;
        }

        return $response;
    }

    public function prepareBillstoreceiverCsv($parameters) {
        $requestsData = array();

        foreach ($parameters['result'] as $key => $item) {
            $status = ($item['status'] == 1)?'Ativo':'Inativo';
            
            $requestsData[$key]['item'] = ($key + 1);
            $requestsData[$key]['expirate_date'] = $item['expirate_date'];
            $requestsData[$key]['status'] = $status;
            $requestsData[$key]['provider_description'] = mb_convert_encoding($item['provider_description'], 'ISO-8859-1');            
            $requestsData[$key]['document_number'] = $item['document_number'];
            $requestsData[$key]['id_request'] = $item['id_request'];
            $requestsData[$key]['origin'] = mb_convert_encoding($item['origin']['name'], 'ISO-8859-1');
            $requestsData[$key]['formpay_name'] = mb_convert_encoding($item['receiver_name'], 'ISO-8859-1');
            $requestsData[$key]['situation'] = mb_convert_encoding($item['situation']['name'], 'ISO-8859-1');
            $requestsData[$key]['payment_date'] = $item["payment_date"];            
            $requestsData[$key]['value_to_pay'] = $item["value_to_pay"];
            $requestsData[$key]['paid_out_value'] = $item["paid_out_value"];
        }

        return $requestsData;
    }

    // Função geral para criar quebras de linhas em campos de texto
    private static function breakLines($parameters) {
        $data = '';
        $parameters = explode(PHP_EOL, $parameters);        

        foreach ($parameters as $value) {
            $data.= '<p>'.$value.'</p>';
        }

        return $data;
    }

    private function getFooter() {
        $text = '
        <div style="position:absolute; left: 20px; bottom: 11px; font-size: 10px;">
            Data de emissão: '.date('d/m/Y').', usuário: '.$this->loggedUser->name.'
        </div>';

        $response = '
        <htmlpagefooter name="myfooter">
        '.$text.'
        </htmlpagefooter>
        <sethtmlpagefooter name="myfooter" value="on" />
        ';
        
        return $response;
    }

    private static function getHeadHtml($title) {
        $response = '
            <head>
                <title>'.$title.'</title>
                <style>
                    body{
                        font-family: "Myriad Pro";
                    }
                    h3{
                        font-family: "Myriad Pro";
                        font-weight: normal;
                        font-size: 30px;
                    }
                    table.items {
                        border: 0.1mm solid #000000;
                    }
                    td { vertical-align: middle; }
                    .items td{
                        border-left: 0.1mm solid #000000;
                        border-right: 0.1mm solid #000000;
                        border-bottom: 0.1mm solid #000000;
                        box-sizing: border-box;
                        padding: 5px;
                    }
                    table thead td{ 
                        background-color: #EEEEEE;
                        text-align: center;
                        border: 0.1mm solid #000000;
                        font-family: "Myriad Pro";
                    }
                    p{
                        font-size: 13px;
                        margin: 0 0 1px;
                    }
                </style>
            </head>
        ';

        return $response;
    }
}