<?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\Interaction;
use \src\models\City;
use \src\models\Client;
use \src\models\Salesman;
use \src\models\User;

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

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

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

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

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


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

        $this->arrayInfo['clientsInfo'] = Client::getClients($offset, $limit, $filter);
        
        foreach ($this->arrayInfo['clientsInfo'] as $key => $client) {
            $this->arrayInfo['clientsInfo'][$key]['city_name'] = City::getName($client['city']);
        }

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

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

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

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

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

    public function addAction() {
        if(!empty($_POST['type']) && !empty($_POST['name']) && !empty($_POST['state']) && !empty($_POST['city'])) {
            $post = $_POST;

            $client['id_salesman'] = filter_input(INPUT_POST, 'salesman');
            $client['classification'] = filter_input(INPUT_POST, 'classification');
            $client['category'] = filter_input(INPUT_POST, 'category');
            $client['type'] = filter_input(INPUT_POST, 'type');
            $client['name'] = filter_input(INPUT_POST, 'name');
            $client['cpf'] = filter_input(INPUT_POST, 'cpf');
            $client['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $client['rg'] = filter_input(INPUT_POST, 'rg');
            $client['birth_date'] = filter_input(INPUT_POST, 'birthdate');
            $client['public_place'] = filter_input(INPUT_POST, 'public_place');
            $client['cep'] = filter_input(INPUT_POST, 'cep');
            $client['state'] = filter_input(INPUT_POST, 'state');
            $client['city'] = filter_input(INPUT_POST, 'city');
            $client['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $client['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $client['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $client['buyer'] = filter_input(INPUT_POST, 'buyer_name');
            $client['buyer_phone'] = filter_input(INPUT_POST, 'buyer_phone');
            $client['buyer_email'] = filter_input(INPUT_POST, 'buyer_email', FILTER_VALIDATE_EMAIL);
            $client['buyer_birth_date'] = filter_input(INPUT_POST, 'buyer_birthdate');
            $note = filter_input(INPUT_POST, 'note');

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

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

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

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

            Client::saveClient($client, $note);

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

    public function edit() {
        $client = filter_input(INPUT_GET, 'c');

        if($client) {
            $error = array();
            $states = CityHandler::getStates();
            $salesmanList = Salesman::getAllActive();

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

            $dataClient = Client::getClient($client);
            $dataClient['city_name'] = City::getName($dataClient['city']);
            $dataClient['birth_date'] = UtilsController::convertDate($dataClient['birth_date']);
            $dataClient['buyer_birth_date'] = UtilsController::convertDate($dataClient['buyer_birth_date']);

            $this->render('clients_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'states' => $states,
                'salesman' => $salesmanList,
                'form' => $dataClient,
                'error' => $error,
                'titlePage' => 'Editar Cliente - Supporte Agronegócios'
                
            ]);
        } else {
            $this->redirect('/clients');
        }
    }

    public function editAction() {
        if(!empty($_POST['id']) && !empty($_POST['type']) && !empty($_POST['name']) && !empty($_POST['state']) && !empty($_POST['city'])) {

            $clientId = filter_input(INPUT_POST, 'id');
            $client['status'] = filter_input(INPUT_POST, 'status');
            $client['id_salesman'] = filter_input(INPUT_POST, 'salesman');
            $client['classification'] = filter_input(INPUT_POST, 'classification');
            $client['type'] = filter_input(INPUT_POST, 'type');
            $client['category'] = filter_input(INPUT_POST, 'category');
            $client['name'] = filter_input(INPUT_POST, 'name');
            $client['cpf'] = filter_input(INPUT_POST, 'cpf');
            $client['cnpj'] = filter_input(INPUT_POST, 'cnpj');
            $client['rg'] = filter_input(INPUT_POST, 'rg');
            $client['birth_date'] = filter_input(INPUT_POST, 'birthdate');
            $client['public_place'] = filter_input(INPUT_POST, 'public_place');
            $client['cep'] = filter_input(INPUT_POST, 'cep');
            $client['state'] = filter_input(INPUT_POST, 'state');
            $client['city'] = filter_input(INPUT_POST, 'city');
            $client['email'] = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
            $client['first_phone'] = filter_input(INPUT_POST, 'first_phone');
            $client['second_phone'] = filter_input(INPUT_POST, 'second_phone');
            $client['buyer'] = filter_input(INPUT_POST, 'buyer_name');
            $client['buyer_phone'] = filter_input(INPUT_POST, 'buyer_phone');
            $client['buyer_email'] = filter_input(INPUT_POST, 'buyer_email', FILTER_VALIDATE_EMAIL);
            $client['buyer_birth_date'] = filter_input(INPUT_POST, 'buyer_birthdate');
            $note = filter_input(INPUT_POST, 'note');

            $client['status'] = ($client['status'] == 1)? intval(1) : intval(0) ;
            $client['birth_date'] = UtilsController::convertDate($client['birth_date']);
            $client['buyer_birth_date'] = UtilsController::convertDate($client['buyer_birth_date']);

            // Buscar dados do cliente a ser atualizado para verificar se mudou o vendedor
            $clientData = Client::getClient($clientId);

            if($clientData['id_salesman'] != $client['id_salesman']) {
                $notification['id_user'] = $client['id_salesman'];
                $notification['title'] = 'Você recebeu um novo cliente';
                $notification['message'] = 'O atendimento do cliente '.$client['name'].', foi tranferido para você.';

                User::saveNotification($notification);
                
                Interaction::updateSalesman($clientData['id_salesman'], $client['id_salesman'], $clientId, 1);
            }

            Client::updateClient($client, $note, $clientId);
        }

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

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

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

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

        if($text && $where) {
            $result = Client::searchBy($where, $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);
    }

    public function getFullClient() {
        $client = filter_input(INPUT_POST, 'client');

        if($client) {
            $result = Client::getClient($client);

            if($result) {
                if($result['id_salesman']) {
                    $result['salesman_name'] = Salesman::getSalesmanName($result['id_salesman']);
                }

                echo json_encode($result);
            }
        }        
    }
}