<?php

namespace App\Services\Sale;

use App\Enums\PropertyStatus;
use App\Enums\SalesType;
use App\Repositories\Sale\PaymentPlansRepositoryInterface;

class PaymentPlanService
{
    protected $PaymentPlansRepository;
    public function __construct(
        PaymentPlansRepositoryInterface $PaymentPlansRepository
    ) {
        $this->PaymentPlansRepository = $PaymentPlansRepository;
    }

    public function createPaymentPlans($data, $sales_id)
    {
        foreach ($data as $differData) {
            $differData['sales_id'] = $sales_id;
            $this->PaymentPlansRepository->create($differData);
        }
    }

    // public function updatePayment($data, $paymet_plans_id)
    // {
    //     if (empty($data)) {
    //         return false;
    //     }
    //     $existingPlan = $this->PaymentPlansRepository->find($paymet_plans_id);
    //     foreach ($data as $index => $differData) {
    //         if ($index === 0) {
    //             if ($existingPlan) {
    //                 $this->PaymentPlansRepository->update($existingPlan->id, $differData);
    //             }
    //         } else {
    //             $differData['sales_id'] = $existingPlan->sales_id ;
    //             $this->PaymentPlansRepository->create($differData);
    //         }
    //     }
    //     return true;
    // }

    public function updatePayments($data, $payment_plans_id)
    {
        if (empty($data)) {
            return false;
        }
        $existingPlan = $this->PaymentPlansRepository->find($payment_plans_id);

        if (!$existingPlan) {
            throw new \Exception("Plan de pago no encontrado.");
        }
        if ($existingPlan->is_paid) {
            throw new \Exception("El plan de pago ya ha sido pagado y no puede ser modificado.");
        }
        foreach ($data['differData'] as $index => $differData) {
            if ($index === 0) {
                $this->PaymentPlansRepository->update($existingPlan->id, $differData);
            } else {
                $differData['sales_id'] = $existingPlan->sales_id;
                $this->PaymentPlansRepository->create($differData);
            }
        }
        return $existingPlan;
    }

    public function updatePayment($data, $payment_plans_id)
    {
        $this->PaymentPlansRepository->update($payment_plans_id, $data);
        return $this->PaymentPlansRepository->find($payment_plans_id);
    }

    // //30000, [10000, 20000, 20000]
    // public function confirmPayment($paymentPlan_id, float $amountPaid, array $dividedPayments = [])
    // {
    //     $paymentPlan = $this->PaymentPlansRepository->find($paymentPlan_id);
    //     if ($amountPaid > $paymentPlan->amount) {
    //         return response()->json([
    //             'message' => 'El monto pagado no puede exceder el monto del plan de pago.'
    //         ], 400);
    //     }
    //     if ($amountPaid == $paymentPlan->amount) {
    //         $paymentPlan->is_paid = true;
    //         $paymentPlan->save();
    //     }
    //     // Caso 2 y 3: Pago parcial (con o sin división)
    //     if ($amountPaid < $paymentPlan->amount) {
    //         $remainingAmount = $paymentPlan->amount - $amountPaid;
    //         $paymentPlan->amount = $remainingAmount;
    //         $paymentPlan->save();
    //         $newPaymentPlan = $this->PaymentPlansRepository->create([
    //             'amount' => $amountPaid,
    //             'sales_id' => $paymentPlan->sales_id,
    //             'is_paid' => true,
    //         ]);
    //         if (!empty($dividedPayments)) {
    //             $totalDivided = array_sum($dividedPayments);
    //             if ($totalDivided != $remainingAmount) {
    //                 return response()->json([
    //                     'message' => 'Los pagos divididos no coinciden con el monto restante.'
    //                 ], 400);
    //             }
    //             foreach ($dividedPayments as $partialAmount) {
    //                 $this->PaymentPlansRepository->create([
    //                     'amount' => $partialAmount,
    //                     'sales_id' => $paymentPlan->sales_id,
    //                     'is_paid' => false,  // No confirmado
    //                 ]);
    //             }
    //         }
    //     }
    // }

    public function confirmarPayment($paymentPlan_id)
    {
        $paymentPlan = $this->PaymentPlansRepository->find($paymentPlan_id);
        $paymentPlan->is_paid = true;
        $paymentPlan->save();
        return $paymentPlan;
    }

    public function verifallpayment($sale){
        $initialPayments = $sale->payment_plans->where('type', 'INITIAL_PAYMENT');

        $allPaymentsConfirmed = $initialPayments->every(function ($paymentPlan) {
            return $paymentPlan->is_paid;
        });
        return $allPaymentsConfirmed;
    }

    public function confirmSaleWithPayment($sale){
        $sale->status = SalesType::SALE->value;
        $sale->save();
        $sale->property->every(function ($property) {
             $property->status = PropertyStatus::SALE->value;
             $property->save();
        });
    }

    public function getBySales($sales_id)
    {
        return $this->PaymentPlansRepository->getBySale($sales_id);
    }
}
