<?php

namespace App\Http\Controllers\Customer;

use App\Core\Repositories\InvoiceRepository;
use App\Core\Services\Invoice\PdfService;
use App\Http\Controllers\Controller;
use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;

class CustomerInvoiceController extends Controller
{
    public function __construct(
        private InvoiceRepository $invoiceRepository,
        private PdfService $pdfService
    ) {}

    /**
     * Display a listing of customer's invoices
     */
    public function index(Request $request): View
    {
        $customer = Auth::guard('customer')->user();

        $filters = [
            'customer_id' => $customer->id,
            'status' => $request->get('status'),
            'date_from' => $request->get('date_from'),
            'date_to' => $request->get('date_to'),
        ];

        $invoices = $this->invoiceRepository->getPaginated(15, $filters);

        return view('customer.invoices.index', [
            'invoices' => $invoices,
        ]);
    }

    /**
     * Display the specified invoice
     */
    public function show(int $id): View|Response
    {
        $customer = Auth::guard('customer')->user();
        $invoice = $this->invoiceRepository->getById($id);

        // Ensure customer can only view their own invoices
        if (! $invoice || $invoice->customer_id !== $customer->id) {
            abort(404);
        }

        return view('customer.invoices.show', [
            'invoice' => $invoice,
        ]);
    }

    /**
     * Download invoice PDF
     */
    public function downloadPdf(int $id): Response
    {
        $customer = Auth::guard('customer')->user();
        $invoice = $this->invoiceRepository->getById($id);

        // Ensure customer can only download their own invoices
        if (! $invoice || $invoice->customer_id !== $customer->id) {
            abort(404);
        }

        return $this->pdfService->download($invoice);
    }
}
