<?php
namespace App\Services;

use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\CompanySetting;
use App\Models\ActivityLog;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceService
{
    public function create(array $data, array $items, int $userId): Invoice
    {
        $data['invoice_number'] = Invoice::generateNumber($data['division']);
        $data['created_by']     = $userId;
        $data['status']         = 'draft';

        $invoice = Invoice::create($data);

        foreach ($items as $item) {
            $item['invoice_id'] = $invoice->id;
            $item['total']      = ($item['qty'] ?? 1) * ($item['unit_price'] ?? 0);
            InvoiceItem::create($item);
        }
        $invoice->recalculate();
        ActivityLog::log('invoice', 'created', "Invoice #{$invoice->invoice_number} dibuat", $invoice);
        return $invoice;
    }

    public function generatePdf(Invoice $invoice): string
    {
        $invoice->load(['client','items','createdBy']);
        $setting = CompanySetting::forDivision($invoice->division);

        $pdf      = Pdf::loadView('admin.invoices.pdf', compact('invoice','setting'))
                       ->setPaper('a4','portrait');
        $filename = "invoice_{$invoice->invoice_number}.pdf";
        $dir      = storage_path('app/public/invoices');
        if (!is_dir($dir)) mkdir($dir, 0775, true);
        $path = $dir.'/'.$filename;
        $pdf->save($path);
        return $path;
    }

    public function sendToClient(Invoice $invoice): void
    {
        $notif = new NotificationService();
        $invoice->update(['status'=>'sent']);
        $notif->notifyInvoiceSent($invoice->fresh()->load('client'));
        ActivityLog::log('invoice', 'sent', "Invoice #{$invoice->invoice_number} dikirim", $invoice);
    }
}
