<?php

namespace App\Http\Controllers\Traits;

use App\Helpers\ImageSize;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

trait FileUploadTrait
{
    /**
     * File upload trait used in controllers to upload files
     * @param Request $request
     * @param null $parameters
     * @return Request
     */
    public function saveFiles(Request $request, $parameters = null)
    {
        $uploadDirectory = env('UPLOAD_PATH', 'uploads');
        $uploadPath = public_path($uploadDirectory);
        $thumbPath = public_path($uploadDirectory . '/thumb');
        $twoOnTwo = public_path($uploadDirectory . '/image_200_200');

        if (isset($parameters['developer'])) {
            $developerLogo = public_path($uploadDirectory . '/' . ImageSize::DEVELOPER_LOGO);
            $developerLogoWEBP = public_path($uploadDirectory . '/' . ImageSize::DEVELOPER_LOGO_WEBP);
            $developerBanner = public_path($uploadDirectory . '/' . ImageSize::DEVELOPER_BANNER);
            $developerBannerWEBP = public_path($uploadDirectory . '/' . ImageSize::DEVELOPER_BANNER_WEBP);
        }
        if (isset($parameters[ImageSize::PROMOTION])) {
            $promotionLogo = public_path($uploadDirectory . '/' . ImageSize::PROMOTION);
            $promotionLogoWEBP = public_path($uploadDirectory . '/' . ImageSize::PROMOTION_WEBP);
        }
        if (isset($parameters[ImageSize::SECRET_BUYER])) {
            $secretBuyer = public_path($uploadDirectory . '/' . ImageSize::SECRET_BUYER);
            $secretBuyerWEBP = public_path($uploadDirectory . '/' . ImageSize::SECRET_BUYER_WEBP);
            $secretBuyerThumb = public_path($uploadDirectory . '/' . ImageSize::SECRET_BUYER_THUMB);
        }
        if (isset($parameters[ImageSize::PLANNING])) {
            $planning = public_path($uploadDirectory . '/' . ImageSize::PLANNING);
            $planningFull = public_path($uploadDirectory . '/' . ImageSize::PLANNING_FULL);
            $planningWEBP = public_path($uploadDirectory . '/' . ImageSize::PLANNING_WEBP);
            $planningFullWEBP = public_path($uploadDirectory . '/' . ImageSize::PLANNING_FULL_WEBP);
        }
        if (isset($parameters[ImageSize::BANK])) {
            $bank = public_path($uploadDirectory . '/' . ImageSize::BANK);
            $bankWEBP = public_path($uploadDirectory . '/' . ImageSize::BANK_WEBP);
        }
        if (isset($parameters[ImageSize::BANNER])) {
            $banner = public_path($uploadDirectory . '/' . ImageSize::BANNER);
            $bannerWEBP = public_path($uploadDirectory . '/' . ImageSize::BANNER_WEBP);
        }

        if (isset($parameters[ImageSize::BANNER])) {
            $banner = public_path($uploadDirectory . '/' . ImageSize::BANNER);
            $bannerWEBP = public_path($uploadDirectory . '/' . ImageSize::BANNER_WEBP);
        }

        if (isset($parameters[ImageSize::MARKER_TYPE])) {
            $markerType = public_path($uploadDirectory . '/' . ImageSize::MARKER_TYPE);
        }
        if (isset($parameters[ImageSize::ICON])) {
            $icon = public_path($uploadDirectory . '/' . ImageSize::ICON);
        }
        if (isset($parameters[ImageSize::PRESENTATION])) {
            $presentation = public_path($uploadDirectory . '/' . ImageSize::PRESENTATION);
        }

        if (!file_exists($uploadPath)) {
            mkdir($uploadPath, 0775);
            mkdir($thumbPath, 0775);
        }
        $finalRequest = $request;
        foreach ($request->all() as $key => $value) {
            if ($request->hasFile($key)) {
                if ($request->has($key . '_max_width') && $request->has($key . '_max_height')) {
                    // Check file width
                    $fileExtention = $request->file($key)->clientExtension();
                    if ($fileExtention != "svg") {
                        $filename = time() . '-' . $request->file($key)->getClientOriginalName();
                        $file = $request->file($key);
                        $image = Image::make($file);
                        $width = $image->width();
                        $height = $image->height();

                        if (!file_exists($thumbPath)) {
                            mkdir($thumbPath, 0775, true);
                        }
                        if (!file_exists($twoOnTwo)) {
                            mkdir($twoOnTwo, 0775, true);
                        }
                        if (isset($developerLogoWEBP) && !file_exists($developerLogoWEBP)) {
                            mkdir($developerLogoWEBP, 0775, true);
                        }
                        if (isset($developerLogo) && !file_exists($developerLogo)) {
                            mkdir($developerLogo, 0775, true);
                        }
                        if (isset($developerBanner) && !file_exists($developerBanner)) {
                            mkdir($developerBanner, 0775, true);
                        }
                        if (isset($developerBannerWEBP) && !file_exists($developerBannerWEBP)) {
                            mkdir($developerBannerWEBP, 0775, true);
                        }
                        if ((isset($promotionLogo) || isset($promotionLogoWEBP)) && (!file_exists($promotionLogo) || !file_exists($promotionLogoWEBP))) {
                            mkdir($promotionLogo, 0775, true);
                            mkdir($promotionLogoWEBP, 0775, true);
                        }
                        if ((isset($planning) || isset($planningWEBP)) && (!file_exists($planning) || !file_exists($planningWEBP))) {
                            mkdir($planning, 0775, true);
                            mkdir($planningWEBP, 0775, true);

                            mkdir($planningFull, 0775, true);
                            mkdir($planningFullWEBP, 0775, true);
                        }
                        if ((isset($bank) || isset($bankWEBP)) && (!file_exists($bank) || !file_exists($bankWEBP))) {
                            mkdir($bank, 0775, true);
                            mkdir($bankWEBP, 0775, true);
                        }
                        if ((isset($banner) || isset($bannerWEBP)) && (!file_exists($banner) || !file_exists($bannerWEBP))) {
                            mkdir($banner, 0775, true);
                            mkdir($bannerWEBP, 0775, true);
                        }

                        if ((isset($secretBuyer) || isset($secretBuyerWEBP))
                            && (!file_exists($secretBuyer) || !file_exists($secretBuyerWEBP))) {
                            mkdir($secretBuyer, 0775, true);
                            mkdir($secretBuyerThumb, 0775, true);
                            mkdir($secretBuyerWEBP, 0775, true);
                        }

                        if ((isset($markerType) && !file_exists($markerType))) {
                            mkdir($markerType, 0775, true);
                        }
                        if ((isset($icon) && !file_exists($icon))) {
                            mkdir($icon, 0775, true);
                        }
                        if (isset($parameters['developer'])) {
                            if ($key == 'logotype_icon') {
                                if ($width > 191 && $height > 155) {
                                    Image::make($file)->resize(191, 155)->save($developerLogo . '/' . $filename);
                                    $webp = Image::make($file)->encode('webp')->resize(191,
                                        155)->save($developerLogoWEBP . '/' . $filename . '.webp');
                                } else {
                                    Image::make($file)->save($developerLogo . '/' . $filename);
                                    $webp = Image::make($file)->encode('webp');
                                    $webp->save($developerLogoWEBP . '/' . $filename . '.webp');
                                }
                            } elseif ($key == 'banner') {
                                Image::make($file)->resize(1920, 607)->save($developerBanner . '/' . $filename);
                                $webp = Image::make($file)->encode('webp');
                                $webp->save($developerBannerWEBP . '/' . $filename . '.webp');
                            }
                        }
                        if (isset($parameters['promotion'])) {
                            Image::make($file)->resize(555, 428)->save($promotionLogo . '/' . $filename);
                            Image::make($file)->encode('webp')->resize(555,
                                428)->save($promotionLogoWEBP . '/' . $filename . '.webp');
                        }
                        if (isset($parameters['planning'])) {
                            $needWidth = ImageSize::PLANING_SIZE_BIG[0];
                            $needHeight = ImageSize::PLANING_SIZE_BIG[1];
                            $size = $this->imagePlanningSize($file, $needWidth, $needHeight);

                            Image::make($file)->resize($size[0], $size[1])->save($planning . '/' . $filename);
                            Image::make($file)->encode('webp')->resize($size[0], $size[1])->save($planningWEBP . '/' . $filename . '.webp');

                            Image::make($file)->save($planningFull . '/' . $filename);
                            Image::make($file)->encode('webp')->save($planningFullWEBP . '/' . $filename . '.webp');
                        }
                        if (isset($parameters['bank'])) {
                            Image::make($file)->resize(159, 159, function ($constraint) {
                                $constraint->aspectRatio();
                            })->save($bank . '/' . $filename);
                            Image::make($file)->encode('webp')->resize(159, 159, function ($constraint) {
                                $constraint->aspectRatio();
                            })->save($bankWEBP . '/' . $filename . '.webp');
                        }
                        if (isset($parameters['banner'])) {
                            Image::make($file)->save($banner . '/' . $filename);
                            Image::make($file)->encode('webp')->save($bannerWEBP . '/' . $filename . '.webp');
                        }
                        if (isset($parameters[ImageSize::SECRET_BUYER])) {
                            $needWidth = ImageSize::SECRET_BUYER_SIZE[0];
                            $needHeight = ImageSize::SECRET_BUYER_SIZE[1];
                            $size = $this->imagePlanningSize($file, $needWidth, $needHeight);

                            Image::make($file)
                                ->resize($size[0], $size[1])->save($secretBuyer . '/' . $filename);
                            Image::make($file)
                                ->resize($size[0], $size[1])->encode('webp')->save($secretBuyerWEBP . '/' . $filename . '.webp');
                            // resize 100 on 100
                            Image::make($file)->resize(100, 100)->save($secretBuyerThumb . '/' . $filename);
                        }
                        if (isset($parameters[ImageSize::MARKER_TYPE])) {
                            Image::make($file)->save($markerType . '/' . $filename);
                        }
                        if (isset($parameters[ImageSize::ICON])) {
                            Image::make($file)->save($icon . '/' . $filename);
                        }

                        if (!isset($parameters[ImageSize::MARKER_TYPE]) ||
                            !isset($parameters[ImageSize::SECRET_BUYER]) ||
                            !isset($parameters[ImageSize::PLANNING])) {
                            // resize 100 on 100
                            Image::make($file)->resize(100, 100)->save($thumbPath . '/' . $filename);
                            // resize 166 on 200
                            Image::make($file)->resize(166, 200)->save($twoOnTwo . '/' . $filename);
                        }

                        if ($width > $request->{$key . '_max_width'} && $height > $request->{$key . '_max_height'}) {
                            $image->resize($request->{$key . '_max_width'}, $request->{$key . '_max_height'});
                        } elseif ($width > $request->{$key . '_max_width'}) {
                            $image->resize($request->{$key . '_max_width'}, null, function ($constraint) {
                                $constraint->aspectRatio();
                            });
                        } elseif ($height > $request->{$key . '_max_height'}) {
                            $image->resize(null, $request->{$key . '_max_height'}, function ($constraint) {
                                $constraint->aspectRatio();
                            });
                        }

                        if (!isset($parameters[ImageSize::MARKER_TYPE]) ||
                            !isset($parameters[ImageSize::SECRET_BUYER]) ||
                            !isset($parameters[ImageSize::PLANNING])) {
                            $image->save($uploadPath . '/' . $filename);
                        }

                    } elseif ($fileExtention == "svg") {
                        $filename = time() . '-' . $request->file($key)->getClientOriginalName();
                        $file = $request->file($key);
                        if (isset($parameters[ImageSize::MARKER_TYPE])) {
                            $mainDirectory = $markerType . '/';
                            $file->move($mainDirectory, $filename);
                            if (file_exists($mainDirectory . $filename)) {
                                copy($mainDirectory . $filename, $thumbPath . '/' . $filename);
                                copy($mainDirectory . $filename, $uploadPath . '/' . $filename);
                            }
                        }
                        if (isset($parameters[ImageSize::ICON])) {
                            $mainDirectory = $icon . '/';
                            $file->move($mainDirectory, $filename);
                            if (file_exists($mainDirectory . $filename)) {
                                copy($mainDirectory . $filename, $thumbPath . '/' . $filename);
                                copy($mainDirectory . $filename, $uploadPath . '/' . $filename);
                            }
                        }
                    }

                    $finalRequest = new Request(array_merge($finalRequest->all(), [$key => $filename]));
                } else {
                    $filename = time() . '-' . $request->file($key)->getClientOriginalName();

                    if (isset($parameters[ImageSize::PRESENTATION])) {
                        $request->file($key)->move($presentation, $filename);
                    } else {
                        $request->file($key)->move($uploadPath, $filename);
                    }

                    $finalRequest = new Request(array_merge($finalRequest->all(), [$key => $filename]));
                }
            }
        }

        return $finalRequest;
    }

    public function imagePlanningSize($file, $needWidth, $needHeight)
    {
        $image = Image::make($file);

        $imageHeight = $image->height();
        $imageWidth = $image->width();
        $imageAspectRatio = $imageHeight / $imageWidth;


        $needAspectRatio = $needHeight / $needWidth;

        if ($needAspectRatio > $imageAspectRatio) {
            $widthAspectRatio = $needWidth;
            $heightAspectRatio = $imageHeight * $needWidth / $imageWidth;
        } else {
            $widthAspectRatio = $imageWidth * $needWidth / $imageHeight;
            $heightAspectRatio = $needHeight;
        }

        return [$widthAspectRatio, $heightAspectRatio];
    }
}
