<?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\models\Bills_to_pay;
use \src\models\Provider;
use \src\models\Product;
use \src\models\Purchase;

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

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

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

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

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

    public function index() {
        $emptyFilter = [
            'searchType' => '',
            'searchProduct' => '',
            'searchProvider' => '',
            'opt' => '',
            'tag' => ''
        ];

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

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


        if(!isset($_SESSION['filter_purchases'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_purchases'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_purchases']['searchType'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_purchases']['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::filterPurchases($_SESSION['filter_purchases']);
        $productList = Product::getAll();
        $providerList = Provider::getAll();
        $purchasesList = Purchase::getPurchases($offset, $limit, $filter);

        foreach ($purchasesList as $key => $purchase) {            
            $purchasesList[$key]['note_date'] = UtilsController::convertDate($purchase['note_date']);
            $purchasesList[$key]['total_amount'] = UtilsController::convertToRealBr($purchasesList[$key]['total_amount']);
            $purchasesList[$key]['total_advance'] = ($purchase['advance'] * $purchase['total_amount'] / 100);
            $purchasesList[$key]['total_advance'] = UtilsController::convertToRealBr($purchasesList[$key]['total_advance']);
            $purchasesList[$key]['product'] = Purchase::getProductPurchase($purchase['id']);
            $purchasesList[$key]['provider'] = Provider::getProviderName($purchase['id_provider']);
            $purchasesList[$key]['form_to_pay'] = Bills_to_pay::getBtp('document_number', $purchase['note_number']);
        }

        $purchase_count = Purchase::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $purchase_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_purchases'];

        $this->render('purchases', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'productList' => $productList,
            'providerList' => $providerList,
            'purchasesList' => $purchasesList,
            'titlePage' => 'Compras - Supporte Agronegócios'
        ]);
    }

    public function add() {
        $productList = Product::getAll();
        $providerList = Provider::getAll();
        $billstopay = Bills_to_pay::getAllPaymentForm();

        // Zerando seções de pedidos, para iniciar novamente
        unset($_SESSION['purshase'], $_SESSION['total_amount'], $_SESSION['purshase_items'], $_SESSION['items_to_show']);

        $_SESSION['purshase'] = array();
        $_SESSION['total_amount'] = 0;
        $_SESSION['purshase_items'] = array();
        $_SESSION['items_to_show'] = array();

        $this->render('purchases_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'productList' => $productList,
            'providerList' => $providerList,
            'payment_form' => $billstopay,
            'titlePage' => 'Adicionar Compra - Supporte Agronegócios'
        ]);
    }

    public function addItem() {
        $item = filter_input(INPUT_POST, 'item', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

        if($item) {
            // Iniciando a compra, dados gerais da compra
            $_SESSION['purshase'] = [
                'note_number' => $item['note_number'],
                'provider' => $item['provider'],
                'note_date' => $item['note_date']
            ];

            // Dados relacionados a valores da compra(Total do Item/Total da compra)
            $valueItem = UtilsController::convertPriceToDb($item['product_price']);
            $totalItem = ($item['quantity'] * $valueItem);

            $_SESSION['total_amount'] += $totalItem;

            $itemReceived = [
                'override' => $item['override'],
                'group' => $item['group'],
                'product' => $item['product'],
                'unity' => $item['unity'],
                'presentation' => $item['presentation'],
                'quantity' => $item['quantity'],
                'product_price' => $valueItem,
                'total' => $totalItem
            ];
            array_push($_SESSION['purshase_items'], $itemReceived);

            // Gerando array de produtos da compra para exibir ao usuário
            $itemToShow = [
                'productId' => $item['product'],
                'productName' => Product::getName($item['product']),
                'quantity' => $item['quantity'],
                'priceItem' => $item['product_price'],
                'total' => UtilsController::convertToRealBr($totalItem),
                'group' => Product::getProductGroup($item['group']),
                'unity' => Product::getProductUnit($item['unity']),
                'presentation' => Product::getProductPresentation($item['presentation'])
            ];
            array_push($_SESSION['items_to_show'], $itemToShow);

            $response['status'] = true;
            $response['items_show'] = $_SESSION['items_to_show'];
            $response['total_amount'] = UtilsController::convertToRealBr($_SESSION['total_amount']);
            $response['count'] = count($_SESSION['purshase_items']);
            echo json_encode($response);
        }
    }

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

        if($product) {
            $removeKey = '';
            $valueItem = 0;
            $countItems = count($_SESSION['purshase_items']);

            // Produrar no array de produtos o selecionado para remover
            for($i=0;$i<$countItems;$i++) {
                if($_SESSION['purshase_items'][$i]['product'] == $product) {
                    $removeKey = $i;
                    $valueItem = $_SESSION['purshase_items'][$i]['total'];
                    break;
                }
            }

            unset($_SESSION['purshase_items'][$removeKey]);
            unset($_SESSION['items_to_show'][$removeKey]);
            $_SESSION['purshase_items'] = array_values($_SESSION['purshase_items']);
            
            $priceReduce = UtilsController::convertPriceToDb($valueItem);

            $_SESSION['total_amount'] = ($_SESSION['total_amount'] - $priceReduce);
            $response['total_amount'] = UtilsController::convertToRealBr($_SESSION['total_amount']);
            $response['count'] = count($_SESSION['purshase_items']);
            $response['status'] = true;

            echo json_encode($response);
        }
    }

    public function savePurchase() {
        if($_SESSION['purshase'] && $_SESSION['purshase_items'] && $_SESSION['total_amount']) {
            $firstPayment = filter_input(INPUT_POST, 'firstPayment');
            $daysPayment = filter_input(INPUT_POST, 'daysPayment');
            $type_payment = filter_input(INPUT_POST, 'type_payment');
            $payment_form = filter_input(INPUT_POST, 'pay_form');
            $advance = filter_input(INPUT_POST, 'percent_advance'); // Adiantamento em %tagem
            $advance = (!empty($advance))? $advance : 0 ;

            if($type_payment == 'Integral') {
                $qtdPayments = filter_input(INPUT_POST, 'qtd_payment');
            } else {
                $qtdPayments = filter_input(INPUT_POST, 'advance_qtd_payment');
            }

            $purchase['id_user'] = $this->loggedUser->id;
            $purchase['id_provider'] = $_SESSION['purshase']['provider'];
            $purchase['id_payment_form'] = $payment_form;
            $purchase['note_number'] = $_SESSION['purshase']['note_number'];
            $purchase['note_date'] = UtilsController::convertDate($_SESSION['purshase']['note_date']);
            $purchase['release_date'] = date('Y-m-d');
            $purchase['total_amount'] = $_SESSION['total_amount'];
            $purchase['payment_type'] = $type_payment;
            $purchase['advance'] = $advance;

            // Salvando a compra
            $pId = Purchase::purchaseSave($purchase);

            // Salvando os itens da compra
            $items = $_SESSION['purshase_items'];

            foreach ($items as $item) {
                $productRow = Product::getProduct($item['product']);

                if($item['override'] == 1) {                    
                    $newCostPrice = $item['product_price'];
                    $newStock = $item['quantity'];                    
                } else {

                    if($productRow['amount'] > 0) {
                        $totalItemReceived = $item['total'];
                        $totalProductRow = ($productRow['amount'] * $productRow['cost_price']);
                        $totalProwAndReceived = ($item['quantity'] + $productRow['amount']);

                        $newCostPrice = ($totalItemReceived + $totalProductRow) / $totalProwAndReceived;
                        $newStock = ($productRow['amount'] + $item['quantity']);
                    } else {
                        $newCostPrice = $item['product_price'];
                        $newStock = $item['quantity'];
                    }
                }

                $product['amount'] = $newStock;
                $product['cost_price'] = $newCostPrice;

                Product::updateProduct($item['product'], $product, '');
                $itemPurchase = self::getObjectItem($pId, $item);
                Purchase::insertItems($itemPurchase);
            }

            // Iniciar inserção de purchase payments e criação de contas a pagar
            $firstPayment = UtilsController::convertDate($firstPayment);            
            $advanceValue = ($advance * $purchase['total_amount']) / 100;

            if($items[0]['group'] == '3') {
                $total_amount = $advanceValue;
            } else {
                $total_amount = ($purchase['total_amount'] - $advanceValue);
            }
            
            $pricePayment = ($total_amount / $qtdPayments);

            for($i=0; $i<$qtdPayments; $i++) {
                $days = $i * $daysPayment;
                $datePayment = date('Y-m-d', strtotime('+'.$days.'days', strtotime($firstPayment)));

                $purchasePayments['id_purchase'] = $pId;
                $purchasePayments['date_payment'] = $datePayment;
                $purchasePayments['price'] = $pricePayment;

                $refPayment = Purchase::insertPayment($purchasePayments);

                // enviar informações para criação do contas a pagar
                self::initPurchaseAccount($pId, $refPayment, $purchase, $datePayment, $advance, $pricePayment, $qtdPayments, $payment_form);
            }
        }

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

    public function viewPurchase() {
        $purchaseId = filter_input(INPUT_GET, 'p');

        if($purchaseId) {
            $purchase = Purchase::getPurchase($purchaseId);
            $purchase['totalAdvance'] = ($purchase['advance'] * $purchase['total_amount']) / 100;
            $purchase['provider_name'] = Provider::getProviderName($purchase['id_provider']);
            $purchase['total_amount'] = UtilsController::convertToRealBr($purchase['total_amount']);
            $purchase['totalAdvance'] = UtilsController::convertToRealBr($purchase['totalAdvance']);
            $purchase['c_payments'] = Purchase::countPayments($purchaseId);
            $purchaseItems = Purchase::getProductsPurchase($purchaseId);
            $purchasePayments = Purchase::getPurchasePayments($purchaseId);
            $payment_form = Bills_to_pay::getAllPaymentForm();

            foreach ($purchaseItems as $key => $item) {
                $purchaseItems[$key]['product'] = Product::getName($item['id_product']);
                $purchaseItems[$key]['group_p'] = Product::getProductGroup($item['id_product_group']);                
                $purchaseItems[$key]['unity'] = Product::getProductUnit($item['id_products_units']);                
                $purchaseItems[$key]['presentation'] = Product::getProductPresentation($item['id_products_presentation']);

                $purchaseItems[$key]['product_price'] = UtilsController::convertToRealBr($purchaseItems[$key]['product_price']);
                $purchaseItems[$key]['total'] = UtilsController::convertToRealBr($purchaseItems[$key]['total']);
            }

            $this->render('purchases_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'purchase' => $purchase,
                'purchaseItems' => $purchaseItems,
                'payment_form' => $payment_form,
                'purchasePayments' => $purchasePayments,
                'titlePage' => 'Vizualizar Compra - Supporte Agronegócios'
            ]);
        }
    }

    // Montando o Objeto com os dados dos itens de compra
    private static function getObjectItem($pId, $item) {
        $response = array();

        $response['id_purchase'] = $pId;
        $response['id_product'] = $item['product'];
        $response['id_product_group'] = $item['group'];
        $response['id_products_units'] = $item['unity'];
        $response['id_products_presentation'] = $item['presentation'];
        $response['quantity'] = $item['quantity'];
        $response['product_price'] = $item['product_price'];
        $response['total'] = $item['total'];

        return $response;
    }

    // Monstando Objeto para salvar em contas a pagar
    private static function initPurchaseAccount($pId, $refPayment, $purchase, $datePayment, $advance, $pricePayment, $qtdPayments, $payment_form) {
        $purchaseObject = array();
        $advance = ($advance / $qtdPayments);

        $purchaseObject['copied'] = 0;
        $purchaseObject['id_user'] = $purchase['id_user'];
        $purchaseObject['id_purchase'] = $pId;
        $purchaseObject['id_purchase_payment'] = $refPayment;
        $purchaseObject['id_provider'] = $purchase['id_provider'];
        $purchaseObject['provider_description'] = Provider::getProviderName($purchase['id_provider']);
        $purchaseObject['billstopay_type'] = 3;
        $purchaseObject['billstopay_description'] = "Pgto de Fornecedor";
        $purchaseObject['form_to_pay'] = $payment_form;
        $purchaseObject['form_to_pay_description'] = Bills_to_pay::getPaymentForm($payment_form);
        $purchaseObject['document_date'] = $purchase['note_date'];
        $purchaseObject['expirate_date'] = $datePayment;
        $purchaseObject['document_number'] = $purchase['note_number'];
        $purchaseObject['main_value'] = $pricePayment;
        $purchaseObject['advance_value'] = $advance;
        $purchaseObject['value_to_pay'] = $pricePayment;
        $purchaseObject['residual_value'] = $pricePayment;
        $purchaseObject['id_situation'] = 2;

        Bills_to_pay::saveAcount($purchaseObject);
    }

    public function getAdvancePurchase() {
        $advance = filter_input(INPUT_POST, 'advance');

        if($advance) {
            $total_amount = $_SESSION['total_amount'];

            $valueAdvance = ($advance * $total_amount) / 100;
            $response = UtilsController::convertToRealBr($valueAdvance);
            echo json_encode($response);
        }        
    }

    public function verifyExistsNote() {
        $note = filter_input(INPUT_POST, 'note');

        if($note) {            
            $response = Purchase::existsNote($note);
            echo json_encode($response);
        }
    }

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

        if($date) {            
            $response = UtilsController::verifyNoteDate($date, '<=');
            echo json_encode($response);
        }
    }

    public function delete() {
        $purchase = filter_input(INPUT_GET, 'purchase');

        if($purchase) {
            $refUser = $this->loggedUser->id;
            $dateUpdate = date('Y-m-d');
            $data['status'] = 3;

            $paymentPurchase = Purchase::getPurchasePayments($purchase);
            $itemsPurchase = Purchase::getProductsPurchase($purchase);

            foreach($paymentPurchase as $item) {
                Bills_to_pay::updateAccount('id_purchase_payment', $item['id'], $data);
            }

            foreach($itemsPurchase as $item) {
                $product = Product::getProduct($item['id_product']);

                $currentStock = $product['amount'];
                $decreaseStock = $item['quantity'];

                $prodUp['amount'] = ($currentStock - $decreaseStock);
                Product::updateProduct($item['id_product'], $prodUp, '');
            }

            Purchase::updatePurchase($purchase, $data);
            echo json_encode(true);
        }
    }
}