<?php
namespace src\controllers;

use \core\Controller;
use \src\models\Farm;
use \src\models\City;
use \src\models\Client;
use \src\models\Provider;
use \src\models\Product;
use \src\models\Salesman;
use \src\models\Shipping_company;
use \src\models\User;

class UtilsController extends Controller {

    public function getCityList() {
        if(isset($_POST['state']) && !empty($_POST['state'])) {
            $uf = filter_input(INPUT_POST, 'state');
            $array = City::select()
                ->where('uf', $uf)
            ->get();

            echo json_encode($array);
        }
    }

    public function verifyExists() {
        if(!empty($_POST['value']) && !empty($_POST['ref'])) {
            $value = filter_input(INPUT_POST, 'value');
            $ref = filter_input(INPUT_POST, 'ref');

            $response = Client::existsClient($ref, $value);
            echo json_encode($response);
        }
    }

    // Verificações em cpf em clientes
    public static function verifyClient($ref, $value, $length) {
        $response = false;
        if(strlen($value) != $length) {
            $response = true;
        }

        if(Client::existsClient($ref, $value)) {
            $response = true;
        }

        return $response;
    }

    public function verifyExistsFarm() {
        $response = false;
        $stateReg = filter_input(INPUT_POST, 'value');

        if($stateReg) {
            $response = Farm::existsFarm($stateReg);
        }

        echo json_encode($response);
    }

    public static function convertDate($date) {
        if($date) {
            if(count(explode("/", $date)) > 1) {
                return implode("-", array_reverse(explode("/", $date)));
            } elseif(count(explode("-", $date)) > 1) {
                return implode("/", array_reverse(explode("-", $date)));
            }
        } else {
            return null;
        }
    }

    public static function uploadAttachment($file, $location) {
        $allowed_attachments = array(
            'image/jpeg',
            'image/jpg',
            'image/png',
            'application/pdf'
        );      

        $tmp_name = $file['tmp_name'];
        $type = $file['type'];
        $name = $file['name'];
        $ext = pathinfo($name, PATHINFO_EXTENSION);

        if(in_array($type, $allowed_attachments)) {
            $new_name = md5(time().rand(0,999)).'.'.$ext;
            move_uploaded_file($tmp_name, '../public/'.$location.'/'.$new_name);
            return $new_name;
        } else {
            return false;
        }
    }

    public function ClientsAndFarmsStatus() {
        $ref = filter_input(INPUT_POST, 'ref');
        $astatus = filter_input(INPUT_POST, 'status');
        $table = filter_input(INPUT_POST, 'where');

        if($ref && $table) {
            $status = ($astatus == 1)? intval(0) : intval(1) ;

            Client::update(['status' => $status])
                ->table($table)
                ->where('id', $ref)
            ->execute();

            echo json_encode(true);
        }
    }

    public function getProviderList() {
        $data['providersList'] = Provider::select()
            ->orderBy(['company_name' => 'asc'])
        ->get();

        echo json_encode($data);
    }

    public static function convertToRealBr($value) {
        $converted = '0,00';
        if(!empty($value)) {
            $converted = number_format($value, 2, ',', '.');
        }
        return $converted;
    }

    public static function convertPriceToDb($value) {
        $source = array('.', ',');
        $replace = array('', '.');
        $valueFormated = 0;

        if($value) {
            $valueFormated = str_replace($source, $replace, $value);
        }

        return $valueFormated;
    }

    public function updateStatusProduct() {
        $astatus = filter_input(INPUT_POST, 'status');
        $product = filter_input(INPUT_POST, 'product');

        if($product) {
            $status = ($astatus == 1)? intval(0) : intval(1);
            
            Product::update(['status' => $status])
                ->where('id', $product)
            ->execute();

            echo json_encode(true);
        }
    }

    public function verifySalesman() {
        if(!empty($_POST['value']) && !empty($_POST['ref'])) {
            $value = filter_input(INPUT_POST, 'value');
            $ref = filter_input(INPUT_POST, 'ref');

            $response = Salesman::existsSalesman($ref, $value);
            echo json_encode($response);
        }
    }

    // Verificações em clientes
    public static function verifySalesmanIdentify($ref, $value, $length) {
        $response = false;
        if(strlen($value) != $length) {
            $response = true;
        }

        if(Salesman::existsSalesman($ref, $value)) {
            $response = true;
        }

        return $response;
    }

    // Verificações em Fornecedores
    public static function verifyProviderIdentify($ref, $value, $length, $table) {
        $response = false;
        if(strlen($value) != $length) {
            $response = true;
        }

        if(Provider::existsProvider($ref, $value, $table)) {
            $response = true;
        }

        return $response;
    }

