<?php

namespace App\Jobs\Dashboard\Product;

use App\Models\Product;
use App\Models\Screen;
use Carbon\Carbon;
use App\Api\ImageResize;
use App\Http\Requests\Dashboard\Product\Store as StoreRequest;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Storage;

class Child
{
    protected $request;
    protected $image;
    protected $product;
    protected $size;

    /**
     * Child constructor.
     * @param StoreRequest $request
     * @param Product $product
     */
    public function __construct(StoreRequest $request, Product $product)
    {
        $this->request = $request;
        $this->product = $product;
        $this->image = new ImageResize();
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        foreach ($this->request->colors as $color) {
            $color_id = $color['color_id'] == "null" ? null : $color['color_id'];
            $sizes = !empty($color['sizes']) ? $color['sizes'] : null;

            $child = Product::create([
                'color_id' => $color_id,
                'sizes' => $sizes,
                'article_number' => $color['article_number'],
                'child_id' => $this->product->id,
                'published' => $this->product->published,
                'available' => true
            ]);

            if (!empty($color['screens'])) {
                foreach ($color['screens'] as $screen) {
                    $folder = Carbon::now()->format('Y/m/d');

                    $path = $screen['image']->store($screen['image']);

                    $thumbPath = $this->storeImageToS3($screen['image']);

                    Screen::create([
                        'path' => $path,
                        'path_thumb' => $thumbPath,
                        'name' => basename($path),
                        'product_id' => $child->id,
                        'size' => $this->size
                    ]);
                }
            }
        }
    }

    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, 'screens');

            $this->size = filesize(public_path($path));

            // 2 - upload local $path to s3
            // Store the image on S3
            if (in_array(env('FILESYSTEM_DISK'), ['s3', 'minio'])) {
                Storage::disk('s3')->put($path, file_get_contents(public_path($path)));
                unlink($path);
            }
        }

        return $path;
    }
}
