<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\SalesInvoiceRequest;
use App\Http\Resources\SalesInvoiceResource;
use App\Models\SalesInvoice;
use App\Services\SalesInvoiceService;
use Illuminate\Http\Request;

class SalesInvoiceController extends Controller
{
    protected $service;

    public function __construct(SalesInvoiceService $service)
    {
        $this->service = $service;
    }

    public function index(Request $request)
    {
        $invoices = $this->service->list($request);

        return ApiResponse::pagination(
            $invoices,
            SalesInvoiceResource::class,
            'Invoices fetched successfully.'
        );
    }

    public function store(SalesInvoiceRequest $request)
    {
        $invoice = $this->service->generate($request);

        return ApiResponse::success(
            'Invoice generated successfully.',
            new SalesInvoiceResource($invoice)
        );
    }

    public function show(SalesInvoice $salesInvoice)
    {
        return ApiResponse::success(
            'Invoice fetched successfully.',
            new SalesInvoiceResource(
                $this->service->show($salesInvoice)
            )
        );
    }

    public function destroy(SalesInvoice $salesInvoice)
    {
        $this->service->cancel($salesInvoice);

        return ApiResponse::success(
            'Invoice cancelled successfully.'
        );
    }
    
    public function downloadPdf(SalesInvoice $salesInvoice)
    {
        $invoice = $this->service->show($salesInvoice);
    
        $pdf = Pdf::loadView(
            'pdf.invoice',
            compact('invoice')
        );
    
        return $pdf->download(
            $invoice->invoice_no . '.pdf'
        );
    }
}