<?php
namespace src\controllers;

use \core\Controller;
use \src\controllers\UtilsController;
use \src\handlers\CityHandler;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\handlers\FiltersHandler;
use \src\models\User;

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

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

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

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

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


        if(!isset($_SESSION['filter_users'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_users'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_users']['searchType'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_users']['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::filterUsers($_SESSION['filter_users']);
        $this->arrayInfo['usersList'] = User::getUsers($offset, $limit, $filter);

        foreach ($this->arrayInfo['usersList'] as $key => $user) {
            $this->arrayInfo['usersList'][$key]['group_name'] = PermissionHandler::getNameGroup($user['id_group']);
        }

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

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

    public function add() {
        $error = array();
        $post = array();
        $groups = PermissionHandler::getAllGroups();

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

        $this->render('users_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'groupsList' => $groups,
            'titlePage' => 'Adicionar Usuário - Supporte Agronegócios',
            'form' => $post,
            'error' => $error
        ]);
    }

    public function addAction() {
        if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['name'])) {
            $post = $_POST;

            $user['id_group'] = filter_input(INPUT_POST, 'user_group');
            $user['name'] = filter_input(INPUT_POST, 'name');
            $user['cpf'] = filter_input(INPUT_POST, 'cpf');
            $user['birth_date'] = filter_input(INPUT_POST, 'birth_date');
            $user['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $user['password'] = filter_input(INPUT_POST, 'password');
            $user['phone'] = filter_input(INPUT_POST, 'phone');            
            $note = filter_input(INPUT_POST, 'note');

            if($user['email']) {
                if(UtilsController::verifyUserEmail('email', $user['email'])) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "E-mail Incorreto e/ou já cadastrado!";
                    $_SESSION['post'] = $post;
                    $this->redirect('/adduser');
                }
            }

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

            if(!UtilsController::verifyDefaltDate($user['birth_date'], 'intern', '<=')) {
                $_SESSION['alertType'] = 'alert-warning';
                $_SESSION['msg'] = "Data Incorreta!";
                $_SESSION['post'] = $post;
                $this->redirect('/adduser');
            }

            $user['birth_date'] = UtilsController::convertDate($user['birth_date']);
            $user['password'] = md5($user['password']);
            $user['email'] = strtolower($user['email']);
            User::saveUser($user, $note);
            $this->redirect('/users');
        }
    }

    public function edit() {
        $user = filter_input(INPUT_GET, 'u');

        if(!$user) {
            $user = $_SESSION['userEditing'];
        }

        if($user) {
            $error = array();
            $groups = PermissionHandler::getAllGroups();
            $userInfo = User::getUser($user);

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

            $userInfo['birth_date'] = UtilsController::convertDate($userInfo['birth_date']);
            $this->render('users_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'groupsList' => $groups,
                'form' => $userInfo,
                'titlePage' => 'Editar Usuário - Supporte Agronegócios',
                'error' => $error
            ]);
        }
    }

    public function editAction() {
        if(!empty($_POST['id']) && !empty($_POST['email']) && !empty($_POST['name'])) {
            $post = $_POST;
            $userId = filter_input(INPUT_POST, 'id');
            $user['id_group'] = filter_input(INPUT_POST, 'user_group');
            $user['name'] = filter_input(INPUT_POST, 'name');
            $user['cpf'] = filter_input(INPUT_POST, 'cpf');
            $user['birth_date'] = filter_input(INPUT_POST, 'birth_date');
            $user['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $password = filter_input(INPUT_POST, 'password');
            $user['phone'] = filter_input(INPUT_POST, 'phone');            
            $note = filter_input(INPUT_POST, 'note');

            if(!UtilsController::verifyDefaltDate($user['birth_date'], 'intern', '<=')) {
                $_SESSION['alertType'] = 'alert-warning';
                $_SESSION['msg'] = "Data Incorreta!";
                $_SESSION['post'] = $post;
                $this->redirect('/adduser');
            }

            $user['birth_date'] = UtilsController::convertDate($user['birth_date']);
            if($password) {
                $user['password'] = md5($password);
            }            
            $user['email'] = strtolower($user['email']);
            User::updateUser($userId, $user, $note);
            $this->redirect('/users');
        }
    }

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

        if($user) {
            User::deleteUser($user);
        }

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