<?php

namespace App\Jobs;

use App\Models\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use PhpOffice\PhpWord\TemplateProcessor;

class GenerateSeparateDocxJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $ids;
    protected $descr;
    protected $filename;
    protected $template;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($ids, $descr, $filename, $template)
    {
        $this->ids = $ids;
        $this->descr = $descr;
        $this->filename = $filename;
        $this->template = $template;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tmpfile = public_path('exported/docx/' . Str::replace('.docx', '.zip', $this->filename) . '.txt');
        $products = Product::query()->whereIn('id', $this->ids)->orderBy('series', 'asc')->get();
        $i = 1;
        $file_for_arch = [];

        foreach ($products as $product){
            switch ($this->descr) {
                case 1:
                    $descr = $product->characteristics . "\r\n" . $product->tech_description_short;
                    break;
                case 2:
                    $descr = $product->characteristics . "\r\n" . $product->tech_description;
                    break;
                case 3:
                    $descr = $product->tech_description_short;
                    break;
                case 4:
                    $descr = $product->tech_description;
                    break;
                case 5:
                default:
                    $descr = $product->characteristics;
                    break;
            }

            $vars_for_template = [
                'series#1'              => $product->series,
                'article#1'             => $product->article,
                'product_group#1'       => $product->product_group,
                'num#1'                 => 1, // $i,
                'name#1'                => $product->name,
                'name_for_form#1'       => $product->name_for_form,
                'price#1'               => number_format($product->price, 2, '.', ' '),
                'image#1'               => $product->image_path,
                'description#1'         => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
                'page_br#1' => ''
            ];
            $article = '';
            $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
            $my_template->cloneBlock('product_block', 1, true, true, $vars_for_template);
            foreach ($vars_for_template as $k => $v) {
                $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
                if (str_starts_with($k, 'image') && file_exists($file) && $v !== '') {
                    $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
                } elseif (Str::startsWith($k, 'num')) {
                    $my_template->setValue($k, 1);
                } elseif (Str::startsWith($k, 'page_br')) {
                    $my_template->setValue($k, '');
                } elseif(Str::startsWith($k, 'article')){
                    $article = $v;
                } else {
                    $my_template->setValue($k, $v);
                }
            }

            $filename = Str::replace('Наш_Двор_', 'Наш_Двор_' . $article . '_', $this->filename);
            $filename = Str::replace('.docx', '_' . str_pad($i + 1, 4, 0, STR_PAD_LEFT) . '.docx', $filename);

            $my_template->saveAs(public_path('exported/docx/') . $filename);
            $file_for_arch[] = $filename;

            if (($i % 10) == 0) {
                $f = fopen($tmpfile, 'w+');
                $percent = round(($i - 2) / (count($this->ids) / 100), 0);
                fwrite($f, $percent);
                fclose($f);
            }
            $i++;
        }



        // creating zip file
        $zip_file = public_path('exported/docx/') . Str::replace('.docx', '.zip', $this->filename);
        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        foreach ($file_for_arch as $file_docx) {
            $zip->addFile(public_path('exported/docx/') . $file_docx, $file_docx);
        }
        $zip->close();

        foreach ($file_for_arch as $file_docx) {
            unlink(public_path('exported/docx/') . $file_docx);
        }
        unlink($tmpfile);

        Log::notice('Generation finished: ' . $i . ' / ' . count($this->ids) . '  Execution time: ' . microtime(true) - LARAVEL_START);
    }
}
