<?php

namespace App\Filament\Resources\PaymentOrder\PaymentOrders\Actions;

use App\Modules\Makeable;
use App\Modules\PaymentOrder\Models\PaymentOrder;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpWord\TemplateProcessor;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ExportToWord
{
    use Makeable;

    /**
     * Export to ms-word
     */
    public function __construct(protected PaymentOrder $record, protected string $filepath = '')
    {
        // ...
    }

    /**
     * Export to ms-word
     */
    public function handle(): self
    {
        Carbon::setLocale('tk');

        $date_written_turkmen = sprintf(
            '%s -nji(y) ýylyň %s aýynyň %s',
            $this->record->created_at->year,
            Str::lower($this->record->created_at->translatedFormat('F')),
            $this->record->created_at->format('d')
        );

        $templateProcessor = new TemplateProcessor(modules_path('PaymentOrder/Resources/Docs/orders.docx'));
        $templateProcessor->setValues([
            'n' => $this->record->number,

            // Dates...
            'date_written_turkmen' => $date_written_turkmen,
            'p_date' => $this->record->created_at->format('Y-m-d'),

            // Money...
            'money_amount' => number_format(floatval($this->record->money_amount), 2, '-', ''),
            'money_in_letter' => ucfirst(moneyFormatInTurkmenLetter($this->record->money_amount)),

            // Bank topary...
            'b_nm' => $this->record->bank_code,

            // Sebäbi...
            'p_reason_n' => $this->record->payment_reason_number,
            'p_reason' => $this->record->payment_reason_description,

            // Töleýji...
            't_name' => $this->record->t_name,
            't_ssb' => $this->record->t_ssb,
            't_bab' => $this->record->t_bab,
            't_bank' => $this->record->t_bank,
            't_hb_1' => $this->record->t_hb_1,
            't_hb_2' => $this->record->t_hb_2,

            // Alyjy...
            'a_name' => $this->record->a_name,
            'a_ssb' => $this->record->a_ssb,
            'a_bab' => $this->record->a_bab,
            'a_bank' => $this->record->a_bank,
            'a_hb_1' => $this->record->a_hb_1,
            'a_hb_2' => $this->record->a_hb_2,
        ]);

        $this->filepath = storage_path('app/private/payment-order.docx');
        $templateProcessor->saveAs($this->filepath);

        return $this;
    }

    /**
     * Return the file path
     */
    public function filePath(): string
    {
        return $this->filepath;
    }

    /**
     * Force browser to download file
     */
    public function download(): StreamedResponse
    {
        /** @var Storage $storage */
        $storage = Storage::disk('private');

        return $storage->download('payment-order.docx');
    }
}
