<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Services\ReceiptService;
use Illuminate\Http\Request;

class BookingController extends Controller
{
    protected $receiptService;

    public function __construct(ReceiptService $receiptService)
    {
        $this->receiptService = $receiptService;
    }

    public function receipt($id)
    {
        $booking = Booking::with(['listing.location', 'listing.rentalType', 'listing.host', 'user', 'addOns', 'payment'])
            ->findOrFail($id);

        // Allow access to: booking owner, listing owner (host), or admin
        $isBookingOwner = $booking->user_id === auth()->id();
        $isListingOwner = $booking->listing->user_id === auth()->id();
        $isAdmin = auth()->user()->isAdmin();

        if (!$isBookingOwner && !$isListingOwner && !$isAdmin) {
            abort(403, 'Unauthorized access to this receipt.');
        }

        // Only show receipt for confirmed or completed bookings
        if (!in_array($booking->status, ['confirmed', 'completed'])) {
            abort(403, 'Receipt is only available for confirmed or completed bookings.');
        }

        // Get selected receipt template from settings
        $template = \App\Models\Setting::get('receipt_template', 'professional');

        // Determine which view to use
        $viewName = $template === 'compact' ? 'bookings.receipt-compact' : 'bookings.receipt';

        return view($viewName, compact('booking'));
    }

    public function hostReceipt($id)
    {
        $booking = Booking::with(['listing.location', 'listing.rentalType', 'listing.host', 'user', 'addOns', 'payment', 'hostReceipt'])
            ->findOrFail($id);

        // Only listing owner (host) or admin can access
        $isListingOwner = $booking->listing->user_id === auth()->id();
        $isAdmin = auth()->user()->isAdmin();

        if (!$isListingOwner && !$isAdmin) {
            abort(403, 'Unauthorized access to host receipt.');
        }

        // Only show receipt for confirmed or completed bookings
        if (!in_array($booking->status, ['confirmed', 'completed'])) {
            abort(403, 'Receipt is only available for confirmed or completed bookings.');
        }

        // Generate host receipt if doesn't exist
        if (!$booking->hostReceipt) {
            $this->receiptService->generateHostReceipt($booking);
            $booking->load('hostReceipt');
        }

        // Get selected receipt template from settings
        $template = \App\Models\Setting::get('receipt_template', 'professional');

        // Determine which view to use
        $viewName = $template === 'compact' ? 'bookings.host-receipt-compact' : 'bookings.host-receipt';

        return view($viewName, compact('booking'));
    }

    public function completeHostPayout(Request $request, $id)
    {
        // Only admin can complete payouts
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Unauthorized action.');
        }

        $booking = Booking::with('hostReceipt')->findOrFail($id);

        if (!$booking->hostReceipt) {
            return back()->with('error', 'Host receipt not found.');
        }

        $request->validate([
            'payout_reference' => 'required|string|max:255',
            'payout_notes' => 'nullable|string',
        ]);

        $this->receiptService->updatePayoutStatus(
            $booking->hostReceipt,
            'completed',
            $request->payout_reference,
            $request->payout_notes
        );

        return back()->with('success', 'Payout marked as completed successfully!');
    }
}
