<?php
namespace src\controllers;

use \core\Controller;
use \src\handlers\FiltersHandler;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\controllers\UtilsController;
use \src\controllers\DeliveriesController;
use \src\models\City;
use \src\models\Client;
use \src\models\Deliverie;
use \src\models\Farm;
use \src\models\Interaction;
use \src\models\Product;
use \src\models\Provider;
use \src\models\Request;
use \src\models\Bills_to_pay;
use \src\models\Bills_to_receive;
use \src\models\Salesman;
use \src\models\User;

class RequestsController extends Controller {
    private $loggedUser;
    private $pageActive;
    private $paramsName;
    private $arrayInfo;

    public function __construct() {
        date_default_timezone_set('America/Sao_Paulo');
        
        $this->loggedUser = LoginHandler::checkLogin();

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

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

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

    public function index() {
        $emptyFilter = [
            'dateInit' => '',
            'dateEnd' => '',
            'searchType' => '',
            'optionList' => '',
            'opt' => '',
            'tag' => ''
        ];

        if(isset($_POST['filter']) && !empty($_POST['filter'])) {
            $_SESSION['filter_requests'] = $_POST['filter'];
            if($_SESSION['filter_requests']['searchType'] == 'clear') {
                $_SESSION['filter_requests'] = $emptyFilter;
                $this->redirect('/requests');
            }
        }

        if(isset($GET['op']) && !empty($_GET['op'])) {
            $op = intval($GET['op']);
            $_SESSION['filter_requests']['searchType'] = $op;
        } else { $this->arrayInfo['op'] = ''; }


        if(!isset($_SESSION['filter_requests'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_requests'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_requests']['searchType'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_requests']['searchType'];
        }

        $offset = 0;
        $limit = 20;
        $this->arrayInfo['p'] = 1;
        if(isset($_GET['p']) && !empty($_GET['p'])) {
            $this->arrayInfo['p'] = intval($_GET['p']);
            if($this->arrayInfo['p'] == 0) {
                $this->arrayInfo['p'] = 1;
            }
        }

        $offset = ( $this->arrayInfo['p'] * $limit ) - $limit;
        $filter = FiltersHandler::filterRequests($_SESSION['filter_requests']);
        $this->arrayInfo['requestsStatus'] = Request::getAllStatus();
        $this->arrayInfo['requestList'] = Request::getRequests($offset, $limit, $filter);

        foreach ($this->arrayInfo['requestList'] as $key => $req) {
            $this->arrayInfo['requestList'][$key]['date_created'] = date('d/m/Y', strtotime($req['date_created']));
            $this->arrayInfo['requestList'][$key]['client'] = Client::getName($req['id_client']);
            $this->arrayInfo['requestList'][$key]['provider'] = Provider::getProviderName($req['id_provider']);
            $this->arrayInfo['requestList'][$key]['salesman'] = ($req['id_salesman'])?Salesman::getSalesmanName($req['id_salesman']):'';
            $this->arrayInfo['requestList'][$key]['status_name'] = Request::getNameStatus($req['status']);
            $this->arrayInfo['requestList'][$key]['amount'] = number_format(Request::getAmountRequest($req['id']), 2);
            $this->arrayInfo['requestList'][$key]['balance'] = number_format(Deliverie::getAmountBalance($req['id']), 2);
            $this->arrayInfo['requestList'][$key]['total'] = UtilsController::convertToRealBr($req['total']);

            // Obtendo valor unitário
            $itemRow = Request::getRequestItems($req['id']);
            $qtItems = count($itemRow);
            $valueItems = array_sum(array_column($itemRow, 'price_sale'));

            if($qtItems == 0 || $valueItems == 0) {
                $this->arrayInfo['requestList'][$key]['value_unit'] = 0;
            } else {
                $this->arrayInfo['requestList'][$key]['value_unit'] = UtilsController::convertToRealBr(($valueItems / $qtItems));
            }            
        }

        $requests_count = Request::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $requests_count / $limit );
        $filterPage = $_SESSION['filter_requests'];

        $this->render('requests', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'filter' => $filterPage,
            'array' => $this->arrayInfo,
            'titlePage' => 'Pedidos - Supporte Agronegócios'
        ]);
    }

    public function addNoStock() {
        $this->arrayInfo['date'] = date('d/m/Y');
        $this->arrayInfo['user'] = $this->loggedUser->name;
        $this->arrayInfo['receiverForm'] = Bills_to_receive::getAllReceiverForm();

        unset($_SESSION['number_request'], $_SESSION['providers'], $_SESSION['total_request'], $_SESSION['request_items'], $_SESSION['percent_supporte'], $_SESSION['reference_request'], $_SESSION['typeRequest']);

        $_SESSION['typeRequest'] = intval(1);

        $this->render('request_nostock_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'array' => $this->arrayInfo,
            'titlePage' => 'Criar Pedido - Supporte Agronegócios'
        ]);
    }


