<?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\Shipping_company;

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

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

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

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

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


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

        $shippingList = Shipping_company::getShippings($offset, $limit, $filter);
        foreach ($shippingList as $key => $shipping) {            
            if(!empty($shipping['city'])) {
                $shippingList[$key]['city_name'] = City::getName($shipping['city']);
            }
        }
        $users_count = Shipping_company::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $users_count / $limit );
        $this->arrayInfo['filter'] = $_SESSION['filter_shipping'];

        $this->render('shipping_company', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'arrayInfo' => $this->arrayInfo,
            'shippingList' => $shippingList,
            'titlePage' => 'Transportadoras - 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('shipping_company_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'states' => $states,
            'error' => $error,
            'form' => $post,
            'titlePage' => 'Adicionar Transportador - Supporte Agronegócios'
        ]);
    }

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

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

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

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

            $shipping['birth_date'] = UtilsController::convertDate($shipping['birth_date']);
            Shipping_company::saveShipping($shipping, $note);
            $this->redirect('/shippingcompany');
        }
    }

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

        if(!$shipping) {
            $shipping = $_SESSION['shippingEditing'];
        }

        if($shipping) {
            $error = array();
            $states = CityHandler::getStates();
            $shippingInfo = Shipping_company::getShipping($shipping);
            
            if($shippingInfo['city']) {
                $shippingInfo['city_name'] = City::getName($shippingInfo['city']); 
            }

            if($shippingInfo['birth_date']) {
                $shippingInfo['birth_date'] = UtilsController::convertDate($shippingInfo['birth_date']);
            }

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

            $this->render('shipping_company_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'states' => $states,
                'error' => $error,
                'form' => $shippingInfo,
                'titlePage' => 'Editar Transportadora - Supporte Agronegócios'
            ]);
        }
    }

    public function editAction() {
        if(!empty($_POST['id']) && !empty($_POST['company_name']) && !empty($_POST['fantasy_name'])) {
            $shippingId = filter_input(INPUT_POST, 'id');
            $shipping['status'] = filter_input(INPUT_POST, 'status');
            $shipping['type'] = filter_input(INPUT_POST, 'type');
            $shipping['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $shipping['cpf'] = filter_input(INPUT_POST, 'cpf');            
            $shipping['state_registration'] = filter_input(INPUT_POST, 'state_registration');
            $shipping['company_name'] = filter_input(INPUT_POST, 'company_name');
            $shipping['fantasy_name'] = filter_input(INPUT_POST, 'fantasy_name');
            $shipping['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $shipping['cep'] = filter_input(INPUT_POST, 'cep');
            $shipping['public_place'] = filter_input(INPUT_POST, 'public_place');
            $shipping['state'] = filter_input(INPUT_POST, 'state');
            $shipping['city'] = filter_input(INPUT_POST, 'city');
            $shipping['bank_data'] = filter_input(INPUT_POST, 'bank_data');
            $shipping['contact_name'] = filter_input(INPUT_POST, 'contact_name');
            $shipping['birth_date'] = filter_input(INPUT_POST, 'birthdateShipping');            
            $shipping['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $shipping['first_phone'] = filter_input(INPUT_POST, 'first_phone');            
            $note = filter_input(INPUT_POST, 'note');

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

            $shipping['status'] = ($shipping['status'] == 1)? intval(1) : intval(0) ;
            $shipping['birth_date'] = UtilsController::convertDate($shipping['birth_date']);
            Shipping_company::updateShipping($shippingId, $shipping, $note);
            $this->redirect('/shippingcompany');
        }
    }

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

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

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

            echo json_encode(true);
        }
    }
}