<?php

namespace App\Http\Requests\Dashboard\Product;

use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;

use App\Api\ImageResize;
use App\Models\Product;
use Illuminate\Support\Facades\Storage;

class Update extends FormRequest
{
    public function rules()
    {
        if ($this->isMethod('get')) {
            return [];
        }

        return [
            'name' => 'array',
            'name.*' => 'required',
            'body' => 'array',
            'body.*' => 'required',
            'short_body' => 'array',
            'short_body.*' => 'required|max:300',
            'price' => 'required|numeric',
            'price_discount' => 'nullable',
            'brand_id' => 'required',
            'category_id' => 'required',
            'popular' => 'nullable',
            "calc" => [],
            'leader_of_sales' => 'nullable',
            'article_number' => 'required|unique:products,article_number,' . $this->product->id . ',id,deleted_at,NULL'
        ];
    }

    protected function getValidatorInstance()
    {
        $validator = parent::getValidatorInstance();

        if ($this->isMethod('post')) {

            $validator->sometimes('price', 'gt:price_discount', function ($input) {
                return $input->price_discount > 0;
            });
        }

        return $validator;
    }

    /**
     * @return mixed
     */
    public function getColors()
    {
        return $this->get('colors');
    }

    /**
     * @return string
     */
    public function getPoster(Product $product): string
    {
        if ($this->hasFile('poster')) {
            if (env('FILESYSTEM_DISK') == 's3') {
                // delete old file from s3
                Storage::disk('s3')->delete($product->poster);
            } else {
                // delete old file
                unlink($product->poster);
            }

            $folder = "uploads/posters/" . Carbon::now()->format('Y/m/d');
            return (string) $this->file('poster')->store($folder);
        }

        return $product->poster;
    }

    /**
     * @return string
     */
    public function getCalc(Product $product): string|null
    {
        if ($this->hasFile('calc')) {
            if (env('FILESYSTEM_DISK') == 's3' and $product->calc) {
                // delete old file from s3
                Storage::disk('s3')->delete($product->calc);
            } elseif($product->calc) {
                unlink($product->calc);
            }

            $folder = "uploads/calc/" . Carbon::now()->format('Y/m/d');
            return (string) $this->file('calc')->store($folder);
        }
        return $product->calc;
    }

    public function getDataSheet(Product $product)
    {
        if ($this->hasFile('data_sheet')) {

            if (is_file($this->get('data_sheet'))) {
                unlink($this->get("data_sheet"));
            }

            $folder = "uploads/datasheet/" . Carbon::now()->format('Y/m/d');
            return (string) $this->file('data_sheet')->store($folder);
        }

        return $product->data_sheet;
    }

    /**
     * @return string
     */
    public function getPosterThumb(Product $product): string
    {
        if ($this->hasFile('poster')) {
            if (env('FILESYSTEM_DISK') == 's3') {
                // delete old file from s3
                Storage::disk('s3')->delete($product->poster_thumb);
            } else {
                // delete old file
                unlink($product->poster_thumb);
            }

            $url = $this->storeImageToS3($this->file('poster'));
            return $url;
        }

        return $product->poster_thumb;
    }

    private function storeImageToS3($image): string
    {
        $path = '';

        // first store temp file and resize it, then upload to s3
        // 1 - store temp file
        $tempPath = $image->store('temp', 'public');
        if ($tempPath) {
            //$tempFilePath = storage_path('app/public/' . $tempPath);
	    
            $image = new ImageResize();
            $path = $image->resize($tempPath, 322, 'posters');

            // 2 - upload to s3 or keep local
            if (in_array(env('FILESYSTEM_DISK'), ['s3', 'minio'])) {
                Storage::disk('s3')->put($path, file_get_contents($path));
                unlink($path);
            }
        }

        return $path;
    }

    /**
     * @return array
     */
    public function getName(): array
    {
        return $this->get('name');
    }

    /**
     * @return array
     */
    public function getBody(): array
    {
        return $this->get('body');
    }


    public function getPrice()
    {
        return $this->get('price');
    }


    public function getPriceDiscount()
    {
        if ($this->get('price_discount')) {
            return $this->get('price_discount');
        }

        return 0;
    }

    /**
     * @return int
     */
    public function getCategoryID()
    {
        return $this->get('category_id');
    }

    /**
     * @return string
     */
    public function getSlug(): string
    {
        if ($this->get('slug')) {
            return (string) str_slug($this->get('slug'));
        }

        return (string) str_slug($this->get('name')['ru']);
    }

    /**
     * @return bool
     */
    public function getPublished()
    {
        if ($this->get('published') == 'true') {
            return true;
        }

        return false;
    }

    /**
     * @return bool
     */
    public function getAvailable()
    {
        if ($this->get('available') == 'true') {
            return true;
        }

        return false;
    }

    /**
     * @return int|null
     */
    public function getBrandID()
    {
        if ($this->get('brand_id') != 0) {
            return (int) $this->get('brand_id');
        }

        return null;
    }

    /**
     * @return int|null
     */
    public function getMeasurementId()
    {
        if ($this->get('measurement_id') != 0) {
            return (int) $this->get('measurement_id');
        }

        return null;
    }

    public function getPopular(): bool
    {
        return $this->get('popular');
    }

    public function getLeaderOfSales(): bool
    {
        if ($this->has('leader_of_sales')) {
            if ($this->get('leader_of_sales') == 'true') {
                return true;
            }
        }

        return false;
    }
}