    public function addWithStock() {
        $this->arrayInfo['date'] = date('d/m/Y');
        $this->arrayInfo['user'] = $this->loggedUser->name;
        $this->arrayInfo['receiverForm'] = Bills_to_receive::getAllReceiverForm();

        unset($_SESSION['number_request'], $_SESSION['providers'], $_SESSION['total_request'], $_SESSION['request_items'], $_SESSION['percent_supporte'], $_SESSION['reference_request'], $_SESSION['typeRequest']);

        $_SESSION['typeRequest'] = intval(2);

        $this->render('request_wstock_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'array' => $this->arrayInfo,
            'titlePage' => 'Criar Pedido - Supporte Agronegócios'
        ]);
    }

    public function insertProductInRequest() {
        $product_group = filter_input(INPUT_POST, 'product_group');
        $request_id = filter_input(INPUT_POST, 'request_id');
        $product_id = filter_input(INPUT_POST, 'product_id');
        $percent_supp = filter_input(INPUT_POST, 'percent_supp');
        $quantity = filter_input(INPUT_POST, 'quantity');
        $cost_price = filter_input(INPUT_POST, 'cost_price');
        $price_sale = filter_input(INPUT_POST, 'price_sale');
        $provider_id = filter_input(INPUT_POST, 'provider_id');
        $type_request = filter_input(INPUT_POST, 'type_request');
        $reference_request = filter_input(INPUT_POST, 'reference_request');
        $quantity = UtilsController::convertPriceToDb($quantity);

        if($product_id) {

            if($type_request == 'withstock') {
                if($product_group != 2) {
                    $response['status'] = false;
                    $response['msg'] = "O produto não pertence ao grupo com estoque!";
                    echo json_encode($response);
                    exit;
                }
            } else if($type_request == 'nostock') {
                if($product_group == 2) {
                    $response['status'] = false;
                    $response['msg'] = "O produto não pertence ao grupo sem estoque!";
                    echo json_encode($response);
                    exit;
                }
            }

            if($product_group == 2) {
                $productInfo = Product::getProduct($product_id);

                if($productInfo['amount'] < $quantity) {
                    $response['status'] = false;
                    $response['msg'] = "O produto possui ".$productInfo['amount']." em estoque!";
                    echo json_encode($response);
                    exit;
                }
            }

            if(isset($_SESSION['request_items'])) {
                if(count($_SESSION['request_items']) > 0) {
                    $countItems = count($_SESSION['request_items']);
                
                    for($i=0;$i<$countItems;$i++) {
                        if($_SESSION['request_items'][$i]['product'] == $product_id) {
                            $response['status'] = false;
                            $response['msg'] = "Produto já adicionado!";
                            echo json_encode($response);
                            exit;
                        } else if($_SESSION['request_items'][$i]['p_group'] != $product_group) {
                            $response['status'] = false;
                            $response['msg'] = "Produto de grupo dirente!";
                            echo json_encode($response);
                            exit;
                        }               
                    }
                }
            }

            if(!isset($_SESSION['reference_request'])) {
                $_SESSION['reference_request'] = md5(rand(0,999));
                $_SESSION['number_request'] = $request_id;
                $_SESSION['providers'] = array();
                $_SESSION['total_request'] = 0;
                $_SESSION['request_items'] = array();
                $_SESSION['percent_supporte'] = 0;
            }

            if($percent_supp && $product_group != 2) {
                $_SESSION['percent_supporte'] = UtilsController::convertPriceToDb($percent_supp);
            }          

            $priceItem = UtilsController::convertPriceToDb($price_sale);
            $price = ($quantity * $priceItem);
            $_SESSION['total_request'] += $price;

            $itemReceived = [
                'product' => $product_id,
                'p_group' => $product_group,
                'provider_id' => $provider_id,
                'quantity' => $quantity,
                'price_coust' => UtilsController::convertPriceToDb($cost_price),
                'price_sale' => $priceItem,
                'product_percente' => UtilsController::convertPriceToDb($percent_supp),
                'total_item' => $price
            ];
            array_push($_SESSION['request_items'], $itemReceived);
            
            $response['status'] = true;
            $response['items_show'] = self::prepareProductsToShow($_SESSION['request_items']);
            $response['total_request'] = UtilsController::convertToRealBr($_SESSION['total_request']);
            $response['reference'] = $_SESSION['reference_request'];
            $response['count'] = count($_SESSION['request_items']);
            echo json_encode($response);
        }
    }

    public function removeItem() {
        $product = filter_input(INPUT_POST, 'product');

        if($product) {
            $requestId = filter_input(INPUT_POST, 'request_id'); // caso seja pedido em aberto, usar referencia para retornar quantidade ao estoque

            $removeItem = '';
            $totalItem = '';
            $count = count($_SESSION['request_items']);

            for($i=0;$i<$count;$i++) {

                if($_SESSION['request_items'][$i]['product'] == $product) {
                    $removeItem = $i;
                    $totalItem = $_SESSION['request_items'][$i]['total_item'];
                    break;
                }
            }

            // Retornando quantidade ao estoque
            // if($requestId) {
            //     $product = new Products();

            //     $stock_return = $_SESSION['request_items'][$removeItem]['quantity'];
            //     $product->increeseAmount($p, $stock_return);
            // }

            // Removendo da Lista
            unset($_SESSION['request_items'][$removeItem]);
            $_SESSION['request_items'] = array_values($_SESSION['request_items']);


            $response['status'] = true;
            $response['items_show'] = self::prepareProductsToShow($_SESSION['request_items']);

            $_SESSION['total_request'] = $_SESSION['total_request'] - $totalItem;
            $response['total_request'] = UtilsController::convertToRealBr($_SESSION['total_request']);
            $response['count'] = count($_SESSION['request_items']);

            echo json_encode($response);
        }
    }

    private function prepareProductsToShow($arrayItems) {
        $table = '';
        $table .= '<table class="table table-bordered">';
        $table .= '<tbody>';
        $table .= '<tr>';
        $table .= '<th scope="col">Item</th> <th scope="col">Descrição do Pedido</th> <th scope="col">Fornecedor</th> <th scope="col">Grupo</th> <th scope="col">Unid</th> <th scope="col">Apres</th> <th scope="col">Qtde</th> <th scope="col">% SUPPORTE</th> <th scope="col">R$ Custo</th> <th scope="col">R$ Venda</th> <th scope="col">Preço do Item</th> <th scope="col" style="width: 80px!important;">Ações</th>';
        foreach ($arrayItems as $key => $item) {
            $productItem = Product::getProduct($item['product']);
            $providerName = Provider::getProviderName($item['provider_id']);
            $group = Product::getProductGroup($item['p_group']);
            $unity = Product::getProductUnit($productItem['id_unity']);
            $presentation = Product::getProductPresentation($productItem['id_presentation']);

            $_SESSION['providers'][] = $item['provider_id'];
            
            $table .= '<tr>';
            $table .= '<td>'.($key + 1).'</td>';
            $table .= '<td>'.$productItem['name'].'</td>';
            $table .= '<td>'.$providerName.'</td>';
            $table .= '<td>'.$group['name'].'</td>';
            $table .= '<td>'.$unity['name'].'</td>';
            $table .= '<td>'.$presentation['name'].'</td>';
            $table .= '<td>'.$item['quantity'].'</td>';
            $table .= '<td>'.$item['product_percente'].'</td>';
            $table .= '<td>'.UtilsController::convertToRealBr($item['price_coust']).'</td>';
            $table .= '<td>'.UtilsController::convertToRealBr($item['price_sale']).'</td>';
            $table .= '<td>'.UtilsController::convertToRealBr($item['total_item']).'</td>';
            $table .= '<td style="width: 80px!important;"><a href="#" class="btn btn-danger" id="'.$item['product'].'">remover</a></td>';
            $table .= '</tr>';
        }

        $table .= '</tr>';
        $table .= '</tbody>';
        $table .= '</table>';

        $_SESSION['providers'] = array_values(array_unique($_SESSION['providers']));
        return $table;
    }

    public function totalValueItem() {
        $qt = filter_input(INPUT_POST, 'qt');
        $value = filter_input(INPUT_POST, 'value');

        if($qt && $value) {
            $qt = UtilsController::convertPriceToDb($qt);
            $value = UtilsController::convertPriceToDb($value);

            $response = ($qt * $value);
            echo json_encode(UtilsController::convertToRealBr($response));
        }
    }

    // Sessão relacionada a resultado estimado
    public function getCoustPerUnity() {
        $data['status'] = false;
        $data['msg'] = 'Nenhum produto foi adicionado!';

        if(isset($_SESSION['request_items']) && !empty($_SESSION['request_items'])) {
            $total_price_coust = 0;
            $total_products = 0;

            foreach ($_SESSION['request_items'] as $key => $item) {                
                $total_price_coust += $item['quantity'] * $item['price_coust'];
                $total_products += $item['quantity'];
            }

            $data['coust_per_unity'] = $total_price_coust / $total_products;
            $data['coust_per_unity'] = UtilsController::convertToRealBr($data['coust_per_unity']);            
            $data['msg'] = '';
            $data['status'] = true;            
        }
        echo json_encode($data);
    }

    public function getTotalCoust() {
        $data['status'] = false;
        $data['msg'] = "Nenhum produto foi adicionado!";

        $group = filter_input(INPUT_POST, 'product_group');

        if($group) {
            $stmt_coust_for_unity = filter_input(INPUT_POST, 'stmt_coust_for_unity');
            $stmt_freight_price_unity = filter_input(INPUT_POST, 'stmt_freight_price_unity');
            $stmt_others_unity = filter_input(INPUT_POST, 'stmt_others_unity');
            $stmt_commision_salesman = filter_input(INPUT_POST, 'stmt_commision_salesman');

            $stmt_coust_for_unity = (!empty($stmt_coust_for_unity))? UtilsController::convertPriceToDb($stmt_coust_for_unity) : 0;
            $stmt_freight_price_unity = (!empty($stmt_freight_price_unity))? UtilsController::convertPriceToDb($stmt_freight_price_unity) : 0;
            $stmt_others_unity = (!empty($stmt_others_unity))? UtilsController::convertPriceToDb($stmt_others_unity) : 0;
            $stmt_commision_salesman = (!empty($stmt_commision_salesman))? UtilsController::convertPriceToDb($stmt_commision_salesman) : 0;

            $data['totalCoust'] = ($stmt_coust_for_unity + $stmt_freight_price_unity + $stmt_others_unity + $stmt_commision_salesman);
            $data['totalCoust'] = UtilsController::convertToRealBr($data['totalCoust']);
            $data['msg'] = '';
            $data['status'] = true;
        }

        echo json_encode($data);
    }

    public function getResultEstimate() {
        $data['status'] = false;
        $data['msg'] = "Alguns campos não foram preenchidos!";

        $product_group = filter_input(INPUT_POST, 'product_group');

        if($product_group) {
            $estimative_total_couste = filter_input(INPUT_POST, 'estimative_total_couste');
            $estimative_total_couste = UtilsController::convertPriceToDb($estimative_total_couste);
            $total_products = 0;
            $total_request = $_SESSION['total_request'];

            if($product_group == 1) {
                $percent_supporte = $_SESSION['percent_supporte'];

                foreach($_SESSION['request_items'] as $key => $item) {
                    $total_products += $item['quantity'];
                }

                $data['estimative_result'] = (((($percent_supporte / 100) * $total_request) - ($estimative_total_couste * $total_products)) / $total_request) * 100;
                $data['estimative_result_real'] = ($data['estimative_result'] * $total_request) / 100;

                $data['estimative_result'] = UtilsController::convertToRealBr($data['estimative_result']);
                $data['estimative_result_real'] = UtilsController::convertToRealBr($data['estimative_result_real']);
                $data['msg'] = '';
                $data['status'] = true;
            } else {
                $medio_price_sale = 0;

                foreach($_SESSION['request_items'] as $key => $item) {                
                    $medio_price_sale += ($item['quantity'] * $item['price_sale']);
                    $total_products += $item['quantity'];
                }

                $medio_price_sale = ($medio_price_sale / $total_products);

                $data['estimative_result'] = ($estimative_total_couste / $medio_price_sale) * 100;
                $data['estimative_result'] = 100 - $data['estimative_result'];
                $data['estimative_result_real'] = ($data['estimative_result'] * $total_request) / 100;

                $data['estimative_result'] = UtilsController::convertToRealBr($data['estimative_result']);
                $data['estimative_result_real'] = UtilsController::convertToRealBr($data['estimative_result_real']);
                $data['msg'] = '';
                $data['status'] = true;
            }

            echo json_encode($data);
        }
    }

    public function getComisionSalesman() {
        $data['total_comission'] = 0;
        $data['reais_to_unity'] = 0;
        $data['status'] = false;
        $data['msg'] = 'Digite a porcentagem da comissão!';

        if($_SESSION['request_items'][0]['p_group'] == 2) {
            $data['status'] = true;
            $data['msg'] = '';
        }

        $percentage = filter_input(INPUT_POST, 'percentage');

        if($percentage) {
            $data['msg'] = 'Nenhum produto foi adicionado!';

            if(isset($_SESSION['request_items']) && !empty($_SESSION['request_items'])) {
                $percentage = UtilsController::convertPriceToDb($percentage);
                $quantity = 0;

                foreach ($_SESSION['request_items'] as $key => $item) {
                    $quantity += $item['quantity'];
                }

                $data['total_comission'] = ($percentage / 100) * $_SESSION['total_request'];
                $data['reais_to_unity'] = $data['total_comission'] / $quantity;

                $data['total_comission'] = UtilsController::convertToRealBr($data['total_comission']);
                $data['reais_to_unity'] = UtilsController::convertToRealBr($data['reais_to_unity']);
                $data['msg'] = '';
                $data['status'] = true;
            }
        }

        echo json_encode($data);
    }
    // Fim Sessão relacionada a resultado estimado

    public function verifyDate() {
        $date = filter_input(INPUT_POST, 'date');

        if($date) {
            $type_requisition = filter_input(INPUT_POST, 'type_requisition');

            $response = UtilsController::verifyFutureDate($date);
            echo json_encode($response);
        }
    }

    public function saveRequest() {
        $read_to_save = filter_input(INPUT_POST, 'read_to_save');

        if($read_to_save) {
            
            $provider = implode(',', $_SESSION['providers']);
            $salesmanId = filter_input(INPUT_POST, 'salesman_selected');
            $requestId = filter_input(INPUT_POST, 'id_request'); // Vindo da página

            $requestInfo['type'] = (isset($_POST['cif']))?'cif':'fob';
            $requestInfo['id_user'] = $this->loggedUser->id;
            $requestInfo['id_client'] = filter_input(INPUT_POST, 'client_selected');
            $requestInfo['id_provider'] = $provider;
            $requestInfo['id_salesman'] = ($salesmanId)?$salesmanId:null;
            $requestInfo['id_receiverform'] = filter_input(INPUT_POST, 'receiver_where');
            $requestInfo['pre_select_farm'] = filter_input(INPUT_POST, 'farms_list');
            $requestInfo['status'] = filter_input(INPUT_POST, 'status_save');
            $requestInfo['date_created'] = date('Y-m-d H:i:s');
            $requestInfo['percente_supporte'] = $_SESSION['percent_supporte'];
            $requestInfo['total'] = $_SESSION['total_request'];
            $requestInfo['note'] = filter_input(INPUT_POST, 'note');

            if(!empty($requestId)) {
                unset($requestInfo['date_created']);
                Request::deleteOtherInformations('request_items', $requestId);
                Request::deleteOtherInformations('request_payment_receiver', $requestId);
                Request::deleteOtherInformations('other_expenses', $requestId);
                Request::deleteOtherInformations('salesman_comission', $requestId);
                Request::deleteOtherInformations('estimative_request', $requestId);

                Request::requestUpdate($requestId, $requestInfo);
            } else {
                $requestId = Request::requestSave($requestInfo);
            }            

            // Inserção de items do pedido no DB e possível redução do estoque
            foreach ($_SESSION['request_items'] as $item) {

                // Redução de estoque caso seja salvar e entregar
                if($item['p_group'] != 1 && $requestInfo['status'] != 1) {                    
                    $productRow = Product::getProduct($item['product']);

                    if($productRow['amount'] > 0) {
                        $newStock = ($productRow['amount'] - $item['quantity']);
                    } else {
                        $newStock = 0;
                    }

                    $product['amount'] = $newStock;
                    Product::updateProduct($item['product'], $product, '');
                }
                // Fim Redução de estoque caso seja salvar e entregar

                // Salvar items do pedido
                $requestItems['id_request'] = $requestId;
                $requestItems['id_product'] = $item['product'];
                $requestItems['quantity'] = $item['quantity'];
                $requestItems['price_sale'] = $item['price_sale'];
                $requestItems['percente_product'] = $item['product_percente'];
                $requestItems['total'] = $item['total_item'];

                Request::insertItems($requestItems);
                // Fim Salvar item do pedido
            }

            // Data de recebimento e Qtd de parcelas
            $receiverForm = filter_input(INPUT_POST, 'receiver_form');

            // if($receiverForm != 0) {
            $dateInCache = filter_input(INPUT_POST, 'date_receiver_incash');
            $dateInTerm = filter_input(INPUT_POST, 'date_receiver_interm');
            $installments = filter_input(INPUT_POST, 'qtd_portion');
            $dateDefalt = date('Y-m-d', strtotime('+ 30 days', strtotime(date('Y-m-d'))));
            $receiverData['id_request'] = $requestId;

            switch ($receiverForm) {
                case 1:
                    $receiverData['type_receiver'] = $receiverForm;
                    $receiverData['date_receiver'] = UtilsController::convertDate($dateInCache);
                    $receiverData['installments'] = 1;
                break;

                case 2:
                    $receiverData['type_receiver'] = $receiverForm;
                    $receiverData['date_receiver'] = UtilsController::convertDate($dateInTerm);
                    $receiverData['installments'] = $installments;
                break;
                
                default:
                    $receiverData['type_receiver'] = $receiverForm;
                    $receiverData['date_receiver'] = $dateDefalt;
                    $receiverData['installments'] = 1;
                break;
            }

            // Recebimento de comissão (Primeiramente para grupo sem estoque)
            if($_SESSION['request_items'][0]['p_group'] == 1) {
                $receiverData['how_pay_comission_supporte'] = filter_input(INPUT_POST, 'whats_pay_comission');
                $receiverData['receiver_comission_days_after_delivery'] = filter_input(INPUT_POST, 'receive_after_delivery');
            }
            // Fim Recebimento de comissão (Primeiramente para grupo sem estoque)

            Request::saveDetailPayment($receiverData);
            // Fim Data de recebimento e Qtd de parcelas

            // Outras despesas
            $othersValue = filter_input(INPUT_POST, 'other_value');

            if($othersValue) {
                $othersInfo['id_request'] = $requestId;
                $othersInfo['value_unity'] = UtilsController::convertPriceToDb($othersValue);
                $othersInfo['note'] = filter_input(INPUT_POST, 'other_description');

                Request::saveOthersExpenses($othersInfo);
            }
            // Fim Outras despesas

            // Comissão do vendedor
            $hasComissionSalesman = filter_input(INPUT_POST, 'has_comission_salesman');

            if($hasComissionSalesman) {
                $real_to_unity = filter_input(INPUT_POST, 'real_per_unity');
                $percentage = filter_input(INPUT_POST, 'salesman_percentage');
                $total = filter_input(INPUT_POST, 'comission_value');

                $salesmanComission['id_request'] = $requestId;
                $salesmanComission['salesman'] = $requestInfo['id_salesman'];
                $salesmanComission['real_to_unity'] = UtilsController::convertPriceToDb($real_to_unity);
                $salesmanComission['percentage'] = UtilsController::convertPriceToDb($percentage);
                $salesmanComission['total'] = UtilsController::convertPriceToDb($total);
                $salesmanComission['payment_comission_days'] = filter_input(INPUT_POST, 'days_of_payment_comission');

                Request::saveComissionSalesman($salesmanComission);
            }
            // Fim Comissão do vendedor

            // Resultado Estimado

            $coust_per_unity = filter_input(INPUT_POST, 'estimative_coust_for_unity');
            $freight_price_unity = filter_input(INPUT_POST, 'estimative_freight_price_unity');
            $others_unity = filter_input(INPUT_POST, 'estimaive_others_unity');
            $comission_salesman = filter_input(INPUT_POST, 'estimative_commision_salesman');
            $total_couste = filter_input(INPUT_POST, 'estimative_total_couste');
            $result_real = filter_input(INPUT_POST, 'estimative_result');

            $estimateResult['id_request'] = $requestId;
            $estimateResult['coust_unity'] = ($coust_per_unity)? UtilsController::convertPriceToDb($coust_per_unity) :0;
            $estimateResult['freight_unity'] = ($freight_price_unity)? UtilsController::convertPriceToDb($freight_price_unity) :0;
            $estimateResult['exepenses_unity'] = ($others_unity)? UtilsController::convertPriceToDb($others_unity) :0;
            $estimateResult['comission_salesman_unity'] = ($comission_salesman)? UtilsController::convertPriceToDb($comission_salesman) :0;
            $estimateResult['total_coust'] = ($total_couste)? UtilsController::convertPriceToDb($total_couste) :0;
            $estimateResult['estimative_result'] = ($result_real)? UtilsController::convertPriceToDb($result_real) :0;

            Request::saveEstimativeResult($estimateResult);
            // Fim Resultado Estimado

            // Criação entregas e suas dependências em pedidos com estoque
            if($_SESSION['request_items'][0]['p_group'] == 2) {
                $data = array();

                $data['type_delivery'] = 'single_delivery';
                $data['id_request'] = $requestId;
                $data['id_client'] = $requestInfo['id_client'];
                $data['id_product'] = $_SESSION['request_items'][0]['product'];
                $data['product_group'] = 2;
                $data['qtd_deliveries'] = '';
                $data['date_first_deliverie'] = date('d-m-Y', strtotime('+ 30 days', strtotime(date('Y-m-d'))));
                $data['daysPayment'] = '';
                $data['shipping_invoice'] = '';
                $data['note'] = '';

                $obj = new DeliveriesController();
                $obj->initDelivery($data);
            }
            // Fim Criação entregas e suas dependências em pedidos com estoque

            // Criação de interação em CRM
            $salesmanClient = Client::getClient($requestInfo['id_client']);

            if($salesmanClient['id_salesman']) {
                $filter['collum'] = 'type';
                $filter['simbol'] = '=';
                $filter['value'] = 1;

                // Verificar se existe conversa criada para o cliente (Caso não, criar uma nova)
                $clientsConversation = Interaction::getConversation('id_client', $requestInfo['id_client'], $filter);

                if($clientsConversation) {
                    $arrayData['id_crm'] = $clientsConversation['id'];
                } else {

                    $clientNewConversation['id_client'] = $requestInfo['id_client'];
                    $clientNewConversation['id_salesman'] = $salesmanClient['id_salesman'];
                    $clientNewConversation['type'] = 1;
                    $clientNewConversation['category'] = 2;

                    $arrayData['id_crm'] = Interaction::createConversation($clientNewConversation);
                }
                // Fim Verificar se existe conversa criada para o cliente (Caso não, criar uma nova)

                $salesmanName = Salesman::getSalesmanName($salesmanClient['id_salesman']);
                $category = ($_SESSION['request_items'][0]['p_group'] == 1)? 2 : 1;

                $arrayData['type'] = 1;
                $arrayData['id_request'] = $requestId;
                $arrayData['id_salesman'] = $salesmanClient['id_salesman'];
                $arrayData['category'] = $category;
                $arrayData['date_created'] = date('Y-m-d H:i:s');
                $arrayData['next_interation'] = $arrayData['date_created'];
                $arrayData['salesman_name'] = $salesmanName;

                $arrayData['id_client'] = $requestInfo['id_client'];
                $arrayData['client_name'] = $salesmanClient['name'];
                $arrayData['client_email'] = $salesmanClient['email'];
                $arrayData['client_phone'] = $salesmanClient['first_phone'];

                $providerName = Provider::getProviderName($provider);
                $requestQuantity = Request::getAmountRequest($requestId);
                $totalRequest = UtilsController::convertToRealBr($requestInfo['total']);
                $productsName = '';

                foreach ($_SESSION['request_items'] as $key => $product) {
                    $productsName .= Product::getName($product['product']).' ('.$product['quantity'].') \n';
                }

                $text = '<strong>Data: </strong>'.date('d/m/Y').nl2br('\n');
                $text .= '<strong>Pedido: </strong>'.$requestId.'\n';
                $text .= '<strong>Produtos: </strong>\n';
                $text .= $productsName;
                $text .= '<strong>Fornecedor: </strong>'.$providerName.'\n';
                $text .= '<strong>Quantidade Total: </strong>'.$requestQuantity.'\n';
                $text .= '<strong>Total Do Pedido: </strong>'.$totalRequest.'\n';
                $text .= '<strong>Vendedor: </strong>'.$salesmanName.'\n';

                $arrayData['conversation'] = $text;

                Interaction::save($arrayData);
            }
            // Fim Criação de interação em CRM

            $this->redirect('/requests');
        }
    }

    public function edit() {
        $requestId = filter_input(INPUT_GET, 'r');

        if($requestId) {            
            $requestInfo = self::getAllInformationRequest($requestId);
            $product = Product::getProduct($requestInfo['requestItems'][0]['id_product']);
            $this->arrayInfo['type_request'] = ($product['id_group'] == 2)?'withstock':'nostock';
            $this->arrayInfo['count_products'] = count($requestInfo['requestItems']);
            $requestInfo['receiver_form'] = Bills_to_receive::getAllReceiverForm();

            
            $_SESSION['reference_request'] = md5(rand(0,999));
            $_SESSION['number_request'] = $requestInfo['requestInfo']['id'];
            $_SESSION['providers'] = array();
            $_SESSION['total_request'] = 0;
            $_SESSION['request_items'] = array();
            $_SESSION['percent_supporte'] = 0;
            

            if($requestInfo['requestInfo']['percente_supporte']) {
                $_SESSION['percent_supporte'] = $requestInfo['requestInfo']['percente_supporte'];
            }

            $_SESSION['total_request'] = UtilsController::convertPriceToDb($requestInfo['requestInfo']['total']);

            foreach ($requestInfo['requestItems'] as $key => $item) {
                $productRow = Product::getProduct($item['id_product']);
                
                $itemReceived = [
                    'product' => $item['id_product'],
                    'p_group' => $productRow['id_group'],
                    'provider_id' => $productRow['id_provider'],
                    'quantity' => $item['quantity'],
                    'price_coust' => $productRow['cost_price'],
                    'price_sale' => $item['price_sale'],
                    'total_item' => $item['total']
                ];

                $_SESSION['providers'][] = $itemReceived['provider_id'];
                array_push($_SESSION['request_items'], $itemReceived);
            }

            $this->arrayInfo['items_show'] = self::prepareProductsToShow($_SESSION['request_items']);
            $this->arrayInfo['reference'] = $_SESSION['reference_request'];

            $this->render('request_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'array' => $requestInfo,
                'infoTecnic' => $this->arrayInfo,
                'group' => $product['id_group'],
                'titlePage' => 'Editar Pedido - Supporte Agronegócios'
            ]);
        }
    }

    public function view() {
        $requestId = filter_input(INPUT_GET, 'r');

        if($requestId) {
            $providersList = array();
            $requestInfo = self::getAllInformationRequest($requestId);
            $requestInfo['receiver_form'] = Bills_to_receive::getAllReceiverForm();

            $deliveries = Deliverie::getDeliveries($requestId);

            if(empty($deliveries)) {
                $deliveries = array(
                    'id' => '',
                    'id_request' => '',
                    'type_delivery' => ''
                );
            }

            $providerArray = explode(',', $requestInfo['requestInfo']['id_provider']);

            foreach ($providerArray as $key => $provider) {
                $providersList[] = Provider::getProvider($provider, 'providers');
            }
            
            // montar lista dos produtos para exibição
            foreach ($requestInfo['requestItems'] as $key => $item) {
                $productRow = Product::getProduct($item['id_product']);

                $requestInfo['requestItems'][$key]['productInfo'] = Product::getProduct($item['id_product']);
                $requestInfo['requestItems'][$key]['p_group'] = Product::getProductGroup($productRow['id_group']);
                $requestInfo['requestItems'][$key]['provider'] = Provider::getProviderName($productRow['id_provider']);
                $requestInfo['requestItems'][$key]['unity'] = Product::getProductUnit($requestInfo['requestItems'][$key]['productInfo']['id_unity']);
                $requestInfo['requestItems'][$key]['presentation'] = Product::getProductPresentation($requestInfo['requestItems'][$key]['productInfo']['id_presentation']);


                $requestInfo['requestItems'][$key]['price_sale'] = UtilsController::convertToRealBr($item['price_sale']);
                $requestInfo['requestItems'][$key]['total'] = UtilsController::convertToRealBr($item['total']);
                $requestInfo['requestItems'][$key]['productInfo']['cost_price'] = UtilsController::convertToRealBr($requestInfo['requestItems'][$key]['productInfo']['cost_price']);

                if( !empty($deliveries[$key]['type_delivery']) && $deliveries[$key]['type_delivery'] == 'single_delivery' ) {

                    $requestInfo['requestItems'][$key]['link_delivery'] = Deliverie::getUniqueDelivery($deliveries[$key]['id']);

                } else if( !empty($deliveries[$key]['type_delivery']) && $deliveries[$key]['type_delivery'] == 'separate_deliveries' ) {

                    $requestInfo['requestItems'][$key]['link_delivery'] = Deliverie::getDelivery($deliveries[$key]['id'], $item['id_product']);
                }
            }

            $this->render('request_view', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'array' => $requestInfo,
                'providers' => $providersList,
                'titlePage' => 'Visualização de Pedido - Supporte Agronegócios'
            ]);
        }
    }

    private function getAllInformationRequest($request) {
        $data = array();

        if($request) {
            $data['requestInfo'] = Request::getRequest($request);
            $data['requestItems'] = Request::getRequestItems($request);
            $data['amountItems'] = Request::getAmountRequest($request);
            $data['clientInfo'] = Client::getClient($data['requestInfo']['id_client']);
            $data['farmSelected'] = Farm::getFarm($data['requestInfo']['pre_select_farm']);
            $data['receiverForm'] = Request::getOtherInformations('request_payment_receiver', $request);
            $data['otherExpenses'] = Request::getOtherInformations('other_expenses', $request);
            $data['comissionSalesman'] = Request::getOtherInformations('salesman_comission', $request);
            $data['estimateResult'] = Request::getOtherInformations('estimative_request', $request);

            $data['estimateResult']['estimative_total'] = ($data['estimateResult']['estimative_result'] * $data['requestInfo']['total']) / 100;

            if(!empty($data['comissionSalesman'])) {
                $data['comissionSalesman']['name'] = Salesman::getSalesmanName($data['comissionSalesman']['salesman']);
                $data['comissionSalesman']['real_to_unity'] = UtilsController::convertToRealBr($data['comissionSalesman']['real_to_unity']);
                $data['comissionSalesman']['total'] = ($data['comissionSalesman']['percentage'] * $data['requestInfo']['total']) / 100;
                $data['comissionSalesman']['total'] = UtilsController::convertToRealBr($data['comissionSalesman']['total']);
            }

            $data['requestInfo']['date_created'] = date('d/m/Y', strtotime($data['requestInfo']['date_created']));
            $data['requestInfo']['user_name'] = User::getName($data['requestInfo']['id_user']);
            $data['requestInfo']['total'] = UtilsController::convertToRealBr($data['requestInfo']['total']);


            $data['farmSelected']['city_name'] = City::getName($data['farmSelected']['city']);

            
            $data['receiverForm']['date_receiver'] = UtilsController::convertDate($data['receiverForm']['date_receiver']);

            if(!empty($data['otherExpenses'])) {
                $data['otherExpenses']['value_unity'] = UtilsController::convertToRealBr($data['otherExpenses']['value_unity']);
            }

            $data['estimateResult']['coust_unity'] = UtilsController::convertToRealBr($data['estimateResult']['coust_unity']);
            $data['estimateResult']['exepenses_unity'] = UtilsController::convertToRealBr($data['estimateResult']['exepenses_unity']);
            $data['estimateResult']['comission_salesman_unity'] = UtilsController::convertToRealBr($data['estimateResult']['comission_salesman_unity']);
            $data['estimateResult']['total_coust'] = UtilsController::convertToRealBr($data['estimateResult']['total_coust']);
            $data['estimateResult']['estimative_result'] = UtilsController::convertToRealBr($data['estimateResult']['estimative_result']);
            $data['estimateResult']['estimative_total'] = UtilsController::convertToRealBr($data['estimateResult']['estimative_total']);
        }

        return $data;
    }

    public static function updateRequest() {
        $note = filter_input(INPUT_POST, 'note');
        $ref = filter_input(INPUT_POST, 'ref');

        if($ref) {
            $requestInfo['note'] = $note;
            Request::requestUpdate($ref, $requestInfo);

            echo json_encode(true);
        }
    }

    public function cancelRequest() {
        $idRequest = intval(filter_input(INPUT_POST, 'ref'));

        if($idRequest) {
            $note = filter_input(INPUT_POST, 'note');
            $inProgress = 0;

            $requestItems = Request::getRequestItems($idRequest);
            Bills_to_pay::deleteAccounts('id_request', $idRequest);
            Bills_to_receive::deleteAccounts('id_request', $idRequest);

            // Entregas do pedido
            $deliveries = Deliverie::getDeliveries($idRequest);

            // Array de atualização do pedido
            $requestUpdate['note'] = $note;

            if($deliveries) {
                foreach ($deliveries as $key => $delivery) {
                    $deliveriesItems = Deliverie::getDeliveryItems($delivery['id']);
                    $totalDeliveries = count($deliveriesItems);

                    // Iterando nas entregas para obter quantidade de entregas ainda não realizadas
                    foreach($deliveriesItems as $item) {
                        if($item['status'] <= 3) {
                            $inProgress++;

                            // Atualizando status da entrega para cancelado
                            $itemDelivery['status'] = 7;
                            Deliverie::updateItemDelivery($itemDelivery, $item['id']);
                        }
                    }                    

                    // Verificação para definir o novo status do pedido
                    if($totalDeliveries == $inProgress) {
                        $requestUpdate['status'] = 6;
                    } else {
                        $requestUpdate['status'] = 5;
                    }

                    Request::requestUpdate($idRequest, $requestUpdate);

                    // Iteração para devolver estoque dos produtos
                    foreach ($requestItems as $productItem) {     
                        $productUpdate = array();               
                        $productRow = Product::getProduct($productItem['id_product']);
                        $amountAtual = $productRow['amount'];

                        if($productRow['id_group'] == 2) {
                            $productUpdate['amount'] = ($amountAtual + $productItem['quantity']);
                        } else if($productRow['id_group'] == 3) {
                            $productUpdate['amount'] = ($amountAtual + $delivery['balance']);
                        }

                        if($productUpdate) {
                            Product::updateProduct($productItem['id_product'], $productUpdate, '');
                        }
                    }

                    // Array de atualização da entrega(Mãe)
                    $deliverieData['status'] = 7;
                    $deliverieData['balance'] = 0;

                    Deliverie::updateDeliverie($deliverieData, $delivery['id']);
                }

            } else {
                // Iteração para devolver estoque dos produtos
                foreach ($requestItems as $productItem) {     
                    $productUpdate = array();               
                    $productRow = Product::getProduct($productItem['id_product']);
                    $amountAtual = $productRow['amount'];

                    $productUpdate['amount'] = ($amountAtual + $productItem['quantity']);

                    if($productUpdate) {
                        Product::updateProduct($productItem['id_product'], $productUpdate, '');
                    }
                }

                $requestUpdate['status'] = 6;
                Request::requestUpdate($idRequest, $requestUpdate);
            }

            echo json_encode(true);
        }
    }
    
    // Impressão do pedido
    public function printOutRequest() {
        $request = filter_input(INPUT_GET, 'r');
        
        if($request) {
            $this->arrayInfo['request'] = Request::getRequest($request);
            $this->arrayInfo['request']['user_name'] = User::getName($this->arrayInfo['request']['id_user']);
            $this->arrayInfo['requestItems'] = Request::getRequestItems($request);
            $this->arrayInfo['delivery'] = Deliverie::getDeliveries($request);

            if($this->arrayInfo['request']['percente_supporte'] > 0) {
                $this->arrayInfo['comission_info']['total_comission'] = ($this->arrayInfo['request']['percente_supporte'] * $this->arrayInfo['request']['total']) / 100;
                $this->arrayInfo['comission_info']['days_to_receiver'] = Request::getOtherInformations('request_payment_receiver', $request);
            }
            
            foreach ($this->arrayInfo['requestItems'] as $key => $pItem) {
                $product = Product::getProduct($pItem['id_product']);
                $provider = Provider::getProvider($product['id_provider'], 'providers');
                $this->arrayInfo['requestItems'][$key]['product_name'] = $product['name'];
                $this->arrayInfo['requestItems'][$key]['company_name'] = $provider['company_name'];
                
                // Formatar valores em R$
                $this->arrayInfo['requestItems'][$key]['price_sale'] = UtilsController::convertToRealBr($pItem['price_sale']);
                $this->arrayInfo['requestItems'][$key]['total'] = UtilsController::convertToRealBr($pItem['total']);
                
                // Pegar informações do produto
                // $this->arrayInfo['requestItems'][$key]['product_group'] = Product::getProductGroup($product['id_group']);
                $this->arrayInfo['requestItems'][$key]['product_unity'] = Product::getProductUnit($product['id_unity']);
                $this->arrayInfo['requestItems'][$key]['product_presentation'] = Product::getProductPresentation($product['id_presentation']);
            }
            
            if($this->arrayInfo['delivery']) {
                foreach ($this->arrayInfo['delivery'] as $key => $item) {
                    $this->arrayInfo['delivery'][$key]['info_deliveries'] = Deliverie::getDeliveryItems($item['id']);

                    foreach ($this->arrayInfo['delivery'][$key]['info_deliveries'] as $keyItem => $deliveryItem) {

                        // Formatando datas das entregas
                        $this->arrayInfo['delivery'][$key]['info_deliveries'][$keyItem]['date_deliverie'] = UtilsController::convertDate($deliveryItem['date_deliverie']);
                        $this->arrayInfo['delivery'][$key]['info_deliveries'][$keyItem]['situation_name'] = Deliverie::getSituationName($deliveryItem['status']);
                        $this->arrayInfo['delivery'][$key]['info_deliveries'][$keyItem]['farm_name'] = Farm::getFarmName($deliveryItem['id_farm']);    
                    }                    
                }
            }            

            if($this->arrayInfo['request']['pre_select_farm']) {
                $this->arrayInfo['printFarmInfo'] = Farm::getFarm($this->arrayInfo['request']['pre_select_farm']);
            } else{
                $this->arrayInfo['printFarmInfo'] = array(
                    'name' => '',
                    'state_registration' => '',
                    'responsible' => '',
                    'phone' => ''
                );
            }
            
            $this->arrayInfo['request']['total'] = UtilsController::convertToRealBr($this->arrayInfo['request']['total']);            
            $this->arrayInfo['reports_info'] = UtilsController::getConfigReports();
            $this->arrayInfo['reports_info']['other_information'] = explode(PHP_EOL, $this->arrayInfo['reports_info']['other_information']);
            $this->arrayInfo['clientInfo'] = Client::getClient($this->arrayInfo['request']['id_client']);
            
            $this->arrayInfo['requestInput'] = Request::getOtherInformations('request_input', $request);
            $this->arrayInfo['requestFreight'] = Request::getOtherInformations('request_freight', $request);

            if($this->arrayInfo['requestInput']) {
                if($this->arrayInfo['requestInput']['how_dilute_input']) {
                    switch ($this->arrayInfo['requestInput']['how_dilute_input']) {
                        case 1:
                            $this->arrayInfo['requestInput']['how_dilute_input'] = 'Não Informado';
                            break;
                        case 2:
                            $this->arrayInfo['requestInput']['how_dilute_input'] = 'Abater % em todas as entregas';
                            break;
                        case 3:
                            $this->arrayInfo['requestInput']['how_dilute_input'] = 'Abater % na última entrega';
                            break;
                    }
                }
            } else {
                $this->arrayInfo['requestInput'] = array();
            }

            if(!$this->arrayInfo['requestFreight']) {
                $this->arrayInfo['requestFreight'] = array();
            }

            // print_r($this->arrayInfo);exit;
            
            ob_start();
            
            $this->render('printout_request', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'array' => $this->arrayInfo,
                'titlePage' => $this->arrayInfo['clientInfo']['name']
            ]);
            
            $html = ob_get_contents();
            ob_end_clean();

            $mpdf = new \Mpdf\Mpdf();
            $mpdf->WriteHTML($html);
            $mpdf->Output();
        }
    }
    
    // Calcular margem de lucro produto    
    public function calculateProfitValue() {
        $coustPrice = filter_input(INPUT_POST, 'costprice');
        $priceSale = filter_input(INPUT_POST, 'pricesale');

        if($coustPrice && $priceSale) {
            $coustPrice = UtilsController::convertPriceToDb($coustPrice);
            $priceSale = UtilsController::convertPriceToDb($priceSale);

            $valueProfit = ($priceSale - $coustPrice);
            $percentProfit = ($valueProfit / $priceSale) * 100;

            echo json_encode(number_format($percentProfit, 2, ',', ''));
        }
    }
}