<?php

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

use App\Models\Ecommerce\Payouts\Payout;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;
use PhpOffice\PhpWord\SimpleType\TblWidth;

class ExportEvidenceForProducts extends Action
{
    use InteractsWithQueue, Queueable;

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

    /**
     * Perform the action on the given models.
     *
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        $payout = $models->first();
        $orderItems = $payout->orderItems;
        $channel = $payout->channel;
        $user = $channel->user;

        exec('rm -rf app-docs/*');

        $documentsPath = 'app-docs/'.Str::random();
        exec("mkdir {$documentsPath}");

        $this->generatePriceNegotiationDocument($user, $payout, $orderItems, $documentsPath);
        $this->generateEvidenceForProductsDocument($user, $payout, $orderItems, $documentsPath);

        return Action::openInNewTab(route('user.docs', ['folder' => $documentsPath]));
    }

    protected function generatePriceNegotiationDocument(User $user, Payout $payout, Collection $orderItems, string $folder): void
    {
        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(resource_path('docs/order/evidence-price-negotiation.docx'));
        $templateProcessor->setValues([
            'year' => date('Y'),
            'product_owner' => $user->companyName(),
        ]);

        $table = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 2,
            'borderColor' => 'black',
            'width' => 5000,
            'width' => 6000,
            'unit' => TblWidth::TWIP,
        ]);
        $table->addRow();
        $table->addCell()->addText('');
        $table->addCell()->addText('Harydyň ady');
        $table->addCell()->addText('Komitentiň satyş bahasy, manat');
        $table->addCell()->addText('Komissioneriň satyş bahasy, manat');

        $i = 0;
        $total_cost_amount = 0;
        $total_unit_price_amount = 0;
        foreach ($orderItems as $orderItem) {
            $i++;
            $table->addRow();

            $table->addCell()->addText($i);
            $table->addCell()->addText($orderItem->product_name);
            $table->addCell()->addText($orderItem->unit_cost_amount);
            $table->addCell()->addText($orderItem->unit_price_amount);

            $total_cost_amount += $orderItem->unit_cost_amount;
            $total_unit_price_amount += $orderItem->unit_price_amount;
        }

        $table->addRow();
        $table->addCell()->addText();
        $table->addCell()->addText('Jemi');
        $table->addCell()->addText($total_cost_amount);
        $table->addCell()->addText($total_unit_price_amount);

        $templateProcessor->setComplexBlock('products_table', $table);

        $documentPath = "{$folder}/hasaplashyk-{$payout->id}-{$user->companyName()}-baha-ylalashyk.docx";
        $templateProcessor->saveAs(public_path($documentPath));
    }

    public function generateEvidenceForProductsDocument(User $user, Payout $payout, Collection $orderItems, string $folder): void
    {
        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(resource_path('docs/order/evidence.docx'));
        $templateProcessor->setValues([
            'date' => date('Y'),
            'o_date' => $payout->created_at->format('d.m.Y'),
            'product_owner' => $user->companyName(),
        ]);

        $table = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 2,
            'borderColor' => 'black',
            'width' => 5000,
            'width' => 6000,
            'unit' => TblWidth::TWIP,
        ]);
        $table->addRow();
        $table->addCell()->addText('No');
        $table->addCell()->addText('Harydyň ady');
        $table->addCell()->addText('Mukdary, san');
        $table->addCell()->addText('Biriniň bahasy, manat');
        $table->addCell()->addText('Jemi bahasy, manat');

        $i = 0;
        $total_price = 0;
        foreach ($orderItems as $orderItem) {
            $i++;
            $table->addRow();

            $table->addCell()->addText($i);
            $table->addCell()->addText($orderItem->product_name);
            $table->addCell()->addText($orderItem->quantity);
            $table->addCell()->addText($orderItem->unit_cost_amount);
            $table->addCell()->addText($orderItem->unit_cost_amount * $orderItem->quantity);

            $total_price += $orderItem->unit_cost_amount * $orderItem->quantity;
        }

        $table->addRow();
        $table->addCell()->addText('');
        $table->addCell()->addText('Jemi');
        $table->addCell()->addText($i);
        $table->addCell()->addText();
        $table->addCell()->addText($total_price);

        $templateProcessor->setComplexBlock('products_table', $table);

        $documentPath = "{$folder}/sargyt-{$payout->id}-{$user->companyName()}-delilnama.docx";
        $templateProcessor->saveAs(public_path($documentPath));
    }

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