<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreProductRequest;
use App\Jobs\Export\ExportCatalog;
use App\Jobs\Import\ImportCatalog;
use App\Models\File;
use App\Models\Product;
use App\Services\FileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductController extends Controller
{
    protected array $data = [
        'active'    => 'catalog',
        'title'     => 'Каталог',
        'id'        => 'products',
        'header'    => [
            'image'                     => 'Картинка',
            'id'                        => 'ID',
            'article'                   => 'Артикул',
            'nomenclature_number'       => 'Номер номенклатуры',
            'manufacturer'              => 'Производитель',
            'unit'                      => 'Ед. изм.',
            'name_tz'                   => 'Наименование ТЗ',
            'type_tz'                   => 'Тип по ТЗ',
            'type'                      => 'Тип',
            'manufacturer_name'         => 'Наименование производителя',
            'sizes'                     => 'Размеры',
            'product_price_txt'         => 'Цена товара',
            'installation_price_txt'    => 'Цена установки',
            'total_price_txt'           => 'Итоговая цена',
            'note'                      => 'Примечания',
            'created_at'                => 'Дата создания',
            'certificate_id'            => 'Сертификат',
        ],
        'searchFields' =>  [
            'nomenclature_number',
            'article',
            'name_tz',
            'manufacturer_name',
            'note',
        ],
    ];

    public function index(Request $request)
    {
        $model = new Product;
        // fill filters
        $this->createFilters($model, 'type_tz', 'type', 'certificate_id');
        $this->createRangeFilters($model, 'nomenclature_number', 'product_price', 'installation_price', 'total_price');
        $this->createDateFilters($model, 'created_at');

        // create request
        $q = $model::query();

        $this->acceptFilters($q, $request);
        $this->acceptSearch($q, $request);

        $this->setSortAndOrderBy($model, $request);
        $q->orderBy($this->data['sortBy'], $this->data['orderBy']);

        $this->data['products'] = $q->paginate(session('per_page', config('pagination.per_page')))->withQueryString();
        return view('catalog.index', $this->data);
    }

    public function show(Request $request, Product $product)
    {
        $this->data['product'] = $product;
        return view('catalog.edit', $this->data);
    }

    public function create()
    {
        $this->data['product'] = null;
        return view('catalog.edit', $this->data);
    }

    public function store(StoreProductRequest $request)
    {
        Product::create($request->validated());
        return redirect()->route('catalog.index');
    }

    public function update(StoreProductRequest $request, Product $product)
    {
        $product->update($request->validated());
        return redirect()->route('catalog.index');
    }

    public function delete(Product $product)
    {
        $product->delete();
        return redirect()->route('catalog.index');
    }

    /**
     * @param Request $request
     * @return RedirectResponse
     */
    public function import(Request $request)
    {
        // validate data
        $request->validate([
            'import_file' => 'file',
        ]);

        // load and save file
        $path = Str::random(2) . '/' . Str::uuid() . '.' .$request->file('import_file')->getClientOriginalExtension();
        Storage::disk('upload')->put($path, $request->file('import_file')->getContent());

        // dispatch job
        ImportCatalog::dispatch($path, year(), $request->user()->id);
        Log::info('ImportCatalog job created!');
        return redirect()->route('catalog.index')->with(['success' => 'Задача импорта успешно создана!']);
    }

    public function export(Request $request)
    {
        $request->validate([
            'withFilter'    => 'nullable',
            'filters'       => 'nullable|array',
        ]);

        // load and save file
        $filters = ($request->withFilter) ? $request->filters ?? [] : [];

        // dispatch job
        ExportCatalog::dispatch($filters , $request->user()->id);
        Log::info('ExportCatalog job created!');


        return redirect()->route('catalog.index')->with(['success' => 'Задача экспорта успешно создана!']);
    }

    /**
     * @param Request $request
     * @return array
     */
    public function search(Request $request): array
    {
        $s = $request->get('s');
        $searchFields = $this->data['searchFields'];
        $ret = [];
        if($s) {
            $result = Product::query()->where(function ($query) use ($searchFields, $s) {
                foreach ($searchFields as $searchField) {
                    $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
                }
            });
            foreach ($result->get() as $p) {
                $ret[$p->id] = $p->common_name;
//                $ret[$p->id] = $p->name_tz . ' (арт.' . $p->article . ', №' . $p->nomenclature_number . ', ' . $p->year . 'г., ' . $p->product_price_txt . ')';
            }
        }
        return $ret;
    }

    public function uploadCertificate(Request $request, Product $product, FileService $fileService)
    {
        $data = $request->validate([
            'certificate' => 'file',
        ]);

        $f = $fileService->saveUploadedFile('products/' . $product->id . '/certificate', $data['certificate']);
        $product->update(['certificate_id' => $f->id]);
        return redirect()->route('catalog.show', $product);
    }

    public function deleteCertificate(Product $product, File $file)
    {
        $product->update(['certificate_id' => null]);
        Storage::disk('public')->delete($file->path);
        $file->delete();
        return redirect()->route('catalog.show', $product);
    }


}
