<?php

namespace App\Http\Controllers;

use App\Jobs\GenerateDocxJob;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ExportController extends Controller
{
    public function export_docx(Request $request){
        $ids = json_decode($request->ids,true);
        $products = Product::query()->whereIn('id', $ids)->orderBy('series', 'asc')->get();

        $vars_for_template = [];
        $i = 1;
        foreach ($products as $product){
            switch ($request->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),
            ]);
            $i++;
        }

        // prepared vars - run job


        $filename = 'Наш_Двор_' . date('YmdHis') . '.docx';
        if($products->count() > 200){
            GenerateDocxJob::dispatch($vars_for_template, count($products), $filename, $request->template)->onConnection('database');
        } else {
            GenerateDocxJob::dispatch($vars_for_template, count($products), $filename, $request->template)->onConnection('sync');
        }


        Log::notice('Created export job. Execution time: ' . microtime(true) - LARAVEL_START);

        $data['filename'] = $filename;
        return redirect()->route('wait_export', $data);

    }

    public function wait_export(Request $request, $filename){
        $fn = public_path('exported/docx/' . $filename . '.txt');
        if(file_exists($fn)){
            $data['percent'] = file_get_contents($fn);
        } else {
            $data['percent'] = 0;
        }

        $fn = public_path('exported/docx/' . $filename);
        if(file_exists($fn)) {
            $data['percent'] = 100;
        }

        $data['filename'] = $filename;

        return view('products.wait', $data);
    }
}
