<?php
namespace src\controllers;

use \core\Controller;
use \src\handlers\CityHandler;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\models\Farm;
use \src\models\City;
use \src\models\Client;

class FarmsController 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() {
        $client = filter_input(INPUT_GET, 'c');

        if(isset($_SESSION['saved'])) {
            $client = $_SESSION['saved'];
            unset($_SESSION['saved']);
        }

        if($client) {
            $dataClient = Client::getClient($client);
            $clientFarms = Farm::getFarms($client);

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

            $this->render('farms', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'client' => $dataClient,
                'farmsList' => $clientFarms,
                'titlePage' => 'Fazendas - Supporte Agronegócios'
            ]);

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

    public function add() {
        $post = array();
        $error = array();
        $client = filter_input(INPUT_GET, 'c');

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

        if($client) {
            $dataClient = Client::getClient($client);
            $states = CityHandler::getStates();

            $this->render('farms_add', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'client' => $dataClient,
                'states' => $states,
                'form' => $post,
                'error' => $error,
                'titlePage' => 'Adicionar Fazenda - Supporte Agronegócios'
            ]);

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

    public function addAction() {
        if(!empty($_POST['name']) && !empty($_POST['state_registration']) && !empty($_POST['city']) ) {
            $farm = array();

            $file = $_FILES['attachment'];            
            $farm['id_client'] = filter_input(INPUT_POST, 'id_client');
            $farm['name'] = filter_input(INPUT_POST, 'name');
            $farm['state_registration'] = filter_input(INPUT_POST, 'state_registration');
            $farm['responsible'] = filter_input(INPUT_POST, 'responsible');
            $farm['phone'] = filter_input(INPUT_POST, 'phone');
            $farm['state'] = filter_input(INPUT_POST, 'state');
            $farm['city'] = filter_input(INPUT_POST, 'city');
            $farm['location'] = filter_input(INPUT_POST, 'location');
            $farm['script'] = filter_input(INPUT_POST, 'script');
            $farm['note'] = filter_input(INPUT_POST, 'note');

            if(Farm::existsFarm($farm['state_registration'])) {
                $_SESSION['alertType'] = 'alert-warning';
                $_SESSION['msg'] = "Insc. Estadual já cadastrada!";
                $_SESSION['post'] = $farm;
                $this->redirect('/addfarms');
            }

            if($file['size'] > 0) {
                $farm['attachment'] = UtilsController::uploadAttachment($file, 'media/files');    

                if($farm['attachment'] == false) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "Arquivo não aceito e/ou muito grande!";
                    $_SESSION['post'] = $farm;
                    $this->redirect('/addfarms');
                }
            }
            
            Farm::saveFarm($farm);
            $_SESSION['saved'] = $farm['id_client'];
        }

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

    public function edit() {
        $error = array();
        $farm = filter_input(INPUT_GET, 'f');

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

        if($farm) {
            $dataFarm = Farm::getFarm($farm);
            $dataClient = Client::getClient($dataFarm['id_client']);
            $states = CityHandler::getStates();
            $dataFarm['city_name'] = City::getName($dataFarm['city']);            

            $this->render('farms_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'states' => $states,
                'form' => $dataFarm,
                'client' => $dataClient,
                'error' => $error,
                'titlePage' => 'Editar Fazenda - Supporte Agronegócios'
            ]);

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

    public function editAction() {
        if(!empty($_POST['name']) && !empty($_POST['state_registration']) && !empty($_POST['city']) ) {
            $farm = array();

            $file = $_FILES['attachment'];            
            $idFarm = filter_input(INPUT_POST, 'id_farm');
            $farm['id_client'] = filter_input(INPUT_POST, 'id_client');
            $farm['name'] = filter_input(INPUT_POST, 'name');
            $farm['state_registration'] = filter_input(INPUT_POST, 'state_registration');
            $farm['responsible'] = filter_input(INPUT_POST, 'responsible');
            $farm['phone'] = filter_input(INPUT_POST, 'phone');
            $farm['state'] = filter_input(INPUT_POST, 'state');
            $farm['city'] = filter_input(INPUT_POST, 'city');
            $farm['location'] = filter_input(INPUT_POST, 'location');
            $farm['script'] = filter_input(INPUT_POST, 'script');
            $farm['note'] = filter_input(INPUT_POST, 'note');            

            if($file['size'] > 0) {
                $farm['attachment'] = UtilsController::uploadAttachment($file, 'media/files');    

                if($farm['attachment'] == false) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "Arquivo não aceito e/ou muito grande!";
                    $_SESSION['post'] = $farm;
                    $this->redirect('/addfarms');
                }
            }
            
            Farm::updateFarm($farm, $idFarm);
            $_SESSION['saved'] = $farm['id_client'];
        }

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

    public function deleteAtt() {
        $status = false;
        $ref = filter_input(INPUT_POST, 'value');
        $farm = filter_input(INPUT_POST, 'farm');

        if($ref && $farm) {
            if(unlink('../public/media/files/'.$ref)) {
                Farm::deleteAttachment($farm);
                $status = true;
            }
        }

        echo json_encode($status);
    }

    public function getFarmsClient() {
        $client = filter_input(INPUT_POST, 'client');
        
        if($client) {
            $clientFarms = Farm::getFarms($client);

            echo json_encode($clientFarms);
        }
    }

    public function getFarmInfo() {
        $farm = filter_input(INPUT_POST, 'farm');
        
        if($farm) {
            $farmInfo = Farm::getFarm($farm);
            $farmInfo['city_name'] = City::getName($farmInfo['city']);
            echo json_encode($farmInfo);
        }
    }

}