<?php

namespace App\Nova\Resources\Ecommerce\Product\Order\Actions;

use App\Models\Ecommerce\Product\Order\Order;
use App\Models\Ecommerce\Product\Order\Shipping\OrderShipping;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Actions\ActionResponse;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use PhpOffice\PhpWord\TemplateProcessor;

class ExportOrderInvoiceAction extends Action
{
    use InteractsWithQueue, Queueable;

    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public function name(): string
    {
        return __('Invoice');
    }

    /**
     * Perform the action on the given models.
     */
    public function handle(ActionFields $fields, Collection $models): mixed
    {
        if ($models->count() !== 1) {
            return Action::danger(
                __('Please run this on only one user resource')
            );
        }

        $order = $models->first();
        $products = $order
            ->items()
            ->with(['channel', 'product'])
            ->get();

        $documentPath = $this->generateDocument(
            order: $order,
            products: $products,
            templatePath: resource_path('docs/order/invoice.docx'),
            productsTotal: $products->sum('total')
        );

        return ActionResponse::download(
            name: sprintf('sargyt-%s.docx', $order->id),
            url: url($documentPath)
        );
    }

    private function generateDocument(
        Order $order,
        Collection $products,
        string $templatePath,
        float $productsTotal
    ): string {
        $templateProcessor = new TemplateProcessor($templatePath);

        $templateProcessor->setValues([
            'id' => $order->id,
            'payment_type' => $order->formattedPaymentType(),
            'created_at' => $order->created_at->format('H:i, d.m.Y'),
            'order_shipping_method' => $order->formattedShippingMethod(),

            'shipping_price' => $order->shipping_method === OrderShipping::SELF_PICKUP
                    ? 'Özüm baryp aljak'
                    : (string) $order->shippingPrice().' TMT',

            'order_name' => $order->customer_name,
            'order_address' => $order->fullAddress(),
            'order_phone' => $order->customer_phone,
            'p_t' => $productsTotal,
            't' => $productsTotal + $order->shippingPrice(),
            'notes' => $order->notes,
            'adt_tax' => $order->additional_tax ?: '0.0',
        ]);

        $table = $this->generateTable($products);
        $templateProcessor->setComplexBlock('products_table', $table);

        $documentPath = public_path(
            sprintf('app-docs/sargyt-%s.docx', $order->id)
        );
        $templateProcessor->saveAs($documentPath);

        return sprintf('app-docs/sargyt-%s.docx', $order->id);
    }

    private function generateTable(Collection $products): Table
    {
        $table = new Table([
            'borderSize' => 2,
            'borderColor' => 'black',
            'width' => 5000,
            'unit' => TblWidth::PERCENT,
        ]);

        $table->addRow();
        $table->addCell()->addText('№');
        $table->addCell()->addText('HARYDYŇ ADY');
        $table->addCell()->addText('BAHASY');
        $table->addCell()->addText('SATYJY');
        $table->addCell()->addText('MUKDARY');
        $table->addCell()->addText('ARZANLADYŞ');
        $table->addCell()->addText('JEMI BAHASY');

        $products->each(function ($product, $index) use ($table) {
            $table->addRow();
            $table->addCell()->addText($index + 1);
            $table->addCell()->addText($product->product->name);
            $table->addCell()->addText($product->unit_price_amount);
            $table
                ->addCell()
                ->addText($product->channel?->name ?? 'Türkmenpoçta PAK');
            $table->addCell()->addText($product->quantity);
            $table
                ->addCell()
                ->addText(
                    $product->product->caluculateDiscountDifference(
                        $product->unit_price_amount
                    )
                );
            $table
                ->addCell()
                ->addText($product->quantity * $product->unit_price_amount);
        });

        return $table;
    }

    /**
     * Get the fields available on the action.
     */
    public function fields(NovaRequest $request): array
    {
        return [];
    }
}
