<?php

namespace App\Http\Controllers;

use App\Models\Receipt;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Barryvdh\DomPDF\Facade\Pdf;

class ReceiptController extends Controller
{
    /**
     * Display a listing of all receipts.
     */
    public function index(Request $request)
    {
        $query = Receipt::with(['booking.room.roomType', 'booking.primaryCustomer']);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('receipt_number', 'like', "%{$search}%")
                  ->orWhereHas('booking.primaryCustomer', function($customerQuery) use ($search) {
                      $customerQuery->where('first_name', 'like', "%{$search}%")
                                   ->orWhere('last_name', 'like', "%{$search}%")
                                   ->orWhere('document_number', 'like', "%{$search}%");
                  })
                  ->orWhereHas('booking.room', function($roomQuery) use ($search) {
                      $roomQuery->where('room_no', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by date range
        if ($request->filled('date_from')) {
            $query->where('issued_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->where('issued_at', '<=', $request->date_to . ' 23:59:59');
        }

        $receipts = $query->orderBy('issued_at', 'desc')->paginate(10);
        
        return view('backend.receipts.index', compact('receipts'));
    }

    /**
     * Display the receipt for a booking.
     */
    public function show(Receipt $receipt)
    {
        $receipt->load(['booking.room.roomType', 'booking.bookingCustomers']);
        return view('backend.receipts.show', compact('receipt'));
    }

    /**
     * Display the receipt for a booking by booking ID.
     */
    public function showByBooking(Booking $booking)
    {
        $receipt = $booking->receipt;
        
        if (!$receipt) {
            return redirect()->route('bookings.index')->with('error', 'Receipt not found for this booking.');
        }

        $receipt->load(['booking.room.roomType', 'booking.bookingCustomers']);
        return view('backend.receipts.show', compact('receipt'));
    }

    /**
     * Download receipt as PDF.
     */
    public function download(Receipt $receipt)
    {
        try {
            $receipt->load(['booking.room.roomType', 'booking.bookingCustomers']);
            
            $pdf = Pdf::loadView('backend.receipts.pdf', compact('receipt'));
            
            return $pdf->download('receipt-' . $receipt->receipt_number . '.pdf');
        } catch (\Exception $e) {
            Log::error('Error generating PDF receipt: ' . $e->getMessage());
            return back()->with('error', 'Error generating PDF receipt.');
        }
    }

    /**
     * Download receipt as PDF by booking ID.
     */
    public function downloadByBooking(Booking $booking)
    {
        $receipt = $booking->receipt;
        
        if (!$receipt) {
            return redirect()->route('bookings.index')->with('error', 'Receipt not found for this booking.');
        }

        return $this->download($receipt);
    }

    /**
     * Print receipt (show in browser).
     */
    public function print(Receipt $receipt)
    {
        try {
            $receipt->load(['booking.room.roomType', 'booking.bookingCustomers']);
            
            $pdf = Pdf::loadView('backend.receipts.pdf', compact('receipt'));
            
            return $pdf->stream('receipt-' . $receipt->receipt_number . '.pdf');
        } catch (\Exception $e) {
            Log::error('Error generating PDF receipt: ' . $e->getMessage());
            return back()->with('error', 'Error generating PDF receipt.');
        }
    }

    /**
     * Print receipt by booking ID.
     */
    public function printByBooking(Booking $booking)
    {
        $receipt = $booking->receipt;
        
        if (!$receipt) {
            return redirect()->route('bookings.index')->with('error', 'Receipt not found for this booking.');
        }

        return $this->print($receipt);
    }

    /**
     * Display receipt optimized for thermal printer (80mm).
     */
    public function thermalPrint(Receipt $receipt)
    {
        $receipt->load(['booking.room.roomType', 'booking.bookingCustomers']);
        return view('backend.receipts.thermal', compact('receipt'));
    }

    /**
     * Display thermal receipt by booking ID.
     */
    public function thermalPrintByBooking(Booking $booking)
    {
        $receipt = $booking->receipt;
        
        if (!$receipt) {
            return redirect()->route('bookings.index')->with('error', 'Receipt not found for this booking.');
        }

        return $this->thermalPrint($receipt);
    }
}
