<?php
namespace src\controllers;

use \core\Controller;
use \src\handlers\CityHandler;
use \src\handlers\FiltersHandler;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\controllers\UtilsController;
use \src\models\City;
use \src\models\Provider;
use \src\models\Salesman;

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

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

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

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

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


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

        // Buscando fornecedores de produtos
        $providersList = Provider::getProviders($offset, $limit, $filter, 'providers');

        foreach ($providersList as $key => $provider) {
            $providersList[$key]['city_name'] = City::getName($provider['city']);
        }
        $users_count = Provider::getCount($filter, 'providers');
        $this->arrayInfo['p_count'] = ceil( $users_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_provider'];

        $this->render('providers', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'providersList' => $providersList,
            'title' => 'Fornecedores',
            'linkPagination' => 'providers',
            'linkEdit' => '&of=1',
            'titlePage' => 'Fornecedores - Supporte Agronegócios'
        ]);
    }

    // Fornecedores de serviços
    public function providerService() {
        $emptyFilter = [
            'searchType' => '1',
            'opt' => '',
            'tag' => ''
        ];

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

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


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


        // Buscando fornecedores de Serviços
        $providersList = Provider::getProviders($offset, $limit, $filter, 'providers_services');

        foreach ($providersList as $key => $provider) {
            $providersList[$key]['city_name'] = City::getName($provider['city']);
        }

        $users_count = Provider::getCount($filter, 'providers_services');
        $this->arrayInfo['p_count'] = ceil( $users_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_providerservice'];

        $this->render('providers', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => 'providerservice',
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'providersList' => $providersList,
            'title' => 'Fornecedores de Serviços',
            'linkPagination' => 'providerservice',
            'linkEdit' => '&of=2',
            'titlePage' => 'Fornecedores - Supporte Agronegócios'
        ]);
    }

    public function add() {
        $error = array();
        $post = array();
        $states = CityHandler::getStates();

        if(isset($_SESSION['msg'])) {
            $error['alertType'] = $_SESSION['alertType'];
            $error['msg'] = $_SESSION['msg'];
            $post = $_SESSION['post'];
            unset($_SESSION['msg'], $_SESSION['alertType'], $_SESSION['post']);
        }

        $this->render('providers_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'states' => $states,
            'error' => $error,
            'form' => $post,
            'titlePage' => 'Adicionar Fornecedor - Supporte Agronegócios'
        ]);
    }

    public function addAction() {
        if(!empty($_POST['company_name']) && !empty($_POST['fantasy_name'])) {
            $post = $_POST;
            
            $provider['provider_of'] = filter_input(INPUT_POST, 'provider_service');
            $provider['type'] = filter_input(INPUT_POST, 'type');
            $provider['rg'] = filter_input(INPUT_POST, 'rg');
            $provider['cpf'] = filter_input(INPUT_POST, 'cpf');
            $provider['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $provider['state_registration'] = filter_input(INPUT_POST, 'state_registration');
            $provider['company_name'] = filter_input(INPUT_POST, 'company_name');
            $provider['fantasy_name'] = filter_input(INPUT_POST, 'fantasy_name');
            $provider['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $provider['cep'] = filter_input(INPUT_POST, 'cep');
            $provider['public_place'] = filter_input(INPUT_POST, 'public_place');
            $provider['state'] = filter_input(INPUT_POST, 'state');
            $provider['city'] = filter_input(INPUT_POST, 'city');
            $provider['location'] = filter_input(INPUT_POST, 'location');
            $provider['contact_name'] = filter_input(INPUT_POST, 'contact_name');
            $provider['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $provider['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $provider['birth_date'] = filter_input(INPUT_POST, 'birth_date');
            $provider['note'] = filter_input(INPUT_POST, 'note');

            // Verificando se existe informações de pagameto e recebimento de comissão
            if(isset($_POST['provider_receiver_day']) && !empty($_POST['provider_receiver_day'])) {
                $provider['receiver_provider_day'] = intval(filter_input(INPUT_POST, 'provider_receiver_day'));
            }

            if(isset($_POST['provider_payment_day']) && !empty($_POST['provider_payment_day'])) {
                $provider['payment_provider_day'] = intval(filter_input(INPUT_POST, 'provider_payment_day'));
            }

            if($provider['provider_of'] == 1) {

                $table = 'providers';

            } else if($provider['provider_of'] == 2) {

                $table = 'providers_services';
            }

            if($provider['cpf']) {
                if(UtilsController::verifyProviderIdentify('cpf', $provider['cpf'], 14, $table)) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "CPF Incorreto e/ou já cadastrado!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/addprovider');
                }
            }

            if($provider['cnpj']) {
                if(UtilsController::verifyProviderIdentify('cnpj', $provider['cnpj'], 18, $table)) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "CNPJ Incorreto e/ou já cadastrado!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/addprovider');
                }
            }

            if($provider['rg']) {
                if(Provider::existsProviderRg('rg', $provider['rg'])) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "RG Incorreto e/ou já cadastrado!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/addprovider');
                }
            }

            if($provider['birth_date']) {
                if(!UtilsController::verifyDefaltDate($provider['birth_date'], 'intern', '<=')) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "Data de Nascimento Inválida!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/addprovider');
                }
            }

            $provider['birth_date'] = UtilsController::convertDate($provider['birth_date']);

            Provider::saveProvider($provider, $table);
            $this->redirect('/providers');
        }
    }

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

        if($provider) {
            $error = array();
            $providerOf = intval(filter_input(INPUT_GET, 'of'));

            if($providerOf == 1) {
                $table = 'providers';
                $returnUrl = 'providers';
            } else if($providerOf == 2) {
                $table = 'providers_services';
                $returnUrl = 'providerservice';
            }

            $states = CityHandler::getStates();
            $providerInfo = Provider::getProvider($provider, $table);
            $providerInfo['city_name'] = City::getName($providerInfo['city']);
            $providerInfo['birth_date'] = UtilsController::convertDate($providerInfo['birth_date']);

            if(isset($_SESSION['msg'])) {
                $error['alertType'] = $_SESSION['alertType'];
                $error['msg'] = $_SESSION['msg'];
                unset($_SESSION['msg'], $_SESSION['alertType']);
            }

            $this->render('providers_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'states' => $states,
                'error' => $error,
                'form' => $providerInfo,
                'returnUrl' => $returnUrl,
                'titlePage' => 'Editar Fornecedor - Supporte Agronegócios'
            ]);
        }
    }

    public function editAction() {
        if(!empty($_POST['id']) && !empty($_POST['company_name']) && !empty($_POST['fantasy_name'])) {
            $post = $_POST;
            $providerOf = intval(filter_input(INPUT_POST, 'provider_of'));
            $providerId = filter_input(INPUT_POST, 'id');
            $provider['status'] = filter_input(INPUT_POST, 'status');
            $provider['type'] = filter_input(INPUT_POST, 'type');
            $provider['rg'] = filter_input(INPUT_POST, 'rg');
            $provider['cpf'] = filter_input(INPUT_POST, 'cpf');
            $provider['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $provider['state_registration'] = filter_input(INPUT_POST, 'state_registration');
            $provider['company_name'] = filter_input(INPUT_POST, 'company_name');
            $provider['fantasy_name'] = filter_input(INPUT_POST, 'fantasy_name');            
            $provider['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $provider['cep'] = filter_input(INPUT_POST, 'cep');
            $provider['public_place'] = filter_input(INPUT_POST, 'public_place');
            $provider['state'] = filter_input(INPUT_POST, 'state');
            $provider['city'] = filter_input(INPUT_POST, 'city');
            $provider['location'] = filter_input(INPUT_POST, 'location');
            $provider['contact_name'] = filter_input(INPUT_POST, 'contact_name');
            $provider['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $provider['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $provider['birth_date'] = filter_input(INPUT_POST, 'birth_date');
            $provider['note'] = filter_input(INPUT_POST, 'note');

            // Verificando se existe informações de pagameto e recebimento de comissão
            if(isset($_POST['provider_receiver_day']) && !empty($_POST['provider_receiver_day'])) {
                $provider['receiver_provider_day'] = intval(filter_input(INPUT_POST, 'provider_receiver_day'));
            }

            if(isset($_POST['provider_payment_day']) && !empty($_POST['provider_payment_day'])) {
                $provider['payment_provider_day'] = intval(filter_input(INPUT_POST, 'provider_payment_day'));
            }

            if($provider['birth_date']) {
                if(!UtilsController::verifyDefaltDate($provider['birth_date'], 'intern', '<=')) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "Data de Nascimento Inválida!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/addprovider');
                }
            }

            if($providerOf == 1) {
                $table = 'providers';
                $returnUrl = '/providers';
            } else if($providerOf == 2) {
                $table = 'providers_services';
                $returnUrl = '/providerservice';
            }

            $provider['status'] = ($provider['status'] == 1)? intval(1) : intval(0) ;
            $provider['birth_date'] = UtilsController::convertDate($provider['birth_date']);
            Provider::updateProvider($providerId, $provider, $table);
            $this->redirect($returnUrl);
        }
    }

    public function updateStatus() {
        $provider = filter_input(INPUT_POST, 'provider');
        $astatus = filter_input(INPUT_POST, 'status');
        $providerOf = filter_input(INPUT_POST, 'provider_of');

        if($provider) {
            $status = ($astatus == 1)? intval(0) : intval(1) ;

            if($providerOf == 1) {
                $table = 'providers';
            } else if($providerOf == 2) {
                $table = 'providers_services';
            }

            Provider::update(['status' => $status])
                ->table($table)
                ->where('id', $provider)
            ->execute();

            echo json_encode(true);
        }
    }

    public function searchProviders() {
        $text = filter_input(INPUT_POST, 'text');
        $response = '';

        if($text) {
            $result = Provider::searchByText($text);

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

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

    public function getProviderInfo() {
        $provider = filter_input(INPUT_POST, 'provider');
        // $salesman = filter_input(INPUT_POST, 'salesman');

        if($provider) {
            $result = Provider::getProvider($provider, 'providers');            

            echo json_encode($result);                     
        }
    }
}