<?php

namespace App\Services;

use App\Models\Booking;
use App\Models\HostReceipt;
use Carbon\Carbon;

class ReceiptService
{
    /**
     * Generate host receipt for a booking
     */
    public function generateHostReceipt(Booking $booking): HostReceipt
    {
        // Check if host receipt already exists
        if ($booking->hostReceipt) {
            return $booking->hostReceipt;
        }

        // Calculate amounts
        $days = Carbon::parse($booking->check_in)->diffInDays(Carbon::parse($booking->check_out));
        $baseAmount = $booking->listing->price_per_day * $days;
        $addonAmount = $booking->addOns->sum('pivot.price_paid');
        $discountAmount = $booking->discount_amount ?? 0;

        // Subtotal before fees (gross revenue for host)
        $subtotal = $baseAmount + $addonAmount - $discountAmount;

        // Calculate platform fee (charged to host, NOT the gateway fee)
        // Gateway fee is charged to guests, platform fee is deducted from host
        $platformFee = PlatformFeeService::calculateFee($subtotal);

        // Service fee (can be configured separately)
        $serviceFee = 0; // Add custom service fee logic if needed

        // Total deductions
        $totalDeductions = $platformFee + $serviceFee;

        // Host payout = Subtotal - All fees
        $hostPayout = $subtotal - $totalDeductions;

        // Create host receipt
        return HostReceipt::create([
            'booking_id' => $booking->id,
            'base_amount' => $baseAmount,
            'addon_amount' => $addonAmount,
            'discount_amount' => $discountAmount,
            'subtotal' => $subtotal,
            'platform_fee' => $platformFee,
            'service_fee' => $serviceFee,
            'total_deductions' => $totalDeductions,
            'host_payout' => $hostPayout,
            'payout_status' => 'pending',
        ]);
    }

    /**
     * Update payout status for host receipt
     */
    public function updatePayoutStatus(
        HostReceipt $hostReceipt,
        string $status,
        ?string $reference = null,
        ?string $notes = null
    ): HostReceipt {
        $data = ['payout_status' => $status];

        if ($status === 'completed') {
            $data['payout_date'] = now();
        }

        if ($reference) {
            $data['payout_reference'] = $reference;
        }

        if ($notes) {
            $data['payout_notes'] = $notes;
        }

        $hostReceipt->update($data);

        return $hostReceipt->fresh();
    }
}