    // Verificações em Transportadoras
    public static function verifyShippingCompIdentify($ref, $value, $length) {
        $response = false;
        if(strlen($value) != $length) {
            $response = true;
        }

        if(Shipping_company::existsShipping($ref, $value)) {
            $response = true;
        }

        return $response;
    }

    // Verificações em Usuários
    public static function verifyUser($ref, $value, $length) {
        $response = false;
        if(strlen($value) != $length) {
            $response = true;
        }

        if(User::existsUser($ref, $value)) {
            $response = true;
        }

        return $response;
    }

    // Verificações em E-mail Usuários
    public static function verifyUserEmail($ref, $value) {
        $response = false;

        if(User::existsUser($ref, $value)) {
            $response = true;
        }

        return $response;
    }    

    // Verificar data padrão
    public static function verifyDefaltDate($date = null, $typeRequest = null, $delimiter = '') {
        
        if(isset($_POST['date'])) {
            $date = filter_input(INPUT_POST, 'date');
            $typeRequest = filter_input(INPUT_POST, 't_request');
            $delimiter = filter_input(INPUT_POST, 'delimiter');
        }

        if(empty($delimiter)) {
            $delimiter = '<=';
        }

        if($date) {
            $response = false;
            $date = explode('/', $date);
            if(count($date) != 3) {
                $response = false;
            }

            if(strlen($date[2]) == 4) {
                if($date[2] .$delimiter. date("Y")) {
                    if(checkdate($date[1], $date[0], $date[2])) {
                        $response = true;
                    }
                }
            }

            if($typeRequest == 'ajax') {
                echo json_encode($response);
            } else {
                return $response;
            }
        }
    }

    public static function verifyFutureDate($date) {
        $response = false;
        $now = date('d/m/Y');
        $dateArray = explode('/', $date);

        if(count($dateArray) != 3) {
            $response = false;
        }

        if(strlen($dateArray[2]) == 4) {
            $datesend = self::convertDate($date);
            $now = self::convertDate($now);
            if(strtotime($datesend) >= strtotime($now)) {
                if($dateArray[2] >= date("Y")) {
                    if(checkdate($dateArray[1], $dateArray[0], $dateArray[2])) {
                        $response = true;
                    }
                }
            }
        }
        return $response;
    }

    public static function verifyNoteDate($date, $delimiter) {
        $response = false;
        $now = date('d/m/Y');
        $dateArray = explode('/', $date);

        if(count($dateArray) != 3) {
            $response = false;
        }

        if(strlen($dateArray[2]) == 4) {
            $datesend = self::convertDate($date);
            $now = self::convertDate($now);
            if(strtotime($datesend) <= strtotime($now)) {
                if($dateArray[2] .$delimiter. date("Y")) {
                    if(checkdate($dateArray[1], $dateArray[0], $dateArray[2])) {
                        $response = true;
                    }
                }
            }
        }
        return $response;
    }

    // Função para verificar se data é maior que outra e válida
    public static function compareDate() {
        $dateverify = filter_input(INPUT_POST, 'date1');
        $dateBase = filter_input(INPUT_POST, 'date2');

        $response = false;
        $dateArray = explode('/', $dateverify);

        if(count($dateArray) != 3) {
            $response = false;
        }

        if(strlen($dateArray[2]) == 4) {
            $datesend = self::convertDate($dateverify);
            $baseDt = self::convertDate($dateBase);
            if(strtotime($datesend) >= strtotime($baseDt)) {
                if(checkdate($dateArray[1], $dateArray[0], $dateArray[2])) {
                    $response = true;
                }
            }
        }
        echo json_encode($response);
    }

    // Verificar se valor é uma data válida
    public static function isDate($date) {
        $response = false;
        $dateArray = explode('/', $date);

        if(count($dateArray) != 3) {
            $response = false;
        }

        if(strlen($dateArray[2]) == 4) {
            if(checkdate($dateArray[1], $dateArray[0], $dateArray[2])) {
                $response = true;
            }
        }
        return $response;
    }

    public function getValueTotal() {
        $qt = filter_input(INPUT_POST, 'qt');
        $value = filter_input(INPUT_POST, 'value');

        if($qt && $value) {
            $qt = self::convertPriceToDb($qt);
            $value = self::convertPriceToDb($value);

            $total = ($qt * $value);
            $response = self::convertToRealBr($total);
            echo json_encode($response);
        }
    }

    public static function getConfigReports() {
        $data = User::select()
            ->table('reports_config')
        ->one();

        return $data;
    }

    public static function updateReportSetings($report, $ref) {
        User::update($report)
            ->table('reports_config')
        ->execute();
    }
}