<?php

namespace App\Http\Controllers\Api\Cobranzas;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

use App\Danoral\Cobranzas\Cobros\Cobro;
use App\Danoral\Cobranzas\Cobros\CobroFormaPago;
use App\Danoral\Cobranzas\Cobros\CobroView;
use App\Danoral\Cobranzas\Cobros\CobroDTView;
use App\Danoral\Cuotas\Cuota;
use App\Danoral\Cuotas\CuotaEntidad;
use App\Danoral\Cuotas\CuotaCond;
use App\Danoral\Entidades\SyncEntidades;
use App\Danoral\Transacciones\TransDTCobranzas;

use App\Http\Resources\CuotaCond as CuotaCondResources;
use App\Http\Resources\Cobro as CobroResources;
use App\Http\Resources\CobroView as CobroViewResources;
use App\Http\Resources\CobroDTView as CobroDTViewResources;
use App\Http\Resources\CobroUser as CobroUserResources;
use App\Http\Resources\CobroDetalle as CobroDetalleResources;


class CobroController extends Controller
{

    protected $cobro;

    public function __construct(Cobro $cobro){
        $this->cobro = $cobro;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return response()->json(CobroResources::collection(
            Cobro::Where([
                ['origenCobro', $request->origenCobro],
            ])->get()
        ),200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //return response()->json($request);

        $cobroNew = new Cobro;
        $cobroNew->fill($request->input());
        //$cobroNew->save();

        //$cobroNew->refresh();
        //$idCobroNew = $cobroNew->idCobro;

        $cobro = Cobro::latest('idCobro')->first();
        $idCobroNew = $cobro->idCobro;

        if(is_null($idCobroNew)){
            return response()->json("idCobro: null");
        }else{

            //return response()->json("idCobro:" . $cobro->idCobro);

            foreach($request->get('itemsCobro') as $i=>$ic){
                $cuota = Cuota::find($ic['idCuota']);
                $cuota->createTransDTCobro();
                
                if(is_null($cuota->idDTCuotaCobro)){
                    return "cuota->idDTCuotaCobro : null";
                }else{
                    $dtC = new TransDTCobranzas();
                    $dtC->idDT = $cuota->idDTCuotaCobro;
                    $dtC->idCobro = $idCobroNew;
                    $dtC->save();
                }
            }

            foreach($request->get('cobroFormaPago') as $i=>$ip){
                $cfp = new CobroFormaPago();
                $cfp->fill($ip);
                $cfp->idCobro = $idCobroNew;
                $cfp->save();
            }

            return response()->json("OK: Procesado");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Danoral\Cobranzas\Cobros\Cobro  $cobro
     * @return \Illuminate\Http\Response
     */
    public function show(Cobro $cobro)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Danoral\Cobranzas\Cobro  $cobro
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Cobro $cobro)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Danoral\Cobranzas\Cobro  $cobro
     * @return \Illuminate\Http\Response
     */
    public function destroy(Cobro $cobro)
    {
        //
    }

    public function getCobros(Request $request){
        $filtro = $request->input();

        //return response()->json($filtro, 200);

        //inicializacion where
        $where = [];
        //idCobro
        if(!empty($filtro['idCobro'])){  $where[] = ['idCobro', $filtro['idCobro']]; }
        //idEUser
        if(!empty($filtro['idEUser'])){  $where[] = ['idEUser', $filtro['idEUser']]; }

        //codEdif
        if(!empty($filtro['codEdif'])){  
            $codEdif = $filtro['codEdif'];
            
            /*
            $where[] = ['idCobro', function ($query) use ($codEdif){
                $query->select('idCobro')->distinct()
                    ->from('admin26.cobros_dt_view')
                    ->where('codEdifCuota', $codEdif);
                }
            ]; 
            */
        }
        
        //fecha
        if(!empty($filtro['fechaDesde'])){
            $fechaDesde = date("Y-m-d",strtotime($filtro['fechaDesde'])) . ' 00:00:00';
            $where[] = ['dateCobro', '>=', $fechaDesde]; 
            
            if(!empty($filtro['fechaHasta'])){
                $fechaHasta = date("Y-m-d",strtotime($filtro['fechaHasta'])) . ' 23:59:59';
                $where[] = ['dateCobro', '<=', $fechaHasta]; 
            }
        }

        $cobros = Cobro::getCobros(
            CobroView::Where($where)
                ->whereIn('idCobro', function ($query) use ($codEdif){
                    $query->select('idCobro')->distinct()
                        ->from('admin26.cobros_dt_view')
                        ->where('codEdifCuota', $codEdif);
                })
                ->orderBy('dateCobro', 'asc')
                ->orderBy('idCobro', 'asc')
                ->limit(1000)
                ->get()
        );
        

        return response()->json(CobroResources::collection($cobros), 200);
        //return response()->json($cobros, 200);

    }

    public function getCobrosView(Request $request) {

        $filtro = $request->input();

        //return response()->json($filtro, 200);

        //inicializacion where
        $where = [];
        //idEUser
        if(!empty($filtro['idEUser'])){  $where[] = ['idEUser', $filtro['idEUser']]; }
        //fecha
        if(!empty($filtro['fechaDesde'])){
            $fechaDesde = date("Y-m-d",strtotime($filtro['fechaDesde']));
            $where[] = ['dateCobro', '>=', $fechaDesde]; 
            
            if(!empty($filtro['fechaHasta'])){
                $fechaHasta = date("Y-m-d",strtotime($filtro['fechaHasta']));
                $where[] = ['dateCobro', '<=', $fechaHasta]; 
            }
        }

        return response()->json(CobroViewResources::collection(
            CobroView::Where($where)
                ->orderBy('dateCobro', 'asc')
                ->orderBy('idCobro', 'asc')
                ->limit(100)
                ->get()
        ),200);

    }

    public function getCobrosDTView(Request $request) {

        $filtro = $request->input();

        //inicializacion where
        $where = [];
        //idEUser
        if(!empty($filtro['idEUser'])){  $where[] = ['idEUser', $filtro['idEUser']]; }
        //fecha
        if(!empty($filtro['fechaDesde'])){
            $fechaDesde = date("Y-m-d",strtotime($filtro['fechaDesde'])) . ' 00:00:00';
            $where[] = ['dateCobro', '>=', $fechaDesde]; 
            
            if(!empty($filtro['fechaHasta'])){
                $fechaHasta = date("Y-m-d",strtotime($filtro['fechaHasta'])) . ' 23:59:59';
                $where[] = ['dateCobro', '<=', $fechaHasta]; 
            }
        }

        //return response()->json($where, 200);

        return response()->json(CobroDTViewResources::collection(
            CobroDTView::Where($where)
                ->orderBy('dateCobro', 'asc')
                ->orderBy('idCobro', 'asc')
                ->orderBy('anoDT', 'asc')
                ->orderBy('mesDT', 'asc')
                ->limit(100)
                ->get()
        ),200);

    }

    public function getDeuda(Request $request) {
        $idE = $request->idE;
        $idE = ($idE < 999999999)?SyncEntidades::cambioID_apto($idE):$idE;

        $fechaPago = isset($request->fechaPago)?$request->fechaPago:null;
        $cuotasEntidad = CuotaEntidad::getCuotasEntidad($idE, $fechaPago);

        return response()->json($cuotasEntidad, 200);

    }

    public function getDeudaEdif(Request $request){
        $idE = $request->idE;
        $isTasaEmision = false;

        if(isset($request->isTE)){
            $isTasaEmision = ($request->isTE == 'on');
        }

        if($idE < 999999999){
            $idE = SyncEntidades::cambioID_edif($idE);
        }
        $deudaEdif = CuotaCond::getDeudaEdif($idE, $isTasaEmision);
        return response()->json($deudaEdif, 200);
    }

    public function getCuotasCond(Request $request){
        $idE = $request->idE;

        if($idE < 999999999){
            $idE = SyncEntidades::cambioID_apto($idE);
        }
        $cuotasCond = CuotaCond::getCuotasCond($idE);

        return response()->json(CuotaCondResources::collection($cuotasCond), 200);
    }

    public function generarCobro(Request $request){

        //return response()->json($request, 200);

        //cambio id apto
        $idE = $request->idE;
        if($idE < 999999999){
            $idE = SyncEntidades::cambioID_apto($idE);
        }

        $input = $request->all();
        $cobro = new Cobro();
        $cobro->idE = $idE;

        $cobro->validarCargar($input);

        $resCobroGenerado = $cobro->generarCobro();
        $cobroDetalles = $resCobroGenerado['cobroDetalles'];
        
        $sum_montoCFP = 0;
        foreach($cobroDetalles as $cD) {
            $sum_montoCFP += $cD->montoCFP;
        }

        $cobroGenerado = [
            "sum_montoCFP"      => number_format($sum_montoCFP, 2, ',', '.'),
            "idMonedaCFP"       => 1001,
            "cobroDetalles"     => CobroDetalleResources::collection($cobroDetalles),
            "resLog"            => $resCobroGenerado['log'],
        ];

        return response()->json($cobroGenerado, 200);

    }

    public function procesarCobro(Request $request){
        
        $res = '';

        DB::beginTransaction();
        try {
            
            $input = $request->all();
            $cobro = new Cobro();
            $cobro->idEUser = $request->user()->idE;
            $res = $cobro->validarCargar($input);       

            /*
            if(!$cobro->isPlanilla()){
                return response()->json([
                    'codResp'     => 1,
                    'request'   => $request->all(),
                    'cobro'     => $cobro,
                    'res'       => $res,
                    'message'   => ["Planilla no seleccionada"],
                ], 200);   
            }
            */
            if($cobro->isCFP_empty()){
                return response()->json([
                    'codResp'     => 1,
                    'request'   => $request->all(),
                    'cobro'     => $cobro,
                    'res'       => $res,
                    'message'   => ["No se encontro forma de pago"],
                ], 200);   
            }


            $res = $cobro->procesarCobro();

            DB::commit();

            return response()->json([
                'codResp'   => 0,
                'request'   => $request->all(),
                'cobro'     => $cobro,
                'res'       => $res,
                'message'   => ["cobro OK. $cobro->idCobro"],
            ], 200);   

        }catch (\Exception $e) {
            DB::rollback();

            return response()->json([
                'codResp'   => 99,
                'request'   => $request->all(),
                'cobro'     => $cobro,
                'res'       => $res,
                'message'   => [$e->getMessage()],
            ], 200);   
        }
        
        return response()->json([
            'codResp'   => 3,
            'request'   => $request->all(),
            'cobro'     => $cobro,
            'res'       => $res,
            'message'   => ["cobro no procesado"],
        ], 200);   
    }

    public function calcularCobro(Request $request){
        $idE = $request->idE;

        if($idE < 999999999){
            $idE = SyncEntidades::cambioID_apto($idE);
        }
        $cobro = new Cobro();
        $cobro->idE = $idE;
        $cobro->validarCargarCFP($request->CFP); //CFP: CobroFormaPago
        $res = $cobro->calcularCobro_CuotasCond();

        return response()->json($res, 200);
    }

    public function getUsersCobros() {

        $schema = $this->cobro->getSchema_anoActual();

        $users = DB::table("$schema.cobros_view")
            ->select('idEUser','nameE')
            ->distinct()
            ->orderBy('nameE', 'asc')
            ->get();

        return response()->json(
            CobroUserResources::collection($users),
            200);

    }
}
