<?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\Provider;

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

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

    public function index() {
        $emptyFilter = [
            'dateInit' => '',
            'dateEnd' => '',
            'status' => '',
            'option_filter' => '',
            'type_b' => '',
            'b_type' => array(),
            'form_p' => '',
            'p_form' => array(),
            'situation_b' => '',
            'b_situation' => array(),
            'searchBy' => 'provider_description',
            'searchText' => '',
            'limit' => 20
        ];

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

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


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

        $offset = 0;
        $limit = $_SESSION['filter_billstopay']['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::filterBillsToPay($_SESSION['filter_billstopay']);

        $this->arrayInfo['billsToPayList'] = Bills_to_pay::getAll($offset, $limit, $filter);
        $this->arrayInfo['billstopay_type'] = Bills_to_pay::getAllBillsToPaytype();
        $this->arrayInfo['payment_form'] = Bills_to_pay::getAllPaymentForm();
        $this->arrayInfo['billstopay_situation'] = Bills_to_pay::getAllBillsToPaySituation();

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

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

        foreach ($this->arrayInfo['billsToPayList'] as $key => $bills) {
            $this->arrayInfo['billsToPayList'][$key]['situation'] = Bills_to_pay::getBillsToPaySituation($bills['id_situation']);
            $this->arrayInfo['billsToPayList'][$key]['expirate_date'] = UtilsController::convertDate($bills['expirate_date']);
            $this->arrayInfo['billsToPayList'][$key]['payment_date'] = UtilsController::convertDate($bills['payment_date']);
            $this->arrayInfo['billsToPayList'][$key]['main_value'] = UtilsController::convertToRealBr($bills['main_value']);
            $this->arrayInfo['billsToPayList'][$key]['value_to_pay'] = UtilsController::convertToRealBr($bills['value_to_pay']);
            $this->arrayInfo['billsToPayList'][$key]['residual_value'] = UtilsController::convertToRealBr($bills['residual_value']);
            $this->arrayInfo['billsToPayList'][$key]['billstopay_description'] = Bills_to_pay::getBillsToPayType($bills['billstopay_type']);
        }

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

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

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

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

        $filterPage = $_SESSION['filter_billstopay'];

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

    public function add() {
        $error = array();   
        $this->arrayInfo['providers_list'] = Provider::getProvidersServices();
        $this->arrayInfo['billstopay_type'] = Bills_to_pay::getAllBillsToPaytype();
        $this->arrayInfo['payment_form'] = Bills_to_pay::getAllPaymentForm();
        $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('billstopay_add', [
            'loggedUser' => $this->loggedUser,
            'pageActive' => $this->pageActive,
            'permissions' => $this->paramsName,
            'array' => $this->arrayInfo,
            'error' => $error,
            'titlePage' => 'Adicionar Contas a Pagar - 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'):'';

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

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


        if(isset($_POST['billstopay_new'])) {
            $billstopay['billstopay_type'] = self::addNewBillstopayType($billstopay['billstopay_description']);
        }

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

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

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

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

        $idBillsToPay = Bills_to_pay::saveAcount($billstopay, $billstopay_repeat, $qtd_repeat);

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

            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_pay::saveAcount($accountInfo);
        }

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


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

        if($id) {
            $error = array();   
            $this->arrayInfo['providers_list'] = Provider::getProvidersServices();
            $this->arrayInfo['billstopay_type'] = Bills_to_pay::getAllBillsToPaytype();
            $this->arrayInfo['payment_form'] = Bills_to_pay::getAllPaymentForm();
            $this->arrayInfo['billstopay_situation'] = Bills_to_pay::getAllBillsToPaySituation();
            $billsItem = Bills_to_pay::getBillsToPay($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('billstopay_edit', [
                'loggedUser' => $this->loggedUser,
                'pageActive' => $this->pageActive,
                'permissions' => $this->paramsName,
                'array' => $this->arrayInfo,
                'error' => $error,
                'bills_item' => $billsItem,
                'titlePage' => 'Editar Contas a Pagar - Supporte Agronegócios'
            ]);
        }
    }

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

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

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

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


            if(isset($_POST['billstopay_new'])) {
                $billstopay['billstopay_type'] = self::addNewBillstopayType($billstopay['billstopay_description']);
            }

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

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

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

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

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

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

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

            Bills_to_pay::updateAccount('id', $idBtp, $billstopay);

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

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

                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_pay::saveAcount($accountInfo);
            }
        }

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

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

        $id = Bills_to_pay::saveBillsToPayType($data);

        return $id;
    }

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

        $id = Bills_to_pay::saveFormToPay($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() {
        $idBtp = filter_input(INPUT_POST, 'ref');

        if($idBtp) {
            $accountInfo = Bills_to_pay::getBillsToPay($idBtp);

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

                $data['receipt_file'] = null;
                Bills_to_pay::updateAccount('id', $idBtp, $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_pay::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');

        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_pay::getBillsToPay($account);
                $accountData['paid_out_value'] = $accountInfo['main_value'];

                Bills_to_pay::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_pay::getBillsToPay($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 Pagar 05/03/2024
    public function updateBtpType() {
        $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_pay::updateBtpType($ref, $data);

            $response['status'] = true;
        }

        echo json_encode($response);
    }

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

        if($name) {
            $ref = self::addNewBillstopayType($name);

            $response['status'] = true;
        }

        echo json_encode($response);
    }
}