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

class ProductsController 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 = 'products';
        $this->paramsName = PermissionHandler::getPermissions($this->loggedUser->group);

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

    public function index() {
        $emptyFilter = [
            'searchProvider' => '',
            'onlystock' => 'on',
            'searchType' => '1',
            'searchTerm' => '',
            'opt' => '',
            'tag' => ''
        ];

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

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


        if(!isset($_SESSION['filter_products'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_products'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_products']['searchType'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_products']['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::filterProducts($_SESSION['filter_products']);

        $this->arrayInfo['listProducts'] = Product::getList($offset, $limit, $filter);

        foreach ($this->arrayInfo['listProducts'] as $key => $product) {
            $this->arrayInfo['listProducts'][$key]['cost_price'] = UtilsController::convertToRealBr($product['cost_price']);
            $this->arrayInfo['listProducts'][$key]['price'] = UtilsController::convertToRealBr($product['price']);
            $this->arrayInfo['listProducts'][$key]['provider'] = Provider::getProviderName($product['id_provider']);
            $this->arrayInfo['listProducts'][$key]['group_p'] = Product::getProductGroup($product['id_group']);
            $this->arrayInfo['listProducts'][$key]['unity'] = Product::getProductUnit($product['id_unity']);
            $this->arrayInfo['listProducts'][$key]['presentation'] = Product::getProductPresentation($product['id_presentation']);
        }

        $users_count = Product::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $users_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_products'];

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

    public function add() {
        $providers = Provider::getAll();
        $groups = Product::allProductGroup();
        $units = Product::allProductUnit();
        $presentations = Product::allProductPresentation();

        $this->render('products_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'providers' => $providers,
            'groups' => $groups,
            'units' => $units,
            'presentations' => $presentations,
            'titlePage' => 'Adicionar Produto - Supporte Agronegócios'
        ]);
    }

    public function addAction() {
        $product['name'] = filter_input(INPUT_POST, 'name');
        $product['id_provider'] = filter_input(INPUT_POST, 'provider');
        $product['id_group'] = filter_input(INPUT_POST, 'group');
        $product['id_unity'] = filter_input(INPUT_POST, 'unity');
        $product['id_presentation'] = filter_input(INPUT_POST, 'presentation');
        $product['price'] = filter_input(INPUT_POST, 'price');
        $product['comission_value'] = filter_input(INPUT_POST, 'value_comission');
        $product['created_at'] = date('Y-m-d');
        $product['updated_at'] = date('Y-m-d');
        $note = filter_input(INPUT_POST, 'note');

        $product['price'] = UtilsController::convertPriceToDb($product['price']);
        $product['comission_value'] = UtilsController::convertPriceToDb($product['comission_value']);

        if($product['name'] && $product['id_provider'] && $product['id_group'] && $product['id_unity'] && $product['id_presentation']) {
            Product::saveProduct($product, $note);
            $this->redirect('/products');
        }
    }

    public function edit() {
        $product = filter_input(INPUT_GET, 'p');

        if($product) {
            $productInfo = Product::getProduct($product);
            $providers = Provider::getAll();
            $groups = Product::allProductGroup();
            $units = Product::allProductUnit();
            $presentations = Product::allProductPresentation();

            // Formatar moedas
            $productInfo['price'] = UtilsController::convertToRealBr($productInfo['price']);
            $productInfo['cost_price'] = UtilsController::convertToRealBr($productInfo['cost_price']);
            $productInfo['comission_value'] = str_replace('.', ',', $productInfo['comission_value']);

            $this->render('products_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'providers' => $providers,
                'groups' => $groups,
                'units' => $units,
                'presentations' => $presentations,
                'productInfo' => $productInfo,
                'titlePage' => 'Editar Produto - Supporte Agronegócios'
            ]);
        }
    }

    public function editAction() {
        $idProduct = filter_input(INPUT_POST, 'id');
        $product['status'] = filter_input(INPUT_POST, 'status');
        $product['name'] = filter_input(INPUT_POST, 'name');
        $product['id_provider'] = filter_input(INPUT_POST, 'provider');
        $product['id_group'] = filter_input(INPUT_POST, 'group');
        $product['id_unity'] = filter_input(INPUT_POST, 'unity');
        $product['id_presentation'] = filter_input(INPUT_POST, 'presentation');
        $product['cost_price'] = filter_input(INPUT_POST, 'cost_price');
        $product['price'] = filter_input(INPUT_POST, 'price');
        $product['comission_value'] = filter_input(INPUT_POST, 'value_comission');
        $product['updated_at'] = date('Y-m-d');
        $note = filter_input(INPUT_POST, 'note');

        $product['status'] = ($product['status'] == 2)? 0 : 1;
        $product['cost_price'] = UtilsController::convertPriceToDb($product['cost_price']);
        $product['comission_value'] = UtilsController::convertPriceToDb($product['comission_value']);
        $product['price'] = UtilsController::convertPriceToDb($product['price']);

        if($idProduct && $product['name'] && $product['id_provider'] && $product['id_group'] && $product['id_unity'] && $product['id_presentation']) {
            Product::updateProduct($idProduct, $product, $note);
            $this->redirect('/products');
        }
    }

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

        if($product) {
            $response = array();
            $response['product'] = Product::getProduct($product);
            $response['group'] = Product::getProductGroup($response['product']['id_group']);
            $response['unity'] = Product::getProductUnit($response['product']['id_unity']);
            $response['presentation'] = Product::getProductPresentation($response['product']['id_presentation']);

            echo json_encode($response);
        }
    }

    public function productsFromProvider() {
        $provider = filter_input(INPUT_POST, 'provider');

        if($provider) {
            $products = Product::getAllFromProvider($provider);

            echo json_encode($products);
        }
    }

    public function productsProviderWStock() {
        $provider = filter_input(INPUT_POST, 'provider');
        $typeRequest = 2;

        if(isset($_SESSION['typeRequest']) && !empty($_SESSION['typeRequest'])) {
            $typeRequest = intval($_SESSION['typeRequest']);
        }


        if($provider) {
            if($typeRequest == 1) {
                $products = Product::getAllFromProvider($provider);
            } elseif($typeRequest == 2) {
                $products = Product::allFromProviderWStock($provider);
            }            

            if($products) {
                foreach ($products as $key => $product) {
                    $products[$key]['price'] = UtilsController::convertToRealBr($product['price']);
                    $products[$key]['cost_price'] = UtilsController::convertToRealBr($product['cost_price']);
                    $products[$key]['group_name'] = Product::getProductGroup($product['id_group']);
                    $products[$key]['unity_name'] = Product::getProductUnit($product['id_unity']);
                    $products[$key]['presentation_name'] = Product::getProductPresentation($product['id_presentation']);
                    $products[$key]['value_comission'] = str_replace('.', ',', $product['comission_value']);
                }
            }
            echo json_encode($products);
        }
    }

    // Busca de produtos via Ajax
    public function searchProducts() {
        $text = filter_input(INPUT_POST, 'text');
        $response = '';

        if($text) {
            $result = Product::searchProductByText($text);

            if($result) {
                $response = '<ul>';
                
                foreach($result as $item) {
                    $response .= '<li data-list="'.$item['id'].'">';
                    $response .= $item['name'];
                    $response .= '</li>';
                }

                $response .= "</ul>";
            }            
        }        
        echo json_encode($response);
    }
}