<?php

namespace App\Http\Controllers;

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

class ExportController extends Controller
{
    public function export_docx(Request $request){
        $ids = json_decode($request->ids,true);

        $filename = 'Наш_Двор_' . date('YmdHis') . '.docx';
        $connection = (count($ids) > 200) ? 'database' : 'sync';

        if(isset($request->separate_docs) && ($request->separate_docs == 'yes')){
            GenerateSeparateDocxJob::dispatch($ids, $request->descr, $filename, $request->template)->onConnection($connection);
            $filename = Str::replace('.docx', '.zip', $filename);
        } else {
            GenerateDocxJob::dispatch($ids, $request->descr, $filename, $request->template)->onConnection($connection);
        }

        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);
            if($data['percent'] < 0) $data['percent'] = 0;
        } 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);
    }
}
