<?php

class Parcial extends Utilidades
{
    protected $pago;
    protected $retiro;
    private $data = null;
    public $escenario = 1;
    public $tipo_parametro = 1;
    public $tipo_parametro_rebaja_prestamos = 3;

    public function __construct($retiro, $pago)
    {
        $this->retiro = $retiro;
        $this->pago = $pago;
        Yii::import('application.modules.contable.models.*', true);
        Yii::import('application.modules.contable.models.comprobantes.*', true);
    }

    public function contabilizar()
    {
        if (! ParamEscenarios::conectado($this->escenario)) {
            return;
        }

        ////////////////////////////////// COMPROBANTE /////////////////////////////////
        $comprobante = $this->comprobante();

        $this->seguimientoComprobante(
            $comprobante->id,
            $this->retiro->id,
            $this->retiro->getIdComprobantePago(),
            $this->retiro->getTituloProceso()
        );
        ////////////////////////// MOVIMIENTOS DEL COMPROBANTE /////////////////////////
        $this->movimientos($comprobante);
    }

    protected function getMontos()
    {
        $debe = (new Warp([
            'ret_total_retiro' => $this->retiro->monto_aprobado,
            $this->getConcepto('cta_retiro_rebaja_ingreso_diferido', 'cuenta_x_cobrar_interes'),
        ]))->flatten();

        $haber = (new Warp([
            'ret_comision' => $this->retiro->monto_gasto_administrativo,
            'ret_comision_bancaria' => $this->retiro->monto_comision_bancaria,
            'ret_banco' => $this->retiro->monto_pagar,
            $this->getConcepto('cta_rebaja_préstamo_retiro', 'saldo_deudor_capital'),
            $this->getConcepto('cta_rebaja_ctaxcobrar_prestamo', 'cuenta_x_cobrar_capital'),
            $this->getConcepto('cta_rebaja_ctaxcobrar_interes', 'cuenta_x_cobrar_interes'),
            $this->getConcepto('cta_retiro_ingreso', 'cuenta_x_cobrar_interes'),
        ]))->flatten();

        // $this->debug($debe, $haber);

        $this->validate($debe, $haber);

        return array_merge([], $debe, $haber);
    }

    protected function movimientos($comprobante)
    {
        $movimiento = new Movimiento(
            $comprobante,
            $this->pago->fecha_pago
        );

        $monto_aporte = $this->getMontos();

        $movimiento->crear(
            Parametros::getCuentaContable([
                'clave' => 'ret_total_retiro',
                'escenario' => $this->escenario,
                'tipo_parametro' => $this->tipo_parametro,
                'proceso' => $this->retiro->idAsociado->idunidad,
            ]),
            $monto_aporte['ret_total_retiro']
        );

        foreach ((new Group([
            'by' => 'cta_retiro_rebaja_ingreso_diferido',
            'column' => 'cuenta_x_cobrar_interes',
            'escenario' => $this->escenario,
            'tipo_parametro' => $this->tipo_parametro_rebaja_prestamos,
            'data' => $this->prestamos(),
        ]))->get() as $prestamo) {
            $movimiento->crear(
                $prestamo['cuenta_contable'],
                $prestamo['monto']
            );
        }

        if ($monto_aporte['ret_comision'] > 0) {
            $movimiento->crear(
                Parametros::getCuentaContable([
                    'clave' => 'ret_comision',
                    'escenario' => $this->escenario,
                    'tipo_parametro' => $this->tipo_parametro,
                    'proceso' => $this->retiro->idAsociado->idunidad,
                ]),
                0,
                $monto_aporte['ret_comision']
            );
        }

        if ($monto_aporte['ret_comision_bancaria'] > 0) {
            $movimiento->crear(
                $this->retiro->bancoCuentaContable($this->pago->id_banco),
                0,
                $monto_aporte['ret_comision_bancaria']
            );
        }

        $movimiento->crear(
            $this->retiro->bancoCuentaContable($this->pago->id_banco),
            0,
            $monto_aporte['ret_banco']
        );

        foreach ((new Group([
            'by' => 'cta_rebaja_préstamo_retiro',
            'column' => 'saldo_deudor_capital',
            'escenario' => $this->escenario,
            'tipo_parametro' => $this->tipo_parametro_rebaja_prestamos,
            'data' => $this->prestamos(),
        ]))->get() as $prestamo) {
            $movimiento->crear(
                $prestamo['cuenta_contable'],
                0,
                $prestamo['monto']
            );
        }

        foreach ((new Group([
            'by' => 'cta_rebaja_ctaxcobrar_prestamo',
            'column' => 'cuenta_x_cobrar_capital',
            'escenario' => $this->escenario,
            'tipo_parametro' => $this->tipo_parametro_rebaja_prestamos,
            'data' => $this->prestamos(),
        ]))->get() as $prestamo) {
            $movimiento->crear(
                $prestamo['cuenta_contable'],
                0,
                $prestamo['monto']
            );
        }

        foreach ((new Group([
            'by' => 'cta_rebaja_ctaxcobrar_interes',
            'column' => 'cuenta_x_cobrar_interes',
            'escenario' => $this->escenario,
            'tipo_parametro' => $this->tipo_parametro_rebaja_prestamos,
            'data' => $this->prestamos(),
        ]))->get() as $prestamo) {
            $movimiento->crear(
                $prestamo['cuenta_contable'],
                0,
                $prestamo['monto']
            );
        }

        foreach ((new Group([
            'by' => 'cta_retiro_ingreso',
            'column' => 'cuenta_x_cobrar_interes',
            'escenario' => $this->escenario,
            'tipo_parametro' => $this->tipo_parametro_rebaja_prestamos,
            'data' => $this->prestamos(),
        ]))->get() as $prestamo) {
            $movimiento->crear(
                $prestamo['cuenta_contable'],
                0,
                $prestamo['monto']
            );
        }
    }

    protected function comprobante()
    {
        $this->setProceso($this->retiro);

        $comprobante = new Comprobante();
        $comprobante->fecha_comprobante = $this->fechaComprobante();
        $comprobante->descripcion = $this->retiro->idAsociado->nombreCompleto();
        $comprobante->status = 1;
        $comprobante->nro_documento = $this->retiro->referencia;

        if (! $comprobante->save()) {
            throw new Exception('Error al generar comprobante contable.', $this->codigo_error);
        }

        return $comprobante;
    }

    private function getConcepto($key, $field)
    {
        $datos = $this->prestamos();

        if (! $datos) {
            return [$key => null];
        }

        return (new Warp($datos))->flatMap(function ($prestamo) use ($key, $field) {
            return [
                "{$key}_{$prestamo->id_credito}" => $prestamo->{$field},
            ];
        });
    }

    public function prestamos()
    {
        if (ConfRetiroParcial::configPagarPrestamoConRetiro()->pago_prestamo_retiro_administrador == 0) {
            return null;
        }

        return json_decode($this->retiro->prestamos_pago);
    }
}
