<?php
// app/Traits/HandlesPayments.php

namespace App\Traits;

use App\Models\Invoice;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;

trait HandlesPayments
{
    /**
     * Get accurate payment data for a reservation
     */
    public function getPaymentData($reservation)
    {
        $data = [
            'total_amount' => 0,
            'paid_amount' => 0,
            'payment_history' => [],
            'installment_count' => 0,
            'balance' => 0,
            'is_fully_paid' => false,
            'is_overpaid' => false,
            'overpaid_amount' => 0
        ];

        // Get the invoice
        $invoice = $reservation->invoices()->first();
        
        if ($invoice) {
            // Get total from invoice
            $data['total_amount'] = (float) $invoice->total_amount;
            
            // Get all payments from this invoice
            $payments = $invoice->payments()->orderBy('created_at', 'asc')->get();
            
            foreach ($payments as $payment) {
                $data['payment_history'][] = [
                    'id' => $payment->id,
                    'amount' => (float) $payment->amount,
                    'method' => $payment->payment_method,
                    'date' => $payment->created_at->format('M j, Y'),
                    'time' => $payment->created_at->format('h:i A'),
                    'reference' => $payment->reference,
                    'notes' => $payment->notes
                ];
                $data['paid_amount'] += (float) $payment->amount;
            }
            
            $data['installment_count'] = count($data['payment_history']);
            $data['balance'] = max(0, $data['total_amount'] - $data['paid_amount']);
            $data['is_fully_paid'] = $data['paid_amount'] >= $data['total_amount'];
            $data['is_overpaid'] = $data['paid_amount'] > $data['total_amount'];
            $data['overpaid_amount'] = $data['is_overpaid'] ? ($data['paid_amount'] - $data['total_amount']) : 0;
        } else {
            // Fallback to reservation fields if no invoice
            $data['total_amount'] = (float) ($reservation->total_amount ?? 0);
            $data['paid_amount'] = (float) ($reservation->paid_amount ?? 0);
            
            if ($data['paid_amount'] > 0) {
                $data['payment_history'][] = [
                    'id' => null,
                    'amount' => $data['paid_amount'],
                    'method' => $reservation->payment_method ?? 'cash',
                    'date' => $reservation->created_at->format('M j, Y'),
                    'time' => $reservation->created_at->format('h:i A'),
                    'reference' => 'INITIAL',
                    'notes' => 'Initial payment'
                ];
            }
            
            $data['installment_count'] = $data['paid_amount'] > 0 ? 1 : 0;
            $data['balance'] = max(0, $data['total_amount'] - $data['paid_amount']);
            $data['is_fully_paid'] = $data['paid_amount'] >= $data['total_amount'];
            $data['is_overpaid'] = $data['paid_amount'] > $data['total_amount'];
            $data['overpaid_amount'] = $data['is_overpaid'] ? ($data['paid_amount'] - $data['total_amount']) : 0;
        }

        return $data;
    }

    /**
     * Calculate overstay fees
     */
    public function calculateOverstay($reservation)
    {
        $overstayDays = 0;
        $overstayFees = 0;
        
        if ($reservation->status === 'checked_in') {
            $checkOutDate = \Carbon\Carbon::parse($reservation->check_out)->startOfDay();
            $today = \Carbon\Carbon::now()->startOfDay();
            
            if ($today->greaterThan($checkOutDate)) {
                $overstayDays = $today->diffInDays($checkOutDate);
                $roomPrice = $reservation->room->price_per_night ?? 0;
                $overstayFeePerDay = ceil($roomPrice * 1.2); // 20% extra for overstay
                $overstayFees = $overstayDays * $overstayFeePerDay;
            }
        }
        
        return [
            'days' => $overstayDays,
            'fees' => $overstayFees,
            'fee_per_day' => ceil(($reservation->room->price_per_night ?? 0) * 1.2)
        ];
    }
}