<?php

namespace App\Http\Controllers;

use App\Http\Requests\SaveProductRequest;
use App\Jobs\ImportXlsxJob;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;


class ProductController extends Controller
{
    public function index(Request $request)
    {
        $data = $request->validate([
            's' => 'nullable|string',
            's_series' => 'nullable|string',
            's_price_min' => 'nullable|integer',
            's_price_max' => 'nullable|integer',
            'perpage' => 'nullable|string',
        ]);

        $query = Product::query();
        if (!empty($data['s'])) {
            $query->whereRaw(" (`article` LIKE '%{$data['s']}%' OR `name` LIKE '%{$data['s']}%' OR
                    `name_for_form` LIKE '%{$data['s']}%' OR `product_group` LIKE '%{$data['s']}%' OR
                    `characteristics` LIKE '%{$data['s']}%' OR `tech_description` LIKE '%{$data['s']}%'
                    OR `tech_description_short` LIKE '%{$data['s']}%') ");
        }

        if (!empty($data['s_series'])) {
            $query->where('series', '=', $data['s_series']);
        }

        if (!empty($data['s_price_min'])) {
            $query->where('price', '>=', $data['s_price_min']);
        }

        if (!empty($data['s_price_max'])) {
            $query->where('price', '<=', $data['s_price_max']);
        }

        $query->orderBy('series');

        $data['products'] = $query->paginate($data['perpage'] ?? 20)->withQueryString();

        // get all series for select field
        $data['series'] = Product::query()->select('series')->distinct()->OrderBy('series')->get();
        return view('products.index', $data);
    }


    public function upload_xls(Request $request)
    {
        $file = $request->file('file');
        $path = storage_path('import');
        $filename = 'import_' . date('YmdHis') . '.' . $file->extension();
        $file->move($path, $filename);

        $info = ['count' => 0, 'updated' => 0, 'created' => 0, 'no_image' => []];
        $f = fopen(storage_path('import/') . $filename . '.txt', 'w+');
        fwrite($f, serialize($info));
        fclose($f);


        ImportXlsxJob::dispatch(storage_path('import/' . $filename));
        return redirect()->route('import_result', ['filename' => $filename]);
    }

    public function import_result(Request $request){
        $filename = $request->filename . '.txt';
        $data = unserialize(file_get_contents(storage_path('import/') . $filename));
        return view('products.import_result', $data);
    }

    private $allfiles; // remember files list

    private function find_images($article)
    {
        $path_to_files = './' . env('IMAGES_PATH', '---') . '/';
        if (!isset($this->allfiles) || empty($this->allfiles)) {
            $this->allfiles = scandir($path_to_files);
        }
        $images = [];
        foreach ($this->allfiles as $filename) {
            if ((mb_strpos($filename, $article) === 0) || (
                    mb_strpos(Str::lower($filename), Str::slug($article)) === 0))
                $images[] = $filename;
        }
        return (!empty($images)) ? $images : '';
    }

    public function product(Request $request, $id)
    {
        $data['product'] = Product::query()->findOrFail($id);
        $data['images'] = $this->find_images($data['product']->article);
        return view('products.product', $data);
    }

    public function save_product(SaveProductRequest $request)
    {
        Product::query()->where('id', $request->validated('id'))->update($request->validated());
        return redirect($request->prev_url);
    }

    public function upload_image(Request $request){
        $path = public_path() . '/' . env('IMAGES_PATH');
//        dd($path);
        $file = $request->file('filename');
        $new_filename = $request->article . '.' . date('YmdHis') . '.' . $file->extension();
        $file->move($path, $new_filename);
        Product::query()->where('article', $request->article)->update(['image_path' => $new_filename]);
        return redirect()->back();
    }

    public function update_image(Request $request, $id){
        $validated = $request->validate(['image_path' => 'required|string']);
        Product::query()->where('id', $id)->update($validated);
        return redirect()->route('view_product', $id);
    }

    public function select_export(Request $request){
        $data['ids'] = json_decode($request->ids, true);
        $data['products'] = Product::query()->whereIn('id', $data['ids'])->get();
        $data['templates'] = $this->get_templates();
        return view('products.select_export', $data);
    }

    private function get_templates(){
        $files = scandir(storage_path('templates'));
        $result = [];
        foreach ($files as $f){
            if(Str::endsWith($f, '.docx'))
                $result[] = $f;
        }
        return$result;
    }


}
