<?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 PhpOffice\PhpWord\TemplateProcessor;

class GenerateDocxJob 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()
    {
        $products = Product::query()->whereIn('id', $this->ids)->orderBy('series', 'asc')->get();
        $tmpfile = public_path('exported/docx/' . $this->filename . '.txt');

        $vars_for_template = [];
        $i = 1;
        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 = array_merge($vars_for_template, [
                'series#' . $i        => $product->series,
                'product_group#' .$i  => $product->product_group,
                'num#' . $i           => $i,
                'name#' . $i          => $product->name,
                'name_for_form#' . $i          => $product->name_for_form,
                'price#' . $i         => number_format($product->price, 2, '.', ' '),
                'image#' . $i         => $product->image_path,
                'description#' . $i   => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
            ]);

            // remove last page break
            if($i < $products->count()) {
                $vars_for_template['page_br#' . $i] = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>';
            } else {
                $vars_for_template['page_br#' . $i] = '';
            }
            $i++;
        }


        $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
        $my_template->cloneBlock('product_block', $products->count(), true, true, $vars_for_template);

        $i = 0;
        $total = count($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]);
            } else {
                $my_template->setValue($k, $v);
            }

            if(($i++ % 50) == 0) {
                $f = fopen($tmpfile, 'w+');
                $percent = round(($i - 2) / ($total / 100), 0);
                fwrite($f, $percent);
                fclose($f);
            }
        }

        $my_template->saveAs(public_path('exported/docx/') . $this->filename);
        unlink($tmpfile);
        Log::notice('Generation finished: ' . $i . ' / ' . $total . '  Execution time: ' . microtime(true) - LARAVEL_START);
    }
}
