<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class InstallmentPlanResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'reservation_id' => $this->reservation_id,
            'total_amount' => (float) $this->total_amount,
            'down_payment' => (float) $this->down_payment,
            'installment_count' => $this->installment_count,
            'installment_amount' => (float) $this->installment_amount,
            'frequency' => $this->frequency,
            'start_date' => $this->start_date->format('Y-m-d'),
            'end_date' => $this->end_date->format('Y-m-d'),
            'status' => $this->status,
            'terms' => $this->terms,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
            
            // Relationships
            'reservation' => new ReservationResource($this->whenLoaded('reservation')),
            'payments' => InstallmentPaymentResource::collection($this->whenLoaded('payments')),
            
            // Calculated fields
            'total_paid' => (float) $this->payments->sum('paid_amount'),
            'total_due' => (float) ($this->total_amount - $this->payments->sum('paid_amount')),
            'next_payment_due' => $this->getNextPaymentDue(),
            'overdue_amount' => $this->getOverdueAmount(),
            'payment_progress' => $this->getPaymentProgress(),
        ];
    }

    private function getNextPaymentDue()
    {
        $nextPayment = $this->payments
            ->where('status', '!=', 'paid')
            ->sortBy('due_date')
            ->first();
            
        return $nextPayment ? [
            'installment_number' => $nextPayment->installment_number,
            'due_date' => $nextPayment->due_date->format('Y-m-d'),
            'due_amount' => (float) $nextPayment->due_amount,
            'status' => $nextPayment->status,
        ] : null;
    }

    private function getOverdueAmount()
    {
        return (float) $this->payments
            ->where('status', 'overdue')
            ->sum(fn($payment) => $payment->due_amount - $payment->paid_amount);
    }

    private function getPaymentProgress()
    {
        $totalPaid = $this->payments->sum('paid_amount');
        $percentage = $this->total_amount > 0 ? ($totalPaid / $this->total_amount) * 100 : 0;
        
        return [
            'percentage' => round($percentage, 2),
            'paid_amount' => (float) $totalPaid,
            'remaining_amount' => (float) ($this->total_amount - $totalPaid),
            'paid_installments' => $this->payments->where('status', 'paid')->count(),
            'total_installments' => $this->installment_count,
        ];
    }
}