<?php

namespace App\Services;

use App\Models\Booking;
use App\Models\Setting;
use App\Models\LedgerEntry;
use App\Models\Customer;

class CancellationService
{
    protected $balanceService;

    public function __construct(BalanceService $balanceService)
    {
        $this->balanceService = $balanceService;
    }

    public function cancelBooking(Booking $booking)
    {
        // 1. Calculate Paid Amount
        $financials = $this->balanceService->calculateForBooking($booking);
        $paidAmount = $financials['paid'];

        // 2. Fetch Deduction Rules
        $deductionPercent = Setting::where('key', 'cancellation_deduction_percent')->value('value') ?? 10;
        
        // Deduction usually on Total Price
        $deductionAmount = $booking->total_price * ($deductionPercent / 100);
        
        // 3. Calculate Refund
        $refundAmount = $paidAmount - $deductionAmount;
        if ($refundAmount < 0) {
            $refundAmount = 0;
        }

        // 4. Update Booking and Property
        $booking->update([
            'status' => 'Cancelled'
        ]);
        
        if ($booking->property) {
            $booking->property->update([
                'status' => 'Available for Sale'
            ]);
        }

        // 5. Automated Ledger Postings for Refund
        if ($refundAmount > 0) {
            // Debit Customer (Reducing Accounts Payable / Liability to them for refund)
            LedgerEntry::create([
                'account_type' => Customer::class,
                'account_id' => $booking->customer_id,
                'reference_type' => Booking::class,
                'reference_id' => $booking->id,
                'type' => 'Debit',
                'amount' => $refundAmount,
                'description' => 'Refund Voucher for Cancelled Booking',
                'date' => now()->toDateString(),
            ]);

            // Credit Cash/Bank (Money leaving the business)
            LedgerEntry::create([
                'account_type' => 'Bank', // Defaulting to Bank for refunds
                'account_id' => null,
                'reference_type' => Booking::class,
                'reference_id' => $booking->id,
                'type' => 'Credit',
                'amount' => $refundAmount,
                'description' => 'Refund Payment for Cancelled Booking',
                'date' => now()->toDateString(),
            ]);
        }

        // Log deduction as income if applicable
        if ($deductionAmount > 0) {
            LedgerEntry::create([
                'account_type' => Customer::class,
                'account_id' => $booking->customer_id,
                'reference_type' => Booking::class,
                'reference_id' => $booking->id,
                'type' => 'Debit',
                'amount' => $deductionAmount,
                'description' => 'Cancellation Deduction',
                'date' => now()->toDateString(),
            ]);
            
            LedgerEntry::create([
                'account_type' => 'Income',
                'account_id' => null,
                'reference_type' => Booking::class,
                'reference_id' => $booking->id,
                'type' => 'Credit',
                'amount' => $deductionAmount,
                'description' => 'Cancellation Penalty Income',
                'date' => now()->toDateString(),
            ]);
        }

        return [
            'paid' => $paidAmount,
            'deduction' => $deductionAmount,
            'refund' => $refundAmount
        ];
    }
}