<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Invoice;
use App\Models\Client;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceController extends Controller
{
    public function index() {
        return response()->json(Invoice::with('client')->get());
    }

    public function store(Request $request) {
        $invoice = Invoice::create($request->all());
        // generate PDF (simple example)
        $pdf = Pdf::loadView('invoices.template', ['invoice' => $invoice]);
        $path = 'invoices/' . $invoice->id . '.pdf';
        $pdf->save(storage_path('app/' . $path));
        $invoice->update(['pdf_path' => $path]);
        return response()->json($invoice, 201);
    }

    public function show($id) {
        return response()->json(Invoice::with('client')->findOrFail($id));
    }

    public function update(Request $request, $id) {
        $invoice = Invoice::findOrFail($id);
        $invoice->update($request->all());
        return response()->json($invoice);
    }

    public function destroy($id) {
        Invoice::findOrFail($id)->delete();
        return response()->json(['message' => 'Invoice deleted']);
    }
}
