<?php

namespace App\Modules\CardRequisite\Repositories;

use App\Modules\Card\Models\Card;
use App\Modules\CardTransaction\Repositories\CardTransactionRepository;
use App\Modules\Makeable;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpWord\TemplateProcessor;

class CardRequisiteRepository
{
    use Makeable;

    /**
     * Download card requisite
     */
    public function downloadCardRequisite(Card $record): ?\Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        /** @var \App\Modules\CardTransaction\Types\CardTransactionResponse */
        $response = $this->fetchApi($record);

        if ($response->errCode != 0) {
            Notification::make()
                ->danger()
                ->title($response->message)
                ->send();

            return null;
        }

        $path = $this->generateFile($record, $response);

        return response()->download($path);
    }

    /**
     * Fetch api
     */
    public function fetchApi(Card $record): object
    {
        $date = today()->format('d.m.Y');

        $response = CardTransactionRepository::make()->fetchApi(
            passport_serie: user()->passport_serie(),
            passport_id: user()->passport_id(),
            card_number_masked: Str::mask($record->number, '*', 6, 6),
            card_expire_date: $record->month.'/'.substr($record->year, 2),
            start_date: $date,
            end_date: $date,
        );

        /** @var \App\Modules\CardTransaction\Types\CardTransactionResponse */
        $response = Str::isJson($response)
            ? json_decode($response)
            : emptyClass(errCode: 1, message: 'Connection issue to VP');

        return $response;
    }

    /**
     * Generate file
     *
     * @param  \App\Modules\CardTransaction\Types\CardTransactionResponse  $response
     * @return string
     */
    public function generateFile(Card $model, object $response)
    {
        $doc_path = modules_path('CardRequisite/Resources/Docs/card-requisite.docx');

        $templateProcessor = new TemplateProcessor($doc_path);
        $templateProcessor->setValues([
            'year' => date('Y'),
            'name' => $response->clientName,
            'contract' => $response->cardAccountNumber,
            'bank' => $response->depName,
            'hasap' => $response->accountNumber,
            'sb' => $response->inn,
            'bab' => $response->mfo,
            'card_type' => $response->cardName,
            'card_number' => $response->cardPan,
            'phone' => $response->mobilPhone ?? '-',
            'contract_date' => '---YOK---',
            'card_order_date' => '---YOK---',
            'card_given_date' => '---YOK---',
        ]);

        $unique_folder_name = Str::snake(str_replace(':', '-', now()->toDateTimeString()));
        $dir = Storage::disk('local')->path("card-requisite/{$unique_folder_name}");

        File::makeDirectory($dir, 0777, true, true);

        $filePath = $dir."/kart-rekwizit-{$model->id}.docx";

        $templateProcessor->saveAs($filePath);

        return $filePath;
    }
}
