<?php

namespace App\Repositories\Shop;

use Carbon\Carbon;
use LaravelDaily\Invoices\Classes\InvoiceItem;
use LaravelDaily\Invoices\Classes\Party;
use LaravelDaily\Invoices\Invoice;

class InvoicePDF
{
    public static function getByUUID($uuid)
    {
        return self::get(Invoices::getIdByUUID($uuid));
    }

    public static function get($id)
    {
        $invoice = Invoices::getFull($id);
        $customFields = [];
        if ($orderRef = optional($invoice->order)->ref) {
            $customFields['Numéro de commande'] = $orderRef;
        }

        $customer = new Party([
            'name' => optional($invoice->customer)->name ?? __('Client inconnu'),
            'address' => self::makeAddress($invoice->address),
            'custom_fields' => $customFields,
        ]);

        $items = self::makeItems($invoice->order->detail);

        $invoice = Invoice::make(__('invoices::invoice.invoice').' '.$invoice->ref)
            ->status(Invoices::getStatus($invoice->status))
            ->buyer($customer)
            ->shipping($invoice->shipping)
            ->date(Carbon::parse($invoice->date_invoice))
            ->payUntilDays(14)
            ->filename('invoice-'.$invoice->ref.'-'.$invoice->uuid)
            ->addItems($items)
            ->notes($invoice->comment ?? '')
            ->logo(public_path('img/logo.png'))
            ->save('public');

        $link = $invoice->url();
        // Then send email to party with link

        // And return invoice itself to browser or have a different view
        return $invoice->stream();
    }

    public static function makeAddress($address)
    {
        if (! $address) {
            return '';
        }

        $lines = array_filter([
            $address->address ?? '',
            $address->address2 ?? '',
            trim(($address->zipcode ?? '').' '.($address->city ?? '')),
        ]);

        return implode("\n", $lines);
    }

    public static function makeItems($details)
    {
        $items = [];

        foreach ($details as $detail) {
            $items[] = InvoiceItem::make($detail->name)
                ->pricePerUnit($detail->price)
                ->taxByPercent($detail->vat)
                ->quantity($detail->quantity);
        }

        return $items;
    }
}
