<?php

namespace App\Jobs;

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 $vars;
    protected $prod_count;
    protected $filename;
    protected $template;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($vars, $count_products, $filename, $template)
    {
        $this->vars =$vars;
        $this->prod_count = $count_products;
        $this->filename = $filename;
        $this->template = $template;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tmpfile = public_path('exported/docx/' . $this->filename . '.txt');
        $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
        $my_template->cloneBlock('product_block', $this->prod_count, true, true, $this->vars);

        $i = 0;
        $total = count($this->vars);

        foreach ($this->vars 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 / ($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);
    }
}
