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

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

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

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

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

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


        if(!isset($_SESSION['filter_salesman'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_salesman'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_salesman']['searchType'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_salesman']['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::filterSalesman($_SESSION['filter_salesman']);
        $salesmanList = Salesman::getSalesmans($offset, $limit, $filter);        
        $users_count = Salesman::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $users_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_salesman'];

        $this->render('salesman', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'salesmanList' => $salesmanList,
            'titlePage' => 'Vendedores - 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('salesman_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'states' => $states,
            'error' => $error,
            'form' => $post,
            'titlePage' => 'Adicionar Vendedor - Supporte Agronegócios'
        ]);
    }

    public function addAction() {
        if(!empty($_POST['name'])) {
            $post = $_POST;      
            $salesman['type'] = filter_input(INPUT_POST, 'type');
            $salesman['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $salesman['cpf'] = filter_input(INPUT_POST, 'cpf');
            $salesman['name'] = filter_input(INPUT_POST, 'name');
            $salesman['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $salesman['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $salesman['email'] = filter_input(INPUT_POST, 'email');
            $salesman['birth_date'] = filter_input(INPUT_POST, 'birthdate');
            $salesman['bank_data'] = filter_input(INPUT_POST, 'data_bank');            
            $salesman['operational_area'] = filter_input(INPUT_POST, 'operational_area');
            $note = filter_input(INPUT_POST, 'note');            

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

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

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

            $salesman['birth_date'] = UtilsController::convertDate($salesman['birth_date']);
            Salesman::saveSalesman($salesman, $note);
            $this->redirect('/salesman');
        }
    }

    public function edit() {
        $salesman = filter_input(INPUT_GET, 's');

        if($salesman) {
            $error = array();
            $states = CityHandler::getStates();
            $providersList = Provider::getAll();
            $salesmanInfo = Salesman::getSalesman($salesman);
            $salesmanInfo['birth_date'] = UtilsController::convertDate($salesmanInfo['birth_date']);

            $comissionList = Salesman::getComissionRegistered($salesman);
            $textComission = '';

            foreach ($comissionList as $key => $item) {
                if($item['value'] > 0) {
                    $textComission.= Provider::getProviderName($item['id_provider'])." - ".$item['value']."% \n";
                }
            }

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

            $this->render('salesman_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'states' => $states,
                'error' => $error,
                'form' => $salesmanInfo,
                'providers' => $providersList,
                'comission' => $textComission,
                'titlePage' => 'Editar Vendedor - Supporte Agronegócios'
            ]);
        }
    }

    public function editAction() {
        if(!empty($_POST['name'])) {
            $post = $_POST;  
            $salesmanId = filter_input(INPUT_POST, 'id');
            $salesman['status'] = filter_input(INPUT_POST, 'status');
            $salesman['type'] = filter_input(INPUT_POST, 'type');
            $salesman['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $salesman['cpf'] = filter_input(INPUT_POST, 'cpf');
            $salesman['name'] = filter_input(INPUT_POST, 'name');
            $salesman['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $salesman['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $salesman['email'] = filter_input(INPUT_POST, 'email');
            $salesman['birth_date'] = filter_input(INPUT_POST, 'birthdate');
            $salesman['bank_data'] = filter_input(INPUT_POST, 'data_bank');            
            $salesman['operational_area'] = filter_input(INPUT_POST, 'operational_area');
            $note = filter_input(INPUT_POST, 'note');

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

            $salesman['status'] = ($salesman['status'] == 1)? intval(1) : intval(0) ;
            $salesman['birth_date'] = UtilsController::convertDate($salesman['birth_date']);
            Salesman::updateSalesman($salesmanId ,$salesman, $note);
            $this->redirect('/salesman');
        }
    }

    public function updateStatus() {
        $salesman = filter_input(INPUT_POST, 'salesman');
        $astatus = filter_input(INPUT_POST, 'status');

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

            Salesman::update(['status' => $status])
                ->where('id', $salesman)
            ->execute();

            echo json_encode(true);
        }
    }

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

        if($text) {
            $result = Salesman::searchByText($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);
    }


    // Verificar se existe comissão salva para o vendedor e atualizar
    public function saveValueComission() {
        $data['id_salesman'] = filter_input(INPUT_POST, 'salesman');
        $data['id_provider'] = filter_input(INPUT_POST, 'provider');
        $data['value'] = filter_input(INPUT_POST, 'percentage');

        if($data['id_salesman'] && $data['id_provider']) {
            $ref = Salesman::verifyComission($data['id_provider'], $data['id_salesman']);
            $data['value'] = UtilsController::convertPriceToDb($data['value']);

            if(isset($ref['id'])) {
                Salesman::updateComission($data, $ref['id']);
            } else {
                Salesman::saveComission($data);
            }

            echo json_encode(true);

        } else {
            echo json_encode(false);
        }
    }

    public function getComission() {
        $data['id_salesman'] = filter_input(INPUT_POST, 'salesman');
        $data['id_provider'] = filter_input(INPUT_POST, 'provider');

        $ref = Salesman::verifyComission($data['id_provider'], $data['id_salesman']);

        if($ref['id']) {
            $response['status'] = true;
            $response['value'] = $ref['value'];
        } else {
            $response['status'] = false;
        }

        echo json_encode($response);
    }

    // Porcentagem da comissão baseado na comissão do produto selecionado
    public function getComissionPercentage() {
        $id_salesman = filter_input(INPUT_POST, 'salesman');
        $id_provider = filter_input(INPUT_POST, 'provider');
        $prod_comi_value = filter_input(INPUT_POST, 'value');

        $ref = Salesman::verifyComission($id_provider, $id_salesman);

        if($ref['id'] && $prod_comi_value) {
            $response['status'] = true;

            $y = UtilsController::convertPriceToDb($prod_comi_value);
            $z = $ref['value'];
            $x = ($z / 100) * $y;

            $response['value'] = UtilsController::convertToRealBr($x);

        } else {
            $response['status'] = false;
        }

        echo json_encode($response);
    }
}