<?php

namespace App\Http\Controllers;

use App\DTOs\Quota\QuotaCreateDto;
use App\DTOs\Quota\QuotaUpdateDto;
use App\Http\Controllers\Controller;
use App\Models\Quota;
use App\Repositories\Interfaces\IQuotaRepository;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class QuotaController extends Controller
{

    private $iQuotaRepository;
    private $errorConnection = "";

    public function __construct(Request $request, IQuotaRepository $iQuotaRepository)
    {
        if (isset($request['business_information'])) {
            $business_information = $request['business_information'];
            $ruc = $business_information['ruc_number'];

            $existe_conexion = $this->setDBClient($ruc);

            if ($existe_conexion['error']) {
                $this->errorConnection = $existe_conexion['message'];
                return $this->messageError("Se espera un numero de RUC valido.", 422);
            } else {
                $this->iQuotaRepository = $iQuotaRepository;
            }
        } else {
            $this->errorConnection = 'Error en la conexion. Se espera numero de RUC';
        }
    }
    public function index(Request $request)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 422);
        }

        $result = $this->iQuotaRepository->paginate($request->all());

        if ($result) {
            return $this->successResponse($result, "Cuotas encontradas correctamente", 200);
        } else {
            return $this->errorResponse("No hay cuotas", 200);
        }
    }
    public function store(Request $request)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }
        $erroresArray = [];
        $errores = [];
        $business_information = $request['business_information'];
        $ruc = $business_information['ruc_number'];

        if(!isset($request['cuotas']) || empty($request['cuotas'])){
            return $this->messageError("Las cuotas son obligatorias", 422);
        }
        if(!isset($request['sale_id']) || empty($request['sale_id'])){
            array_push($errores, 'Las cuotas deben estar relacionadas a una venta');
        }else{
            if(!is_numeric($request['sale_id'])){
                array_push($errores, 'El identificador de la venta debe se numérico');
            }
        }
        if(!isset($request['currency']) || empty($request['currency'])){
            array_push($errores, 'El código de moneda es requerido');
        }
        else{
            if(!$this->currency_validate($request['currency'])){
                array_push($errores, 'El código de moneda no es válido.');
            }
        }
        if(!isset($request['created_by']) || empty($request['created_by'])){
            array_push($errores, 'El usuario de creación es requerido');
        }
        else{
            if(!is_numeric($request['created_by'])){
                array_push($errores, 'El identificador del usuario debe se numérico');
            }
        }
        if(!empty($errores)){
            $erroresArray[0] = $errores;
        }
        foreach($request['cuotas'] as $index => $cuotaItem){
            $errores = [];
            $rs_quota = Quota::where('sale_id',$request['sale_id'])->where('quota',$index)->get();
            if(count($rs_quota)>0){
                array_push($errores, 'La venta ya tiene registrado la cuota '.$index);
            }
            else{
                if(!is_numeric($cuotaItem['amount'])){
                    array_push($errores, 'El importe debe ser numérico');
                }
            }
            if(!isset($cuotaItem['payment_date']) || empty($cuotaItem['payment_date'])){
                array_push($errores, 'La fecha de pago es requerido');
            }
            else{
                $paymentDateArray = explode("-",$cuotaItem['payment_date']);
                if(count($paymentDateArray) != 3){
                    array_push($errores, 'La fecha ingresada no es válida.');
                }else{
                    if(!checkdate($paymentDateArray[1],$paymentDateArray[0],$paymentDateArray[2])){
                        array_push($errores, 'La fecha debe tener el formato "dd-mm-aaaa".'.json_encode($paymentDateArray));
                    }
                }
            }
            $erroresArray['cuota'][$index] = $errores;
        }
        if(!empty($errores)){
            return $this->messageError($erroresArray, 422);
        }
        $resultArray = [];
        foreach ($request['cuotas'] as $index => $cuotaItem) {
            $store = new QuotaCreateDto($cuotaItem);
            $store->ruc = $ruc;
            $store->sale_id = $request['sale_id'];
            $store->currency = $request['currency'];
            $store->quota = $index;
            $store->sunat_code = "Cuota".str_pad($index, 3, "0", STR_PAD_LEFT);
            $store->status_quota = 1;
            $paymentDateArray = explode("-",$cuotaItem['payment_date']);
            $store->payment_date = $paymentDateArray[2]."-".$paymentDateArray[1]."-".$paymentDateArray[0];
            $store->created_by = $request['created_by'];
            $store->created_at = date('Y-m-d h:m:s');
            $store->status = 1;
            $result = $this->iQuotaRepository->store($store);
            array_push($resultArray, $result);
        }
        return $this->successResponse($resultArray,'Cuotas registradas correctamente',200);
    }
    public function show($id)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }
        if (!is_numeric($id)) {
            return $this->messageError("identificador de la cuota no es correcto", 422);
        }

        $result = $this->iQuotaRepository->find($id);

        if ($result) {
            return $this->successResponse($result, "cuota ebcontrada correctamente", 200);
        } else {
            return $this->errorResponse("Cuota no encontrada", 200);
        }
    }
    public function update($id, Request $request)
    {
        if (!is_numeric($id)) {
            return $this->messageError("identificador de la cuota no es correcto", 422);
        }

        $business_information = $request['business_information'];
        $ruc = $business_information['ruc_number'];
        $result = $this->iQuotaRepository->find($id);
        $cuotaItem = $request['quota'];

        if ($result) {
            $errores = [];
            if(!isset($cuotaItem['amount_paid']) || empty($cuotaItem['amount_paid'])){
                array_push($errores, 'El importe de pago es requerido');
            }
            else{
                if(!is_numeric($cuotaItem['amount_paid'])){
                    array_push($errores, 'El importe pagado no es válido.');
                }
                if($cuotaItem['amount_paid'] <= 0){
                    array_push($errores, 'El importe pagado debe ser mayor a 0');
                }
            }


            if(!isset($cuotaItem['updated_by']) || empty($cuotaItem['updated_by'])){
                array_push($errores, 'El usuario es requerido');
            }
            else{
                if(!is_numeric($cuotaItem['updated_by'])){
                    array_push($errores, 'El identificador del usuario debe se numérico');
                }
            }
            if($result->status_quota == 2){
                array_push($errores, 'La cuota está pagada.');
            }


            if(!empty($errores)){
                return $this->messageError($errores, 422);
            }

            $data = $request['quota'];

            if($result->amount_paid != null){
                $data['amount_paid'] = $result->amount_paid + $data['amount_paid'];
            }

            if($result->amount > $data['amount_paid']){
                $data['status_quota'] = 1;
            }else if($result->amount <= $data['amount_paid']){
                $data['status_quota'] = 2;
            }
            $data['id'] = $id;
            $data['ruc'] = $ruc;
            $data['updated_at'] = date('Y-m-d h:m:s');
            $entry = new QuotaUpdateDto($data);
            $this->iQuotaRepository->update($entry);

            $result = $this->iQuotaRepository->find($id);

            return $this->successResponse($result, "La cuota fue actualizada.", 201);
        } else {
            return $this->errorResponse("La cuota no existe.", 201);
        }
    }
    public function destroy($id)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }
        if (!is_numeric($id)) {
            return $this->messageError("identificador de la cuota no es correcto", 422);
        }
        $result = $this->iQuotaRepository->find($id);

        if ($result) {
            $this->iQuotaRepository->destroy($id);

            return $this->successResponse($id, "Cuota eliminado correctamente", 200);
        } else {
            return $this->errorResponse("Cuota ingresado no existe", 404);
        }
    }
    public function destroyQuotaBySale($saleId, Request $request)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }
        if (!is_numeric($saleId)) {
            return $this->messageError("identificador de la cuota no es correcto", 422);
        }

        $result = $this->iQuotaRepository->findBySale($saleId);

        if ($result) {
            $business_information = $request['business_information'];
            $ruc = $business_information['ruc_number'];
            $this->iQuotaRepository->destroyQuotaBySale($saleId, $ruc);

            return $this->successResponse($saleId, "Quotas eliminadas correctamente", 200);
        } else {
            return $this->errorResponse("Quotas no existen", 404);
        }
    }

    private function currency_validate($currency){
        switch($currency){
            case "PEN":
                $validate = true;
                break;
            case "USD":
                $validate = true;
                break;
            case "EUR":
                $validate = true;
                break;
            default:
                $validate = false;
                break;
        }
        return $validate;
    }
}
