<?php

class ReversoAprobacion extends Aprobacion
{
    public function __construct($ordenPago)
    {
        parent::__construct($ordenPago);
    }

    public function getNombreProveedor()
    {
        return $this->ordenPago->id_tipo_persona .' '. $this->ordenPago->rif . ' '. $this->ordenPago->razon_social;
    }

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

        $comprobante = new Comprobante();
        $comprobante->fecha_comprobante = $this->fechaComprobante();
        $comprobante->descripcion = 'Reverso: '.$this->getNombreProveedor();
        $comprobante->status = 1;
        $comprobante->nro_documento = $this->ordenPago->rif;

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

        return $comprobante;
    }

    protected function movimientos($comprobante)
    {
        $movimiento = new Movimiento(
            $comprobante,
            date('d-m-Y')
        );

        $saldos = $this->getMontos();

        $movimiento->crear(
            $this->getCuentaProveedor(),
            $saldos['cta_x_pagar_proveedor']
        );

        $movimiento->crear(
            $this->getCuentaConcepto(),
            0,
            $saldos['cta_concepto_operacion']
        );
    }

    protected function getMontos()
    {
        $debe = [
            'cta_x_pagar_proveedor' => $this->ordenPago->monto_pago
        ];

        $haber = [
            'cta_concepto_operacion' => $this->ordenPago->monto_pago,
        ];

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

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

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

    protected function flip($movimientos, $from, $to)
    {
        $movimeintos = (new Warp($movimientos))->filter(function ($movimiento) use ($to) {
            return $movimiento[$to] == 0;
        });

        return (new Warp($movimeintos))->map(function ($movimiento) use ($from, $to) {
            return [
                'id' => $movimiento['id'],
                'id_cuenta' => $movimiento['id_cuenta'],
                'referencia' => $movimiento['referencia'],
                'clv_comprobante' => $movimiento['clv_comprobante'],
                $to => $movimiento[$from],
            ];
        });
    }

    protected function getCuentaConcepto()
    {
        if ($this->ordenPago->id_tipo_orden == 3) {
            return Operacion::getCuentaContableFromConcepto($this->ordenPago->id_concepto_reverso);
        }

        $concepto = $this->ordenPago->concepto;

        if (is_null($concepto->id_cuenta)) {
            throw new Exception("El concepto <strong>{$concepto->descripcion}</strong>, no tiene una cuenta auxiliar definida {$this->configuracionConceptoUrl()}.");
        }

        return $concepto->id_cuenta;
    }
}
