<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ResizeFloorImage extends Command
{
    protected $signature = 'resize:floorimg';

    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        $company = [4];
        foreach ($company as $com){
            $files = Storage::disk('public')->files('company_'.$com.'/floor');
            foreach ($files as $file){
                $fileNames = explode('/', $file);
                $fileName = $fileNames[count($fileNames) - 1];
                try {
                    if (str_contains($file, 'floor_image2')){
                        $this->resizeVerticalFloor(file_get_contents(storage_path('app/public/'.$file)), $fileName, $com);
                    }else {
                        $this->resizeHorizontalFloor(file_get_contents(storage_path('app/public/'.$file)), $fileName, $com);
                    }
                }catch (\Exception $exception){
                    Log::debug($exception->getMessage());
                }
            }
        }
    }

    public function resize($image, $width, $path){
        $newImage = \Image::make($image);
        //$newImage->orientate();
        //$newImage->resize($width, $height)->save($path);
        $newImage->resize($width, null, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })->save($path);
    }

    public function resizeVerticalFloor($image, $fileName, $company_id){
        $folder = storage_path('app/public/company_'.$company_id.'/floor');
        $this->checkDirExists($company_id);
        $this->resize($image, 800, $folder.'/800/'. $fileName);
        $this->resize($image, 350, $folder.'/350/'. $fileName);
    }

    public function checkDirExists($company_id){
        if(!Storage::exists('public/company_'.$company_id.'/floor/1200')){
            Storage::makeDirectory('public/company_'.$company_id.'/floor/1200');
        }
        if(!Storage::exists('public/company_'.$company_id.'/floor/800')){
            Storage::makeDirectory('public/company_'.$company_id.'/floor/800');
        }
        if(!Storage::exists('public/company_'.$company_id.'/floor/350')){
            Storage::makeDirectory('public/company_'.$company_id.'/floor/350');
        }
    }

    public function resizeHorizontalFloor($image, $fileName, $company_id){
        $folder = storage_path('app/public/company_'.$company_id.'/floor');
        $this->checkDirExists($company_id);
        $this->resize($image, 1200, $folder.'/1200/'. $fileName);
        $this->resize($image, 800, $folder.'/800/'. $fileName);
        $this->resize($image, 350, $folder.'/350/'. $fileName);
    }
}
