<?php
namespace src\controllers;

use \core\Controller;
use \src\controllers\UtilsController;
use \src\handlers\LoginHandler;
use \src\handlers\PermissionHandler;
use \src\handlers\FiltersHandler;
use \src\models\Bills_to_pay;
use \src\models\Bills_to_receive;
use \src\models\Provider;

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

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

    public function index() {
        $emptyFilter = [
            'dateInit' => '',
            'dateEnd' => '',
            'clear' => '',
            'situation_b' => '',
            'b_situation' => array(),
            'receiver_origin' => '',
            'status' => '',
            'searchBy' => 'provider_description',
            'searchText' => '',
            'limit' => 20
        ];

        if(isset($_POST['filter']) && !empty($_POST['filter'])) {
            $_SESSION['filter_billstoreceiver'] = filter_input(INPUT_POST, 'filter', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
            if($_SESSION['filter_billstoreceiver']['clear'] == 'clear') {
                $_SESSION['filter_billstoreceiver'] = $emptyFilter;
                $this->redirect('/billstoreceiver');
            }
        }

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


        if(!isset($_SESSION['filter_billstoreceiver'])) {
            $this->arrayInfo['op'] = '';
            $_SESSION['filter_billstoreceiver'] = $emptyFilter;
        } elseif(!empty($_SESSION['filter_billstoreceiver']['option_filter'])) {
            $this->arrayInfo['op'] = "&op=".$_SESSION['filter_billstoreceiver']['option_filter'];
        }

        if(empty($_SESSION['filter_billstoreceiver']['limit'])) {
            $_SESSION['filter_billstoreceiver']['limit'] = $emptyFilter['limit'];
        }

        $offset = 0;
        $limit = intval($_SESSION['filter_billstoreceiver']['limit']);

        $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::filterBillsToReceiver($_SESSION['filter_billstoreceiver']);

        $this->arrayInfo['billstoreceiverList'] = Bills_to_receive::getAll($offset, $limit, $filter);        
        $this->arrayInfo['billstopay_situation'] = Bills_to_pay::getAllBillsToPaySituation();
        $this->arrayInfo['receiver_origin'] = Bills_to_receive::getAllReceiverOrigin();
        $this->arrayInfo['receiver_form'] = Bills_to_receive::getAllReceiverForm();

        // Valor a pagar
        $valueTotalThisPage = array_sum(array_column($this->arrayInfo['billstoreceiverList'], 'main_value'));
        $this->arrayInfo['valueTotalThisPage'] = UtilsController::convertToRealBr($valueTotalThisPage);

        // Valor pago
        $paiOutTotalThisPage = array_sum(array_column($this->arrayInfo['billstoreceiverList'], 'paid_out_value'));
        $this->arrayInfo['paiOutTotalThisPage'] = UtilsController::convertToRealBr($paiOutTotalThisPage);

        foreach ($this->arrayInfo['billstoreceiverList'] as $key => $bills) {
            $this->arrayInfo['billstoreceiverList'][$key]['situation'] = Bills_to_pay::getBillsToPaySituation($bills['id_situation']);
            $this->arrayInfo['billstoreceiverList'][$key]['expirate_date'] = UtilsController::convertDate($bills['expirate_date']);
            $this->arrayInfo['billstoreceiverList'][$key]['origin'] = Bills_to_receive::getReceiverOrigin($bills['receiver_origin']);
            $this->arrayInfo['billstoreceiverList'][$key]['payment_date'] = UtilsController::convertDate($bills['payment_date']);
            $this->arrayInfo['billstoreceiverList'][$key]['main_value'] = UtilsController::convertToRealBr($bills['main_value']);
            $this->arrayInfo['billstoreceiverList'][$key]['advance_value'] = UtilsController::convertToRealBr($bills['advance_value']);
            $this->arrayInfo['billstoreceiverList'][$key]['residual_value'] = UtilsController::convertToRealBr($bills['residual_value']);
        }

        $btr_count = Bills_to_receive::getCount($filter);
        $this->arrayInfo['p_count'] = ceil( $btr_count / $limit );

        if(!isset($_SESSION['filter_billstoreceiver']['b_situation']) || empty($_SESSION['filter_billstoreceiver']['b_situation'])) {
            $_SESSION['filter_billstoreceiver']['b_situation'] = array();
        }

        $filterPage = $_SESSION['filter_billstoreceiver'];

        $this->render('billstoreceiver', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'array' => $this->arrayInfo,
            'filter' => $filterPage,
            'titlePage' => 'Contas a Receber - Supporte Agronegócios'
        ]);
    }

    public function add() {
        $error = array();

        $this->arrayInfo['receiver_origin'] = Bills_to_receive::getAllReceiverOrigin();
        $this->arrayInfo['payment_form'] = Bills_to_receive::getAllReceiverForm();        
        $this->arrayInfo['billstopay_situation'] = Bills_to_pay::getAllBillsToPaySituation();

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

        $this->render('billstoreceiver_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'array' => $this->arrayInfo,
            'error' => $error,
            'titlePage' => 'Adicionar Contas a Receceber - Supporte Agronegócios'
        ]);
    }    

    public function addAction() {
        $dateNewAccount = filter_input(INPUT_POST, 'date_new_acount');
        $billstopay_repeat = (isset($_POST['billstopay_repeat']))?filter_input(INPUT_POST, 'billstopay_repeat'):'';
        $qtd_repeat = (isset($_POST['qtd_repeat']))?filter_input(INPUT_POST, 'qtd_repeat'):'';

        $billstoreceiver['copied'] = intval(filter_input(INPUT_POST, 'copied'));
        $billstoreceiver['id_user'] = $this->loggedUser->id;
        $billstoreceiver['id_provider'] = filter_input(INPUT_POST, 'providers_list');        
        $billstoreceiver['provider_description'] = filter_input(INPUT_POST, 'provider_description');
        $billstoreceiver['receiver_origin'] = filter_input(INPUT_POST, 'billstopay_list');
        $billstoreceiver['origin_description'] = filter_input(INPUT_POST, 'billstopay_description');
        $billstoreceiver['form_to_pay'] = filter_input(INPUT_POST, 'form_to_pay');
        $billstoreceiver['form_to_pay_description'] = filter_input(INPUT_POST, 'form_to_pay_description');
        $billstoreceiver['payment_data'] = filter_input(INPUT_POST, 'payment_data');         
        $billstoreceiver['document_date'] = filter_input(INPUT_POST, 'document_date');
        $billstoreceiver['id_request'] = filter_input(INPUT_POST, 'id_request');
        $billstoreceiver['document_number'] = filter_input(INPUT_POST, 'document_number');
        $billstoreceiver['expirate_date'] = filter_input(INPUT_POST, 'expirate_date');
        $billstoreceiver['payment_date'] = filter_input(INPUT_POST, 'payment_date');
        $billstoreceiver['main_value'] = filter_input(INPUT_POST, 'main_value');
        $billstoreceiver['advance_value'] = filter_input(INPUT_POST, 'advance_value');
        $billstoreceiver['value_to_pay'] = filter_input(INPUT_POST, 'value_to_pay');
        $billstoreceiver['paid_out_value'] = filter_input(INPUT_POST, 'paid_out_value');
        $billstoreceiver['residual_value'] = filter_input(INPUT_POST, 'residual_value');
        $billstoreceiver['note'] = filter_input(INPUT_POST, 'note');
        $billstoreceiver['id_situation'] = filter_input(INPUT_POST, 'situation');

        $billstoreceiver['id_provider'] = ($billstoreceiver['id_provider'] != 0)?$billstoreceiver['id_provider']:null;
        $billstoreceiver['document_date'] = UtilsController::convertDate($billstoreceiver['document_date']);
        $billstoreceiver['expirate_date'] = UtilsController::convertDate($billstoreceiver['expirate_date']);
        $billstoreceiver['payment_date'] = UtilsController::convertDate($billstoreceiver['payment_date']);
        $billstoreceiver['main_value'] = UtilsController::convertPriceToDb($billstoreceiver['main_value']);
        $billstoreceiver['advance_value'] = UtilsController::convertPriceToDb($billstoreceiver['advance_value']);
        $billstoreceiver['value_to_pay'] = UtilsController::convertPriceToDb($billstoreceiver['value_to_pay']);
        $billstoreceiver['paid_out_value'] = UtilsController::convertPriceToDb($billstoreceiver['paid_out_value']);
        $billstoreceiver['residual_value'] = UtilsController::convertPriceToDb($billstoreceiver['residual_value']);


        if(isset($_POST['billstopay_new'])) {
            $billstoreceiver['receiver_origin'] = self::addNewReceiverOrigin($billstoreceiver['origin_description']);
        }

        if(isset($_POST['billstopay_new_type'])) {
            $billstoreceiver['form_to_pay'] = self::addNewFormToReceiver($billstoreceiver['form_to_pay_description']);
        }


        $file = (!empty($_FILES['receipt_file']))?$_FILES['receipt_file']:array();

        if($file['size'] > 0) {
            $billstoreceiver['receipt_file'] = UtilsController::uploadAttachment($file, 'media/vouchers_receiver');    

            if($billstoreceiver['receipt_file'] == false) {
                $_SESSION['alertType'] = 'alert-warning';
                $_SESSION['msg'] = "Arquivo não aceito e/ou muito grande!";
                $this->redirect('/billstoreceiveradd');
                exit;
            }
        }        

        $idBillsToReceiver = Bills_to_receive::saveAcount($billstoreceiver, $billstopay_repeat, $qtd_repeat);


        if($billstoreceiver['copied'] == 1) {
            $accountInfo = Bills_to_receive::getBillsToReceiver($idBillsToReceiver);

            unset($accountInfo['id']);
            $accountInfo['expirate_date'] = UtilsController::convertDate($dateNewAccount);
            $accountInfo['payment_date'] = null;
            $accountInfo['copied'] = 0;
            $accountInfo['advance_value'] = 0;
            $accountInfo['paid_out_value'] = 0;
            $accountInfo['main_value'] = $accountInfo['residual_value'];
            $accountInfo['value_to_pay'] = $accountInfo['residual_value'];
            $accountInfo['residual_value'] = $accountInfo['residual_value'];
            $accountInfo['id_situation'] = 2;
            $accountInfo['note'] = 'Conta residual solicitado pelo usuário';

            Bills_to_receive::saveAcount($accountInfo);
        }

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

    public function edit() {
        $id = filter_input(INPUT_GET, 'btr');

        if($id) {
            $error = array();   
            
            $this->arrayInfo['receiver_origin'] = Bills_to_receive::getAllReceiverOrigin();
            $this->arrayInfo['payment_form'] = Bills_to_receive::getAllReceiverForm();        
            $this->arrayInfo['billstopay_situation'] = Bills_to_pay::getAllBillsToPaySituation();
            $billsItem = Bills_to_receive::getBillsToReceiver($id);

            $billsItem['document_date'] = UtilsController::convertDate($billsItem['document_date']);
            $billsItem['expirate_date'] = UtilsController::convertDate($billsItem['expirate_date']);
            $billsItem['payment_date'] = UtilsController::convertDate($billsItem['payment_date']);

            $billsItem['main_value'] = UtilsController::convertToRealBr($billsItem['main_value']);
            $billsItem['advance_value'] = UtilsController::convertToRealBr($billsItem['advance_value']);
            $billsItem['value_to_pay'] = UtilsController::convertToRealBr($billsItem['value_to_pay']);
            $billsItem['paid_out_value'] = UtilsController::convertToRealBr($billsItem['paid_out_value']);
            $billsItem['residual_value'] = UtilsController::convertToRealBr($billsItem['residual_value']);

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

            $this->render('billstoreceiver_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'array' => $this->arrayInfo,
                'error' => $error,
                'bills_item' => $billsItem,
                'titlePage' => 'Editar Contas a Receceber - Supporte Agronegócios'
            ]);
        }
    }

    public function editAction() {
        $idBtr = filter_input(INPUT_POST, 'id_bills_item');

        if($idBtr) {
            $dateNewAccount = filter_input(INPUT_POST, 'date_new_acount');
            $cloned = intval(filter_input(INPUT_POST, 'cloned'));

            $billstoreceiver['copied'] = intval(filter_input(INPUT_POST, 'copied'));
            $billstoreceiver['id_user'] = $this->loggedUser->id;
            $billstoreceiver['id_provider'] = filter_input(INPUT_POST, 'providers_list');        
            $billstoreceiver['provider_description'] = filter_input(INPUT_POST, 'provider_description');
            $billstoreceiver['receiver_origin'] = filter_input(INPUT_POST, 'billstopay_list');
            $billstoreceiver['origin_description'] = filter_input(INPUT_POST, 'billstopay_description');
            $billstoreceiver['form_to_pay'] = filter_input(INPUT_POST, 'form_to_pay');
            $billstoreceiver['form_to_pay_description'] = filter_input(INPUT_POST, 'form_to_pay_description');
            $billstoreceiver['payment_data'] = filter_input(INPUT_POST, 'payment_data');         
            $billstoreceiver['document_date'] = filter_input(INPUT_POST, 'document_date');
            $billstoreceiver['id_request'] = filter_input(INPUT_POST, 'id_request');
            $billstoreceiver['document_number'] = filter_input(INPUT_POST, 'document_number');
            $billstoreceiver['expirate_date'] = filter_input(INPUT_POST, 'expirate_date');
            $billstoreceiver['payment_date'] = filter_input(INPUT_POST, 'payment_date');
            $billstoreceiver['main_value'] = filter_input(INPUT_POST, 'main_value');
            $billstoreceiver['advance_value'] = filter_input(INPUT_POST, 'advance_value');
            $billstoreceiver['value_to_pay'] = filter_input(INPUT_POST, 'value_to_pay');
            $billstoreceiver['paid_out_value'] = filter_input(INPUT_POST, 'paid_out_value');
            $billstoreceiver['residual_value'] = filter_input(INPUT_POST, 'residual_value');
            $billstoreceiver['note'] = filter_input(INPUT_POST, 'note');
            $billstoreceiver['id_situation'] = filter_input(INPUT_POST, 'situation');

            $billstoreceiver['id_provider'] = ($billstoreceiver['id_provider'] != 0)?$billstoreceiver['id_provider']:null;
            $billstoreceiver['document_date'] = UtilsController::convertDate($billstoreceiver['document_date']);
            $billstoreceiver['expirate_date'] = UtilsController::convertDate($billstoreceiver['expirate_date']);
            $billstoreceiver['payment_date'] = UtilsController::convertDate($billstoreceiver['payment_date']);
            $billstoreceiver['main_value'] = UtilsController::convertPriceToDb($billstoreceiver['main_value']);
            $billstoreceiver['advance_value'] = UtilsController::convertPriceToDb($billstoreceiver['advance_value']);
            $billstoreceiver['value_to_pay'] = UtilsController::convertPriceToDb($billstoreceiver['value_to_pay']);
            $billstoreceiver['paid_out_value'] = UtilsController::convertPriceToDb($billstoreceiver['paid_out_value']);
            $billstoreceiver['residual_value'] = UtilsController::convertPriceToDb($billstoreceiver['residual_value']);


            if(isset($_POST['billstopay_new'])) {
                $billstoreceiver['receiver_origin'] = self::addNewReceiverOrigin($billstoreceiver['origin_description']);
            }

            if(isset($_POST['billstopay_new_type'])) {
                $billstoreceiver['form_to_pay'] = self::addNewFormToReceiver($billstoreceiver['form_to_pay_description']);
            }

            $file = (!empty($_FILES['receipt_file']))?$_FILES['receipt_file']:array();

            if($file['size'] > 0) {
                $accountInfo = Bills_to_pay::getBillsToPay($idBtr);

                if($accountInfo['receipt_file']) {
                    unlink('../public/media/vouchers_receiver/'.$accountInfo['receipt_file']);
                }

                $billstoreceiver['receipt_file'] = UtilsController::uploadAttachment($file, 'media/vouchers_receiver');    

                if($billstoreceiver['receipt_file'] == false) {
                    $_SESSION['alertType'] = 'alert-warning';
                    $_SESSION['msg'] = "Arquivo não aceito e/ou muito grande!";
                    $this->redirect('/billstoreceiver');
                    exit;
                }
            }

            if($cloned == 1) { $billstoreceiver['copied'] = $cloned; } // Mudando valor de copied caso a conta já tenha sido copiada.

            Bills_to_receive::updateAccount('id', $idBtr, $billstoreceiver);

            if($cloned == 1) { $billstoreceiver['copied'] = 0; } // Mudando valor de copied para não copiar a conta novamente.

            if($billstoreceiver['copied'] == 1) {
                $accountInfo = Bills_to_pay::getBillsToPay($idBtr);

                unset($accountInfo['id']);
                $accountInfo['expirate_date'] = UtilsController::convertDate($dateNewAccount);
                $accountInfo['payment_date'] = null;
                $accountInfo['copied'] = 0;
                $accountInfo['advance_value'] = 0;
                $accountInfo['paid_out_value'] = 0;
                $accountInfo['main_value'] = $accountInfo['residual_value'];
                $accountInfo['value_to_pay'] = $accountInfo['residual_value'];
                $accountInfo['residual_value'] = $accountInfo['residual_value'];
                $accountInfo['id_situation'] = 2;
                $accountInfo['note'] = 'Conta residual solicitado pelo usuário';

                Bills_to_receive::saveAcount($accountInfo);
            }
        }

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

    private function addNewReceiverOrigin($billstopay_description) {
        $data['name'] = $billstopay_description;

        $id = Bills_to_receive::saveReceiverOrigin($data);
        return $id;
    }

    private function addNewFormToReceiver($form_to_pay_description) {
        $data['name'] = $form_to_pay_description;

        $id = Bills_to_receive::saveFormToReceiver($data);        
        return $id;
    }

    public function verifyDate() {
        $date = filter_input(INPUT_POST, 'date');

        if($date) {
            $response = false;

            if(UtilsController::isDate($date)) {
                $response = true;
            }

            echo json_encode($response);
        }
    }

    public function getValueToPay() {
        $response = 0;
        $main = filter_input(INPUT_POST, 'value');
        $advance = filter_input(INPUT_POST, 'advance');

        if($main) {
            $main = UtilsController::convertPriceToDb($main);
            $advance = UtilsController::convertPriceToDb($advance);

            $response = ($main - $advance);
        }

        $response = UtilsController::convertToRealBr($response);
        echo json_encode($response);
    }

    public function deleteAtt() {
        $idBtr = filter_input(INPUT_POST, 'ref');

        if($idBtr) {
            $accountInfo = Bills_to_receive::getBillsToReceiver($idBtr);

            if($accountInfo['receipt_file']) {
                unlink('../public/media/vouchers_receiver/'.$accountInfo['receipt_file']);

                $data['receipt_file'] = null;
                Bills_to_receive::updateAccount('id', $idBtr, $data);

                echo json_encode(true);
            }            
        }
    }

    public function updateStatus() {
        $ref = intval(filter_input(INPUT_POST, 'ref'));
        $status = intval(filter_input(INPUT_POST, 'value'));

        if($ref) {
            $data['status'] = $status;
            Bills_to_receive::updateAccount('id', $ref, $data);

            echo json_encode(true);
        }
    }

    // Setar contas selecionadas como pagas
    public function setAccountsPaidOut() {
        $btpList = filter_input(INPUT_POST, 'refs');
        $payment_form = intval(filter_input(INPUT_POST, 'payform'));
        $payment_date = filter_input(INPUT_POST, 'paydate');
        $note_number = filter_input(INPUT_POST, 'notenumber');
        $deduceir = filter_input(INPUT_POST, 'ir');


        if($btpList && $payment_form && $payment_date) {
            $listAccounts = explode(',', $btpList);
            $payment_date = UtilsController::convertDate($payment_date);

            $accountData['id_situation'] = 4;
            $accountData['residual_value'] = 0;
            $accountData['payment_date'] = $payment_date;

            if($note_number) {
                $accountData['document_number'] = $note_number;
            }            

            foreach ($listAccounts as $key => $account) {
                $accountInfo = Bills_to_receive::getBillsToReceiver($account);

                if(!empty($deduceir) && $deduceir != ',') {
                    $deduceir = UtilsController::convertPriceToDb($deduceir);
                    $valueReduce = ($accountInfo['main_value'] * $deduceir) / 100;

                    $accountData['main_value'] = ($accountInfo['main_value'] - $valueReduce);
                    $accountData['paid_out_value'] = $accountData['main_value'];
                } else {
                    $accountData['paid_out_value'] = $accountInfo['main_value'];
                }                

                Bills_to_receive::updateAccount('id', $account, $accountData);
            }

            echo json_encode(true);
        }
    }


    // Somatório das contas selecionadas
    public function totalAccountsSelected() {
        $ref = filter_input(INPUT_POST, 'refs');

        if($ref) {
            $data = [];
            $listAccounts = explode(',', $ref);

            foreach ($listAccounts as $key => $account) {
                $data[] = Bills_to_receive::getBillsToReceiver($account);   
            }

            $response['value'] = array_sum(array_column($data, 'main_value'));
            $response['value'] = UtilsController::convertToRealBr($response['value']);
            $response['status'] = true;

            echo json_encode($response);
        }
    }

    // Edição de Tipo de Contas a Receber 06/03/2024
    public function updateBtrType() {
        $data = array();
        $response = array();

        $ref = filter_input(INPUT_POST, 'item', FILTER_DEFAULT);
        $data['name'] = filter_input(INPUT_POST, 'value', FILTER_DEFAULT);

        $ref = explode('_', $ref);
        $ref = intval(end($ref));
        
        $response['status'] = false;

        if($ref && $data['name']) {            
            Bills_to_receive::updateReceiverOrigin($data, $ref);

            $response['status'] = true;
        }

        echo json_encode($response);
    }

    public function saveBtrType() {
        $response = array();
        $response['status'] = false;
        $data['name'] = filter_input(INPUT_POST, 'value', FILTER_DEFAULT);        

        if($data['name']) {
            $ref = Bills_to_receive::saveReceiverOrigin($data);

            $response['status'] = true;
        }

        echo json_encode($response);
    }
}