<?php

namespace App\Services;

use App\Mail\CustomerInvoiceMail;
use App\Models\Customers;
use App\Models\Invoices;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class InvoiceService
{
    public static function generateAndSend($customer_id, $order, $transaction, $invoice_id)
    {
        $customer = Customers::find($customer_id);
        $invoice = Invoices::find($invoice_id);
        $invoiceNumber = $invoice->invoice_number;

        $order->load([
            'items.course'
        ]);

        // Generate PDF
        $pdf = Pdf::loadView('templates.invoices.invoice', [
            'invoice'     => $invoice,
            'transaction' => $transaction,
            'customer'    => $customer,
            'order'       => $order,
        ]);

        $filePath = 'invoices/' . date('y/m/d') . '/' . $invoiceNumber . '.pdf';
        Storage::disk('public')->put($filePath, $pdf->output());

        $invoice->update(['file_path' => $filePath]);
        $invoice->enc_id = Crypt::encrypt($invoice->id);

        // Send Email
        if ($customer && $customer->email) {
            // $downloadLink = url('/invoices/' . $invoice->enc_id . '/download');
            $downloadLink = route('invoice.download', $invoice->enc_id);
            Mail::to($customer->email)->send(new CustomerInvoiceMail($invoice, $downloadLink));
        }

        return $invoice;
    }
}
