<?php

namespace Source\Models;


use CodePhix\Asaas\Asaas;
use Source\Conn\DataLayer;



class Finance extends DataLayer
{
    public function balanceKey(array $data): void
    {
        $resultBuy = $this->db()->from('buy')
            ->where('buy_id_user')->is(ID_LOG)
            ->andWhere('buy_status')->is(1)
            ->select(function($include){
                $include->sum('buy_quantify', 'total');
            })
            ->all();

        if($resultBuy){
            foreach ($resultBuy as $rBuy){
                if($rBuy->total != ''){
                    $totalKeys = $rBuy->total;
                }else{
                    $totalKeys = 0;
                }
            }
        }else{
            $totalKeys = 0;
        }

        $resultKey = $this->db()->from('xml')
            ->where('xml_id_user')->is(ID_LOG)
            ->andWhere('xml_trash')->is(0)
            ->select(function($include){
                $include->count('xml_id', 'total');
            })
            ->all();

        if($resultKey){
            foreach ($resultKey as $rKey){
                if($rKey->total != ''){
                    $totalXml = $rKey->total;
                }else{
                    $totalXml = 0;
                }
            }
        }else{
            $totalXml = 0;
        }

        $this->call(
            '200',
            'Parabéns',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "ok",
            "Operação realizada com sucesso."
        )->back(["countKey" => $totalKeys, "countXml" => $totalXml, "countAvailable" => ($totalKeys - $totalXml)]);
        return;
    }

    public function buy(array $data): void
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $buyForm['buy_id_user'] = ID_LOG;
        $buyForm['buy_date']    = date('Y-m-d');
        $buyForm['buy_status']  = '0';
        $buyForm['buy_value']   = $data['quantify'] * VALUE_KEY;
        $buyForm['buy_quantify']= $data['quantify'];

        if($this->db()->insert($buyForm)->into('buy')){

            $idBuy = $this->lastRegistro('buy', 'buy_id', 'buy_id');

            $asaas = new Asaas(TOKEN_ASAAS, ASAAS_AMB);

            $arrR = ['.', '-', '/'];
            $arrC = ['', '', ''];

            $readUser = $this->db()->from('user')
                ->where('user_id')->is($buyForm['buy_id_user'])
                ->select()
                ->all();

            if($readUser){
                foreach($readUser as $rUser){
                    if($rUser->user_id_filial != ''){

                        $dataCob = [
                            'dateCreated' => date('Y-m-d'),
                            'customer' => $rUser->user_id_filial,
                            'dueDate' => date('Y-m-d', strtotime('+1 days')),
                            'value' => $buyForm['buy_value'],
                            'billingType' => 'UNDEFINED',
                            'externalReference' => $idBuy
                        ];

                        $cob = $asaas->Cobranca()->create($dataCob);

                        $upBuy['buy_code'] = str_replace('pay_', '', $cob->id);
                        $upBuy['buy_link'] = $cob->invoiceUrl;

                        $this->db()->update('buy')->where('buy_id')->is($idBuy)->andWhere('buy_id_user')->is(ID_LOG)->set($upBuy);
                    }else{
                        $dataUser = [
                            'name' => $rUser->user_nome,
                            'cpfCnpj' => str_replace($arrR, $arrC, $rUser->user_cpf)
                        ];

                        $userCreate = $asaas->Cliente()->create($dataUser);

                        $upUser['user_id_filial'] = $userCreate->id;
                        $this->db()->update('user')->where('user_id')->is($buyForm['buy_id_user'])->set($upUser);


                        $dataCob = [
                            'dateCreated' => date('Y-m-d'),
                            'customer' => $userCreate->id,
                            'dueDate' => date('Y-m-d', strtotime('+1 days')),
                            'value' => $buyForm['buy_value'],
                            'billingType' => 'UNDEFINED',
                            'externalReference' => $idBuy
                        ];

                        $cob = $asaas->Cobranca()->create($dataCob);

                        $upBuy['buy_code'] = str_replace('pay_', '', $cob->id);
                        $upBuy['buy_link'] = $cob->invoiceUrl;

                        $this->db()->update('buy')->where('buy_id')->is($idBuy)->andWhere('buy_id_user')->is(ID_LOG)->set($upBuy);
                    }
                }
            }

            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["count" => 0]);
            return;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Houve um problema no processamento da solicitação."
        )->back(["count" => 0]);
        return;
    }

    public function buyLoad(array $data): void
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $result = $this->db()->from('buy')
            ->where('buy_id_user')->is(ID_LOG)
            ->orderBy('buy_id', 'desc')
            ->orderBy('buy_id', 'desc')
            ->select()
            ->all();

        if($result){
            $var = '<table class="table table-hover table-nomargin">';
                $var .= '<thead>
                    <tr>
                        <th>ID</th>
                        <th>Data</th>
                        <th>Status</th>
                        <th>Valor</th>
                        <th>Quantidade</th>
                        <th></th>
                    </tr>
                </thead>';
                $var .= '<tbody>';
                    foreach($result as $rBuy){
                        if($rBuy->buy_status == '0'){
                            $rBuy->buy_status = 'ABERTO';
                            $button = '<a href="'.$rBuy->buy_link.'" target="_blank" class="btn btn-blue">PAGAR</a>';
                        }elseif($rBuy->buy_status == '1'){
                            $rBuy->buy_status = 'PAGO';
                            $button = '';
                        }else{
                            $rBuy->buy_status = 'CANCELADO';
                            $button = '';
                        }
                        $var .= '<tr>
                            <td>'.$rBuy->buy_id.'</td>
                            <td>'.format_date_br($rBuy->buy_date).'</td>
                            <td>'.$rBuy->buy_status.'</td>
                            <td>'.format_money($rBuy->buy_value).'</td>
                            <td>'.$rBuy->buy_quantify.'</td>
                            <td>'.$button.'</td>
                        </tr>';
                    }
                $var .= '</tbody>';
            $var .= '</table>';

            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["count" => 0, "order" => $var]);
            return;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Existem campos em branco"
        )->back(["count" => 0]);
        return;
    }
}