<?php

namespace App\Http\Controllers\Admin;

use App\Models\Article;
use App\Models\Facility;
use App\Models\PortalHomesPanorama;
use App\Models\PortalStatusArticle;
use App\Models\PortalSuumoTrafficMap;
use App\Models\RelationArticleFacility;
use App\Models\RelationArticlePhoto;
use Illuminate\Support\Facades\Auth;
use App\Models\RelationPortalPhoto;
use App\Models\RelationPortalFacility;
use App\Models\PortalSuumoPhoto;
use App\Models\MstPropertyType;
use App\Models\MstPropertyTypeSub;
use App\Models\MstStore;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

class PortalController extends Controller
{
    public function edit($id, Request $request)
    {
        $article = Article::findOrFail($id);
        $articlePortal = PortalStatusArticle::getDataById($article->building_id);

        if(!empty($articlePortal)){
            foreach ($articlePortal as $pp){
                if($pp->portal_type == 1){
                    $article->suumo_date = $pp->updated_at;
                }
                if($pp->portal_type == 2){
                    $article->homes_date = $pp->updated_at;
                }
                if($pp->portal_type == 3){
                    $article->athome_date = $pp->updated_at;
                }
            }
        }

        $property_name = $this->getPropertyName($article->property, $article->property_sub);
        $title = "物件登録-{$property_name}-ポータル登録「{$article->name}」";

        $data['main_title'] = $title;
        $data['article'] = $article;
        $data['portal_public'] = $article->portalPublic();

        $store = MstStore::where('code', auth()->user()->store_id)->where('company_id', auth()->user()->company_id)->first();

        $data['store'] = $store;

        $data['saved'] = 1;

        $data['back'] = route("admin.portal.image", $article->building_id);

        if(in_array($article->property, [1,2,3])) {
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
        } elseif(in_array($article->property, [4,5])) {
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);
        } else {
            $data['action'] = route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $article->building_id]);
        }

        return view("admin.pages.portal", $data);
    }

    public function update($type, $id, Request $request)
    {
        ini_set('max_execution_time', -1);
        $correctType = ["suumo", "homes", "athome"];
        $user = auth()->user();
        $isNotCorrectType = !in_array($type, $correctType);

        if ($isNotCorrectType) return back();

        $article = Article::findOrFail($id);

        $typeDate = "{$type}_date";
        if ($type == "homes") {
            $typeDate = "homes_date";
        }

        $article->update([
            "{$type}" => 2,
            "{$typeDate}" => date("Y-m-d")
        ]);

        switch ($type) {
            case "suumo":
                Artisan::call('batch:test', ['id' => $article->building_id, 'user' => $user, "type" => 2]);
                break;
            case "homes":
                Artisan::call('batch:test2', ['id' => $article->building_id, 'type' => 2, 'user' => $user]);
                break;
            case "athome":
                Artisan::call('batch:athome', ['id' => $article->building_id, 'user' => $user]);
                break;
        }

        return back();
    }

    private static function getPropertyName($property, $property_sub) {
        $res = '';
        if($property == 4 || $property == 5 ||$property == 6 ||$property == 7) {
            $res .= MstPropertyTypeSub::find($property_sub)->name??'';
        }

        if(is_null($property)) {
            $res .= 'マンション（部屋）';
        } elseif($property == 99) {
            $res .= '分譲地';
        } else {
            $res .= MstPropertyType::find($property)->name??'';
        }

        return $res;
    }
    public function editImage($id, Request $request)
    {
        $error = $request->session()->all();

        $user = auth()->user();
        $article = Article::where('company_id', $user->company_id)->where('building_id', '=', $id)->first();
        $imageFacilities = $article->facility();
        $dataImageFacilities = [];
        $data['public_portal'] = $article->portalPublic();
        $referer = $_SERVER['HTTP_REFERER'] ?? null;

        if (isset($request->referer)) {
            $referer = $request->referer;
        }

        $back = str_replace(url(''), '', $referer);

        if (strpos($referer, '/admin/registLand') !== false) {
            $back = route('showEditLand', ['id' => $request->id]);
        }
        if(isset($request->detail)){
            $property = $article->property;

            if (empty($property)) {
                $back = route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $request->id]);
            } elseif ($property < 4) {
                $back = route('showEditLand', ['id' => $request->id]);
            } elseif ($property < 6) {
                $back = route('showEditHouse', ['id' => $request->id]);
            }else{
                $back = route('showEditMansion', ['id' => $request->id]);
            }
        }else{
            $back = route('showRegistImage', $request->id);
        }
        $data['back'] = $back;

        $property_name = $this->getPropertyName($article->property, $article->property_sub);
        $title = "物件登録-{$property_name}-ポータル登録「{$article->name}」";

        $data['main_title'] = $title;
        $data['portal_suumo_image'] = RelationPortalPhoto::ofImage(null, $id, config('const.SUUMO'), null, 0)->ofOrder()->get();
        $data['portal_suumo_image_del'] = RelationPortalPhoto::ofImage(null, $id, config('const.SUUMO'), null, 1)->ofOrder()->get();
        $data['portal_suumo_facility'] = RelationPortalFacility::getImgByArticleId($id, config('const.SUUMO'), 0);
        $data['portal_suumo_facility_del'] = RelationPortalFacility::getImgByArticleId($id, config('const.SUUMO'), 1);
        $data['portal_suumo_seller'] = PortalSuumoPhoto::getImgByArticleId(1, $id);
        $data['portal_suumo_spec'] = PortalSuumoPhoto::getImgByArticleId(2, $id);
        $data['portal_suumo_construction'] = PortalSuumoPhoto::getImgByArticleId(3, $id);

        $data['portal_homes_image'] = RelationPortalPhoto::ofImage(null, $id, config('const.HOMES'), null, 0)->ofOrder()->get();
//        dd($data['portal_homes_image']->toArray());
        $data['portal_homes_panorama_default'] = PortalHomesPanorama::ofImage($id, config('const.PANORAMA_TYPE_DEFAULT'))->first();
        $data['portal_homes_panorama'] = PortalHomesPanorama::ofImage($id, config('const.PANORAMA_TYPE_IMAGE'))->ofOrder()->get();
        $data['portal_homes_panorama_del'] = PortalHomesPanorama::ofImage($id, config('const.PANORAMA_TYPE_IMAGE'), 1)->ofOrder()->get();
        $data['portal_homes_image_del'] = RelationPortalPhoto::ofImage(null, $id, config('const.HOMES'), null, 1)->ofOrder()->get();


        $data['portal_athome_image'] = RelationPortalPhoto::ofImage(null, $id, config('const.ATHOME'), null, 0)->ofOrder()->get();
        $data['portal_athome_image_del'] = RelationPortalPhoto::ofImage(null, $id, config('const.ATHOME'), null, 1)->ofOrder()->get();
        $data['portal_athome_facility'] = RelationPortalFacility::getImgByArticleId($id, config('const.ATHOME'), 0);
        $data['portal_athome_facility_del'] = RelationPortalFacility::getImgByArticleId($id, config('const.ATHOME'), 1);
        $suumo_traffic_map = PortalSuumoTrafficMap::getImgByArticleId($id)->first();

        if(!empty($suumo_traffic_map)){
            $suumo_traffic_map->file_path = json_decode($suumo_traffic_map->file_path);
        }

        $data['suumo_traffic_map'] = $suumo_traffic_map;

        $store = MstStore::where('code', auth()->user()->store_id)->where('company_id', auth()->user()->company_id)->first();

        $data['article_id'] = $id;
        $data['building_id'] = $article->id;
        $data['store'] = $store;
        $data['article'] = $article;
        $data['article_property'] = $article->property;

        $photo_facility_summo = config('const.PHOTO_FACILITY_SUUMO');
        $data['photo_facility_summo'] = $this->parseData($photo_facility_summo);

        $photo_facility_athome = config('const.PHOTO_FACILITY_ATHOME');
        $data['photo_facility_athome'] = $this->parseData($photo_facility_athome);

        $panorama_title = config('const.PANORAMA_TITLE');
        $data['panorama_title'] = $this->parseData($panorama_title);
        $panorama_reins_type = config('const.PANORAMA_REINS_TYPE');
        $data['panorama_reins_type'] = $this->parseData($panorama_reins_type);
        $panorama_public_type = config('const.PANORAMA_PUBLIC_TYPE');
        $data['panorama_public_type'] = $this->parseData($panorama_public_type);
        if (empty($article->property)) {
            $photo_property_suumo = config('const.PHOTO_PROPERTY_SUUMO_ROOM');
            $data['photo_property_suumo'] = $this->parseData($photo_property_suumo);

            $photo_property_homes = config('const.PHOTO_PROPERTY_HOMES_ROOM');
            $data['photo_property_homes'] = $this->parseData($photo_property_homes);

            $photo_property_athome = config('const.PHOTO_PROPERTY_ATHOME_ROOM');
            $data['photo_property_athome'] = $this->parseData($photo_property_athome);

            $suumo_seller_comment = config('const.SUUMO_SELLER_COMMENT_ROOM');
            $data['suumo_seller_comment'] = $this->parseData($suumo_seller_comment);

            $suumo_facility_spec = config('const.SUUMO_FACILITY_SPEC_ROOM');
            $data['suumo_facility_spec'] = $this->parseData($suumo_facility_spec);
        } elseif ($article->property < 4) {
            $photo_property_suumo = config('const.PHOTO_PROPERTY_SUUMO_LAND');
            $data['photo_property_suumo'] = $this->parseData($photo_property_suumo);

            $photo_property_homes = config('const.PHOTO_PROPERTY_HOMES_LAND');
            $data['photo_property_homes'] = $this->parseData($photo_property_homes);

            $photo_property_athome = config('const.PHOTO_PROPERTY_ATHOME_LAND');
            $data['photo_property_athome'] = $this->parseData($photo_property_athome);

            $suumo_seller_comment = config('const.SUUMO_SELLER_COMMENT_LAND');
            $data['suumo_seller_comment'] = $this->parseData($suumo_seller_comment);

            $suumo_facility_spec = config('const.SUUMO_FACILITY_SPEC_LAND');
            $data['suumo_facility_spec'] = $this->parseData($suumo_facility_spec);
        } elseif ($article->property < 6) {
            $photo_property_suumo = config('const.PHOTO_PROPERTY_SUUMO_HOUSE');
            $data['photo_property_suumo'] = $this->parseData($photo_property_suumo);

            $photo_property_homes = config('const.PHOTO_PROPERTY_HOMES_HOUSE');
            $data['photo_property_homes'] = $this->parseData($photo_property_homes);

            $photo_property_athome = config('const.PHOTO_PROPERTY_ATHOME_HOUSE');
            $data['photo_property_athome'] = $this->parseData($photo_property_athome);

            $suumo_seller_comment = config('const.SUUMO_SELLER_COMMENT_HOUSE');
            $data['suumo_seller_comment'] = $this->parseData($suumo_seller_comment);

            $suumo_facility_spec = config('const.SUUMO_FACILITY_SPEC_HOUSE');
            $data['suumo_facility_spec'] = $this->parseData($suumo_facility_spec);
        } else {
            $photo_property_suumo = config('const.PHOTO_PROPERTY_SUUMO_MANSION');
            $data['photo_property_suumo'] = $this->parseData($photo_property_suumo);

            $photo_property_homes = config('const.PHOTO_PROPERTY_HOMES_MANSION');
            $data['photo_property_homes'] = $this->parseData($photo_property_homes);

            $photo_property_athome = config('const.PHOTO_PROPERTY_ATHOME_MANSION');
            $data['photo_property_athome'] = $this->parseData($photo_property_athome);

            $suumo_seller_comment = config('const.SUUMO_SELLER_COMMENT_MANSION');
            $data['suumo_seller_comment'] = $this->parseData($suumo_seller_comment);

            $suumo_facility_spec = config('const.SUUMO_FACILITY_SPEC_MANSION');
            $data['suumo_facility_spec'] = $this->parseData($suumo_facility_spec);
        }
        if(isset($request->all()['saved'])){
            $data['saved'] = 1;
        }
        //Check image suumo
        $list = RelationArticlePhoto::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->get();

        if($article->mansion_id != null){
            $list_mansion = RelationArticlePhoto::where('article_id', '=', $article->mansion_id)->where('company_id', '=', $user->company_id)->get();
        }
        $portal_status = 0;
        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_suumo_image']) == 0){
            $portal_status = 1;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_suumo_image']) == 0){
            $portal_status = 2;
        }
        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_suumo_image']) > 0){
            $portal_status = 3;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_suumo_image']) > 0){
            $portal_status = 4;
        }
        $data['portal_status'] = $portal_status;

        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_homes_image']) == 0){
            $portal_homes_status = 1;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_homes_image']) == 0){
            $portal_homes_status = 2;
        }
        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_homes_image']) > 0){
            $portal_homes_status = 3;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_homes_image']) > 0){
            $portal_homes_status = 4;
        }
        $data['portal_homes_status'] = $portal_homes_status;
        //----------------------------------
        //Check image athome
        $portal_athome_status = 0;
        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_athome_image']) == 0){
            $portal_athome_status = 1;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_athome_image']) == 0){
            $portal_athome_status = 2;
        }
        if((count($list) > 0 || ((isset($list_mansion) && count($list_mansion) > 0 ) || !isset($list_mansion))) && count($data['portal_athome_image']) > 0){
            $portal_athome_status = 3;
        }
        if((count($list) == 0 && ((isset($list_mansion) && count($list_mansion) == 0 ) || !isset($list_mansion))) && count($data['portal_athome_image']) > 0){
            $portal_athome_status = 4;
        }
        $data['portal_athome_status'] = $portal_athome_status;

        //-----------------------------------------
        $suumo_image_do = [];
        $homes_image_do = [];
        $athome_image_do = [];
        //Check first image house
        $filePath = $article->isVertical() ? $article->file_path2 : $article->floor_file_path;
        if (!empty($filePath)) {
            $item = (object) array(
                'id'        =>  'null',
                'article_id' => $article->building_id,
                'file_path' =>  str_replace('public', '/storage', $filePath),
                'memo'      =>  $article->floor_file_comment,
                'first'     =>  1
            );
            if(count($data['portal_suumo_image']) > 0){
                $no = 0;
                foreach ($data['portal_suumo_image'] as $psi){
                    if ($psi->file_path == $filePath) {
                        $no = 1;
                        break;
                    }
                }
                if($no == 0){
                    $suumo_image_do[] = $item;
                }
            }else{
                $suumo_image_do[] = $item;
            }
            if(count($data['portal_homes_image']) > 0){
                $no = 0;
                foreach ($data['portal_homes_image'] as $psi){
                    if ($psi->file_path == $filePath) {
                        $no = 1;
                        break;
                    }
                }
                if($no == 0){
                    $homes_image_do[] = $item;
                }
            }else{
                $homes_image_do[] = $item;
            }
            if(count($data['portal_athome_image']) > 0){
                $no = 0;
                foreach ($data['portal_athome_image'] as $psi){
                    if ($psi->file_path == $filePath) {
                        $no = 1;
                        break;
                    }
                }
                if($no == 0){
                    $athome_image_do[] = $item;
                }
            }else{
                $athome_image_do[] = $item;
            }
        }
        ////////////////////////
        if(count($list)>0){
            if(count($data['portal_suumo_image']) > 0){
                foreach ($list as $item){
                    $no = 0;
                    foreach ($data['portal_suumo_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $suumo_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $suumo_image_do[] = $item;
                }
            }
            //homes
            if(count($data['portal_homes_image']) > 0){
                foreach ($list as $item){
                    $no = 0;
                    foreach ($data['portal_homes_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $homes_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $homes_image_do[] = $item;
                }
            }
            //athome
            if(count($data['portal_athome_image']) > 0){
                foreach ($list as $item){
                    $no = 0;
                    foreach ($data['portal_athome_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $athome_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $athome_image_do[] = $item;
                }
            }
        }
        if(isset($list_mansion) && count($list_mansion) > 0){
            if(count($data['portal_suumo_image']) > 0){
                foreach ($list_mansion as $item){
                    $no = 0;
                    foreach ($data['portal_suumo_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $suumo_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list_mansion as $item) {
                    $suumo_image_do[] = $item;
                }
            }
            //homes
            if(count($data['portal_homes_image']) > 0){
                foreach ($list_mansion as $item){
                    $no = 0;
                    foreach ($data['portal_homes_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $homes_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list_mansion as $item) {
                    $homes_image_do[] = $item;
                }
            }
            //athome
            if(count($data['portal_athome_image']) > 0){
                foreach ($list_mansion as $item){
                    $no = 0;
                    foreach ($data['portal_athome_image'] as $psi){
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $athome_image_do[] = $item;
                    }
                }
            }else{
                foreach ($list_mansion as $item) {
                    $athome_image_do[] = $item;
                }
            }
        }
        $data['suumo_status_do'] = '';
        $data['homes_status_do'] = '';
        $data['athome_status_do'] = '';
        if(empty($suumo_image_do)){
            $data['suumo_status_do'] = 2;
        }
        if(empty($athome_image_do)){
            $data['athome_status_do'] = 2;
        }
        $data['suumo_image_do'] = $suumo_image_do;
        $data['homes_image_do'] = $homes_image_do;
        $data['athome_image_do'] = $athome_image_do;
        //----------------------------------

        $list = RelationArticleFacility::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->get();
        $portal_facility_status = 0;
        if(count($list) > 0 && count($data['portal_suumo_facility']) == 0){
            $portal_facility_status = 1;
        }
        if(count($list) == 0 && count($data['portal_suumo_facility']) == 0){
            $portal_facility_status = 2;
        }
        if(count($list) > 0 && count($data['portal_suumo_facility']) > 0){
            $portal_facility_status = 3;
        }
        if(count($list) == 0 && count($data['portal_suumo_facility']) > 0){
            $portal_facility_status = 4;
        }
        $data['portal_facility_status'] = $portal_facility_status;
        // Athome Facility
        $athome_facility_status = 0;
        if(count($list) > 0 && count($data['portal_athome_facility']) == 0){
            $athome_facility_status = 1;
        }
        if(count($list) == 0 && count($data['portal_athome_facility']) == 0){
            $athome_facility_status = 2;
        }
        if(count($list) > 0 && count($data['portal_athome_facility']) > 0){
            $athome_facility_status = 3;
        }
        if(count($list) == 0 && count($data['portal_athome_facility']) > 0){
            $athome_facility_status = 4;
        }
        $data['athome_facility_status'] = $athome_facility_status;
        //-----------------------------------------
        $suumo_facility_do = [];
        $homes_facility_do = [];
        $athome_facility_do = [];
        if(count($list)>0){
            if(count($data['portal_suumo_facility']) > 0){
                foreach ($list as $item){
                    $fac = Facility::getDataById($item->facility_id);
                    $item->file_path = str_replace('public', '/storage', $fac->file_path);
                    $no = 0;
                    foreach ($data['portal_suumo_facility'] as $psi){
                        if($psi->file_path == $fac->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $suumo_facility_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $fac = Facility::getDataById($item->facility_id);
                    $item->file_path = str_replace('public', '/storage', $fac->file_path);
                    $suumo_facility_do[] = $item;
                }
            }
            //homes
            if(count($data['portal_homes_image']) > 0){
                foreach ($list as $item){
                    $no = 0;
                    foreach ($data['portal_homes_image'] as $psi){
                        $item->file_path = str_replace('/storage', 'public', $item->file_path);
                        if($psi->file_path == $item->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $homes_facility_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $homes_facility_do[] = $item;
                }
            }
            //athome
            if(count($data['portal_athome_facility']) > 0){
                foreach ($list as $item){
                    $fac = Facility::getDataById($item->facility_id);
                    $item->file_path = str_replace('public', '/storage', $fac->file_path);
                    $no = 0;
                    foreach ($data['portal_athome_facility'] as $psi){
                        if($psi->file_path == $fac->file_path){
                            $no = 1;
                            break;
                        }
                    }
                    if($no == 0){
                        $athome_facility_do[] = $item;
                    }
                }
            }else{
                foreach ($list as $item) {
                    $fac = Facility::getDataById($item->facility_id);
                    $item->file_path = str_replace('public', '/storage', $fac->file_path);
                    $athome_facility_do[] = $item;
                }
            }
        }
        $data['suumo_facility_do'] = $suumo_facility_do;
        foreach($homes_facility_do as $row) {
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['homes_facility_do'] = $homes_facility_do;
        $data['athome_facility_do'] = $athome_facility_do;

        $data['suumo_facility_status_do'] = '';
        $data['athome_facility_status_do'] = '';
        if(empty($suumo_facility_do)){
            $data['suumo_facility_status_do'] = 2;
        }
        if(empty($athome_facility_do)){
            $data['athome_facility_status_do'] = 2;
        }
        if(empty($homes_image_do) && empty($homes_facility_do)){
            $data['homes_status_do'] = 2;
        }

        return view("admin.pages.portal-image", $data);
    }
    public function uploadPortalFirstImage($id, $type) {
        $article = Article::getDataById($id);
        $filePath = $article->isVertical() ? $article->file_path2 : $article->floor_file_path;
        if (!empty($filePath)) {
            $photo_data = [
                'article_id' => $article->building_id,
                'file_type'  => null,
                'file_path' =>  $filePath,
                'file_disp' =>  null,
                'order'     =>  0,
                'memo'      =>  $article->floor_file_comment,
                'company_id' => \auth()->user()->company_id,
                'portal_id' =>  $article->building_id,
                'mansion'   =>  null,
                'property_sub' =>  $article->floor_file_type,
                'facility' =>  config('const.TYPE_FLOOR_PLAN'),
                'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN'),
            ];

            $photo_data['type'] = $type;
            $obj = RelationPortalPhoto::ofImage($article->building_id, $article->building_id, $type)->first();
            if (!empty($obj)){
                $photo_data['order'] = $obj->order;
                $photo_data['del'] = 0;
                $obj->update($photo_data);
            }else{
                $obj = RelationPortalPhoto::create($photo_data);
            }
        }
    }

    public function registImage(Request $request)
    {
        $check = $this->PortalPost($request, true);
        if($check !== true){
            return  response()->json($check, 422);
//            return redirect()->route('admin.portal.image', [$request->id, 'tab' => $request->tab]);
        }
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        if (is_null($article)) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }
        $all = $request->all();

        $this->saveImageSuumoImage($request, $article);
        $this->saveImageSuumoFacility($request, $article);
        $this->saveImageSuumoTrafficMap($request, $article);
        $this->saveImageSuumoSeller($request, $article);
        $this->saveImageSuumoSpec($request, $article);
        $this->saveImageSuumoContruction($request, $article);
        //homes
        $this->saveImageHomes($request, $article);
        $this->saveImageHomesPanorama($request, $article);
        //athome
        $this->saveImageAthome($request, $article);
        $this->saveImageAthomeFacility($request, $article);

        if (isset($request->delete_relation_portal_image)) {
            $list = explode(',', $request->delete_relation_portal_image);
            foreach ($list as $key => $val) {
                RelationPortalPhoto::where('id', '=', $val)->delete();
            }
        }
        if ($request->get('restore_relation_portal_image') !='') {
            $list = explode(',', $request->restore_relation_portal_image);
            foreach ($list as $key => $val) {
                $relationPortalPhoto = RelationPortalPhoto::findOrFail($val);
                $relationPortalPhoto->update(['del'  =>  0]);
            }
        }

        if (isset($request->delete_relation_portal_facility_image)) {
            $list = explode(',', $request->delete_relation_portal_facility_image);
            foreach ($list as $key => $val) {
                RelationPortalFacility::where('id', '=', $val)->delete();
            }
        }

        if ($request->get('restore_relation_portal_facility_image') != '') {
            $list = explode(',', $request->restore_relation_portal_facility_image);
            foreach ($list as $key => $val) {
                $relationPortalPhoto = RelationPortalFacility::findOrFail($val);
                $relationPortalPhoto->update(['del'  =>  0]);
            }
        }

        if (isset($request->delete_portal_panorama_image)) {
            $list = explode(',', $request->delete_portal_panorama_image);
            foreach ($list as $key => $val) {
                PortalHomesPanorama::where('id', '=', $val)->delete();
            }
        }

        if ($request->get('restore_relation_portal_panorama_image') != '') {
            $list = explode(',', $request->restore_relation_portal_panorama_image);
            foreach ($list as $key => $val) {
                $relationPortalPhoto = PortalHomesPanorama::findOrFail($val);
                $relationPortalPhoto->update(['del'  =>  0]);
            }
        }


        if ($request->toportal == 1) {
            $URL = url('');
            header('Location: ' . route("admin.portal", $article->id));
            die();
        }

        return redirect()->route('admin.portal.image', [$request->id, 'tab' => $request->tab, 'saved' => 1]);
    }

    public function updateImageDo(Request $request)
    {
        $user = Auth::user();
        //ID Relation_article_photo
        $article_id = $request->article_id;
        $list_portal_image_do = $request->list_portal_image_do;

        $ar_img = [];
        if($list_portal_image_do != ''){
            $ar_img = explode(',', $list_portal_image_do);
        }
        $ar_img_homes = [];

        $portal = $request->portal;
        if($portal == 'suumo'){
            $type = config('const.SUUMO');
        }
        if($portal == 'homes'){
            $type = config('const.HOMES');
            //case home
            $list_portal_facility_do = $request->list_portal_facility_do;
            if($list_portal_facility_do){
                $ar_img_homes = explode(',', $list_portal_facility_do);
            }
        }
        if($portal == 'athome'){
            $type = config('const.ATHOME');
        }
        //Check first image
        $ar_img_new = [];
        foreach ($ar_img as $ai){
            if($ai == 'null'){
                $this->uploadPortalFirstImage($article_id, $type);
            }else{
                $ar_img_new[] = $ai;
            }
        }
        $ar_img = $ar_img_new;
        $list = RelationArticlePhoto::wherein('id', $ar_img)->where('company_id', '=', $user->company_id)->get();

        $last_order = RelationPortalPhoto::where('article_id', $article_id)->where('type', '=', $type)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
        $num_order = 0;
        if(!empty($last_order)){
            $num_order = $last_order->order;
        }
        foreach ($list as $img) {
            //$article_id = $img->article_id;
            $property_sub = $img->property_sub;
            $mansion = null;

            $num_order++;
            $photo_data = [
                'article_id' => $article_id,
                'file_type' => $img->file_type,
                'file_path' => $img->file_path,
                'file_disp' => $img->file_disp,
                'order' => $num_order,
                'memo' => $img->memo,
                'company_id' => $img->company_id,
                'portal_id' => $img->id==null?'':$img->id,
                'mansion' => $mansion,
                'property_sub' => $property_sub,
                'facility' => config('const.TYPE_IMAGE_PORTAL'),
                'type_upload' => config('const.TYPE_UPLOAD_BUKKEN'),
            ];

            $photo_data['type'] = $type;
            $obj = RelationPortalPhoto::ofImage($img->id, $img->article_id, $type)->first();
            if (!empty($obj)) {
                $photo_data['order'] = $obj->order;
                $photo_data['del'] = 0;
                $obj->update($photo_data);
            } else {
                $obj = RelationPortalPhoto::create($photo_data);
            }
        }
        if(count($ar_img_homes) > 0) {
            $listFacility = RelationArticleFacility::with('facilityRelation')->whereIn('id', $ar_img_homes)->where('company_id', '=', $user->company_id)->get();

            foreach ($listFacility as $f) {
                $facility_memo = '施設名: '.$f->facilityRelation->name.'
現地からの距離: '.$f->distance.'m';
                $num_order++;
                $dataImage = [
                    'article_id' => $f->article_id,
                    'file_type' => $f->file_type,
                    'file_path' => $f->facilityRelation->file_path,
                    'memo' => $facility_memo,
                    'company_id' => $f->company_id,
                    'order' => $num_order,
                    'facility' => config('const.TYPE_IMAGE_PORTAL'),
                    'type_upload' => config('const.TYPE_UPLOAD_BUKKEN'),
                    'type' => $type
                ];
                $obj = RelationPortalPhoto::ofImage($f->id, $f->article_id, $type)->first();
                if (!empty($obj)) {
                    $photo_data['order'] = $obj->order;
                    $photo_data['del'] = 0;
                    $obj->update($dataImage);
                } else {
                    $obj = RelationPortalPhoto::create($dataImage);
                }
            }
        }
        return redirect()->route('admin.portal.image', [$article_id, 'tab' => $portal, 'saved' => 1]);
    }
    public function updateFacilityDo(Request $request)
    {
        $user = Auth::user();
        //ID Relation_article_photo
        $article_id = $request->article_id;
        $list_portal_facility_do = $request->list_portal_facility_do;
        $ar_img = [];
        if($list_portal_facility_do != ''){
            $ar_img = explode(',', $list_portal_facility_do);
        }
        $portal = $request->portal;
        if($portal == 'suumo'){
            $type = config('const.SUUMO');
        }
        if($portal == 'homes'){
            $type = config('const.HOMES');
        }
        if($portal == 'athome'){
            $type = config('const.ATHOME');
        }

        $list = RelationArticleFacility::wherein('id', $ar_img)->where('company_id', '=', $user->company_id)->get();
        if(count($list) > 0){
            $last_order = RelationPortalFacility::where('article_id', $article_id)->where('type', '=', $type)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
        }
        $num_order = 0;
        if(!empty($last_order)){
            $num_order = $last_order->order;
        }

        foreach ($list as $img) {
            $num_order++;
            $fac = Facility::where('id', '=', $img->facility)->where('company_id', '=', $user->company_id)->first();
            $facility_memo = '施設名: ' . $fac->name . '
現地からの距離: ' . $img->distance . 'm';
            $facility_data = [
                'company_id' => $img->company_id,
                'article_id' => isset($room_id) ? $room_id : $img->article_id,
                'article_facility_id' => $img->id,
                'facility_name' => $fac->name,
                'facility_memo' => $fac->memo,
                'file_path' => $fac->file_path,
                'distance' => $img->distance,
                'order' => $num_order,
                'facility_area' => $img->facility_area,
                'facility_property' => $img->facility_property,
                'facility' => $img->facility,
                'type_upload' => config('const.TYPE_UPLOAD_BUKKEN')
            ];

            if ($portal == 'suumo') {
                $facility_data_suumo = $facility_data;
                $obj_suumo = RelationPortalFacility::where('article_facility_id', $img->id)->type(config('const.SUUMO'))->first();
                $facility_data_suumo['type'] = config('const.SUUMO');
                if (!empty($obj_suumo)) {
                    $facility_data_suumo['del'] = 0;
                    $obj_suumo->update($facility_data_suumo);
                } else {
                    RelationPortalFacility::create($facility_data_suumo);
                }
            }
            if ($portal == 'athome') {
                $facility_data_athome = $facility_data;
                $obj_athome = RelationPortalFacility::where('article_facility_id', $img->id)->type(config('const.ATHOME'))->first();
                $facility_data_athome['type'] = config('const.ATHOME');
                if (!empty($obj_suumo)) {
                    $facility_data_athome['del'] = 0;
                    $obj_athome->update($facility_data_athome);
                } else {
                    RelationPortalFacility::create($facility_data_athome);
                }
            }
        }
        return redirect()->route('admin.portal.image', [$article_id, 'tab' => $portal, 'saved' => 1]);
    }
    private function PortalPost($request, $ajax = false){
        $all = $request->all();
        $msg = [];
        $array_keys = array_keys($all);
        ///////////////////////////////
        $restore_image_ids = $request->restore_relation_portal_image != '' ? explode(",", $request->restore_relation_portal_image): [];
        $restore_facility_image_ids = $request->restore_relation_portal_facility_image != '' ? explode(",", $request->restore_relation_portal_facility_image): [];
        $photo_del_ids = RelationPortalPhoto::where('del', 1)
            ->where('article_id', $request->article_id)
            ->whereNotIn('id', $restore_image_ids)
            ->get()
            ->pluck('id')
            ->toArray();
        $photo_facility_del_ids = RelationPortalFacility::where('del', 1)
            ->where('article_id', $request->article_id)
            ->whereNotIn('id', $restore_facility_image_ids)
            ->get()
            ->pluck('id')
            ->toArray();
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_photo_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }
        }
        foreach ($tag as $i){
            if($all['article_photo_id'.$i] != null || (isset($request->file_input[$i]) && $request->file_input[$i] != '')){
                if($all['photo_property_sub'.$i] == null){
                    $msg[] = 'SUUMO (内外観・その他)の必須項目の画像のカテゴリーに入力がありません';
                }
            }
            //////////////////////////////////
            if(isset($request->file_input[$i])) {
                $photo = $request->file_input[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO(内外観・その他)にPNG形式の画像が登録されています';
                }
            }
            //////////////////////////////
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_facility_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_facility_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_facility_del_ids)) {
                $tag[] = $target_key;
            }
        }
        foreach ($tag as $i){
            if($all['article_facility_id'.$i] != '' || (isset($request->file_facility[$i]) && $request->file_facility[$i] != '')){
                if($all['portal_facility_photo_property_sub'.$i] == ''){
                    $msg[] = 'SUUMO (施設など)の必須項目の画像のカテゴリーに入力がありません';
                }
                if($all['portal_facility_name'.$i] == ''){
                    $msg[] = 'SUUMO (施設など)の必須項目の施設名称に入力がありません';
                }
                if($all['portal_facility_distance'.$i] == ''){
                    $msg[] = 'SUUMO (施設など)の必須項目の物件への距離に入力がありません';
                }
            }
            //////////////////////////////////
            if(isset($request->file_facility[$i])) {
                $photo = $request->file_facility[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO(施設など)にPNG形式の画像が登録されています';
                }
            }
            //////////////////////////////
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_seller_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_seller_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }

        }
        foreach ($tag as $i){
            if($all['suumo_seller_id'.$i] != '' || (isset($request->file_seller[$i]) && $request->file_seller[$i] != '')){
                if($all['seller_property_sub'.$i] == ''){
                    $msg[] = 'SUUMO (売主コメント)の必須項目の画像のカテゴリーに入力がありません';
                }
            }
            //////////////////////////////////
            if(isset($request->file_seller[$i])) {
                $photo = $request->file_seller[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO(売主コメント)にPNG形式の画像が登録されています';
                }
            }
            //////////////////////////////
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_spec_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_spec_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }

        }
        foreach ($tag as $i){
            if($all['suumo_spec_id'.$i] != '' || (isset($request->file_spec[$i]) && $request->file_spec[$i] != '')){
                if($all['spec_property_sub'.$i] == ''){
                    $msg[] = 'SUUMO (設備仕様)の必須項目の画像のカテゴリーに入力がありません';
                }
            }
            //////////////////////////////////
            if(isset($request->file_spec[$i])) {
                $photo = $request->file_spec[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO(設備仕様)にPNG形式の画像が登録されています';
                }
            }
            //////////////////////////////
        }
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_traffic_map_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_traffic_map_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }

        }
        foreach ($tag as $i){
            if(isset($request->file_traffic_map[$i])) {
                $photo = $request->file_traffic_map[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO(現地案内図)にPNG形式の画像が登録されています';
                }
            }
        }
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_construction_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_construction_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }
        }
        foreach ($tag as $i){
            if(isset($request->file_construction[$i])) {
                $photo = $request->file_construction[$i];
                $extension = $photo->getClientOriginalExtension();
                if ($extension == 'png') {
                    $msg[] = 'SUUMO構造にPNG形式の画像が登録されています';
                }
            }
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/homes_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('homes_photo_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }

        }
        foreach ($tag as $i){
            if($all['homes_photo_id'.$i] != '' || (isset($request->homes_file_input[$i]) && $request->homes_file_input[$i] != '')){
                if($all['homes_property_sub'.$i] == ''){
                    $msg[] = 'HOMES (内外観・その他)の必須項目の画像のカテゴリーに入力がありません';
                }
            }
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/athome_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('athome_photo_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_del_ids)) {
                $tag[] = $target_key;
            }
        }
        foreach ($tag as $i){
            if($all['athome_photo_id'.$i] != '' || (isset($request->athome_file_input[$i]) && $request->athome_file_input[$i] != '')){
                if($all['athome_property_sub'.$i] == ''){
                    $msg[] = 'at home (内外観・地図・周辺写真・その他)の必須項目の画像のカテゴリーに入力がありません';
                }
            }
        }
        ///////////////////////////////////////////
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/athome_facility_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('athome_facility_id', '', $key);
            if ($target_key != "" && !in_array($request[$key], $photo_facility_del_ids)) {
                $tag[] = $target_key;
            }
        }
        foreach ($tag as $i){
            if($all['athome_facility_id'.$i] != '' || (isset($request->athome_facility_file_input[$i]) && $request->athome_facility_file_input[$i] != '')){
                if($all['athome_facility_property_sub'.$i] == ''){
                    $msg[] = 'at home (周辺環境写真)の必須項目の画像のカテゴリーに入力がありません';
                }
                if($all['athome_facility_name'.$i] == ''){
                    $msg[] = 'at home (周辺環境写真)の必須項目の施設名称に入力がありません';
                }
                if($all['athome_facility_distance'.$i] == '' || $all['athome_facility_distance'.$i] == 0){
                    $msg[] = 'at home (周辺環境写真)の必須項目の物件への距離に入力がありません';
                }
            }
        }
        if(!empty($msg)){
            $msgs = '';
            $j = 0;
            foreach ($msg as $mg){
                $j++;
                $msgs .= $j.'. '.$mg.'<br>';
            }
            $msgs .= '<br>以上より、受付不可となります。';

            if($ajax)
                return  $msgs;
            else
                $request->session()->flash('message_modal', $msgs);

            return false;
        }
        return true;
    }

    private function saveImageSuumoImage($request, $article){
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);

        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_photo_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->file_input)) {
                $last_order = RelationPortalPhoto::ofImage(null, $request->id, config('const.SUUMO'))->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $article_portal_id = $all['article_photo_id' . $i];

                    if(isset($request->file_input[$i])) {
                        $num_order++;
                        $photo = $request->file_input[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }

                        $tmp_path = 'company_'.$user->company_id.'/portal/suumo/image';
                        if(!Storage::disk('public')->exists($tmp_path))
                            Storage::disk('public')->makeDirectory($tmp_path);

                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/image/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'type'      =>  config('const.SUUMO'),
                            'property_sub' => $all['photo_property_sub' . $i],
                            'memo' => $all['photo_comment' . $i],
                            'order' =>  $all['order' . $i] == '' ? $num_order: $all['order' . $i],
                            'company_id' => auth()->user()->company_id,
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL')
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }else{
                        $photo_data = [
                            'property_sub' => $all['photo_property_sub' . $i],
                            'memo' => $all['photo_comment' . $i],
                            'order' =>  $all['order' . $i] == '' ? $num_order: $all['order' . $i]
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_portal_id = $all['article_photo_id'.$val];
                    $file_path = $all['file_path'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'memo' => $all['photo_comment'.$val],
                            'property_sub' => $all['photo_property_sub' . $val],
                            'order' =>  $all['order'.$val],
                            'company_id' => auth()->user()->company_id,
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL')
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->del_photo_id)) {
                $list = explode(',', $request->del_photo_id);
                foreach ($list as $key => $val) {
                    $query = RelationPortalPhoto::where('id', $val)->first();
                    if(!empty($query)){
                        $query->update(['del'  =>  1]);
                    }
                }
            }
        }
    }

    private function saveImageSuumoFacility($request, $article){
        $all = $request->all();
        $array_keys = array_keys($all);
        $user = Auth::user();
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_facility_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_facility_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->file_facility)) {
                $last_order = RelationPortalFacility::where('article_id', $request->id)->where('type', config('const.SUUMO'))->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $article_facility_id = $all['article_facility_id' . $i];
                    if(isset($request->file_facility[$i])) {
                        $num_order++;
                        $photo = $request->file_facility[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/facility/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'type'      =>  config('const.SUUMO'),
                            'facility_property' => $all['portal_facility_photo_property_sub' . $i],
                            'facility_name' => $all['portal_facility_name' . $i],
                            'distance' => $all['portal_facility_distance' . $i],
                            'facility_memo' => $all['portal_facility_memo' . $i],
                            'order' =>  $all['facility_order' . $i] == '' ? $num_order: $all['order' . $i],
                            'company_id' => auth()->user()->company_id,
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                            'del'   =>  0
                        ];
                        if (!empty($article_facility_id)) {
                            $relationArticleFancility = RelationPortalFacility::where('id', $article_facility_id)->where('type', config('const.SUUMO'))->first();
                            if (!empty($relationArticleFancility)) {
                                $photo_data['del'] = 0;
                                $relationArticleFancility->update($photo_data);
                            }
                        } else {
                            RelationPortalFacility::create($photo_data);
                        }
                    }else {
                        $file_path = $all['file_path_suumo_fac' . $i];
                        if ($file_path != '') {
                            $photo_data = [
                                'file_path' => $file_path,
                                'facility_name' => $all['portal_facility_name' . $i],
                                'facility_property' => $all['portal_facility_photo_property_sub' . $i],
                                'distance' => $all['portal_facility_distance' . $i],
                                'facility_memo' => $all['portal_facility_memo' . $i],
                                'order' => $all['facility_order' . $i],
                                'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                            ];

                            if (!empty($article_facility_id)) {
                                $relationArticlePhoto = RelationPortalFacility::where('id', $article_facility_id)->first();
                                if (!empty($relationArticlePhoto)) {
                                    $photo_data['del'] = 0;
                                    $relationArticlePhoto->update($photo_data);
                                }
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_facility_id = $all['article_facility_id'.$val];
                    $file_path = $all['file_path_suumo_fac'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'facility_name' => $all['portal_facility_name' . $val],
                            'distance' => $all['portal_facility_distance' . $val],
                            'facility_memo' => $all['portal_facility_memo' . $val],
                            'facility_property' => $all['portal_facility_photo_property_sub' . $val],
                            'order' =>  $all['facility_order'.$val],
                            'company_id' => auth()->user()->company_id,
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];

                        if (!empty($article_facility_id)) {
                            $relationArticlePhoto = RelationPortalFacility::where('id', $article_facility_id)->where('type', config('const.SUUMO'))->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalFacility::create($photo_data);
                        }
                    }
                }
            }

            if (isset($request->del_facility_id)) {
                $list = explode(',', $request->del_facility_id);
                foreach ($list as $key => $val) {
                    $query = RelationPortalFacility::where('id', $val)->where('type', config('const.SUUMO'))->first();
                    if(!empty($query)){
                        $query->update(['del'  =>  1]);
                    }
                }
            }
        }

    }

    private function saveImageSuumoTrafficMap($request, $article){
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);

        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/article_traffic_map_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('article_traffic_map_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            $file_paths = [];
            if (isset($request->file_traffic_map)) {
                $relationArticleTrafficMap = PortalSuumoTrafficMap::where('article_id', $article->building_id)->first();
                if (!empty($relationArticleTrafficMap)) {
                    $file_pathss = json_decode($relationArticleTrafficMap->file_path);
                }
                foreach ($tag as $i){
                    if(isset($request->file_traffic_map[$i])) {
                        $photo = $request->file_traffic_map[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/trafic_map/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());
                        $file_paths[] = [
                            'id'        =>  $all['article_traffic_map_id' . $i],
                            'file_path' => $image_url,
                            'memo' => $all['portal_traffic_map_memo' . $i]
                        ];
                    }else{
                        $image_url = $all['file_path_suumo_traffic'.$i];
                        $file_paths[] = [
                            'id'        =>  $all['article_traffic_map_id' . $i],
                            'file_path' => $image_url,
                            'memo' => $all['portal_traffic_map_memo' . $i]
                        ];
                    }
                }

                $photo_data = [
                    'article_id'        => $article->building_id,
                    'file_path'         => json_encode($file_paths),
                    'memo'              => $all['portal_traffic_map_content'],
                    'company_id'        => auth()->user()->company_id
                ];

                if (!empty($relationArticleTrafficMap)) {
                    $relationArticleTrafficMap->update($photo_data);
                }else {
                    PortalSuumoTrafficMap::create($photo_data);
                }

            }else{
                foreach ($tag as $i){
                    $image_url = $all['file_path_suumo_traffic'.$i];
                    if($image_url != ''){
                        $file_paths[] = [
                            'id'        =>  $all['article_traffic_map_id' . $i],
                            'file_path' => $image_url,
                            'memo'      => $all['portal_traffic_map_memo' . $i]
                        ];
                    }
                }
                $photo_data = [
                    'article_id'        =>  $article->building_id,
                    'file_path'         => json_encode($file_paths),
                    'memo'              =>  $all['portal_traffic_map_content'],
                    'company_id'        => auth()->user()->company_id
                ];
                $relationArticleTrafficMap = PortalSuumoTrafficMap::where('article_id', $article->building_id)->first();
                if (!empty($relationArticleTrafficMap)) {
                    $relationArticleTrafficMap->update($photo_data);
                }else {
                    PortalSuumoTrafficMap::create($photo_data);
                }
            }
        }
        // End Suumo Traffic Map
    }

    private function saveImageSuumoSeller($request, $article){
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_seller_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_seller_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->file_seller)) {
                $last_order = PortalSuumoPhoto::where('article_id', $request->id)->where('type', 1)->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $suumo_seller_id = $all['suumo_seller_id' . $i];
                    if(isset($request->file_seller[$i])) {
                        $num_order++;
                        $photo = $request->file_seller[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/seller/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'property' => $all['seller_property_sub' . $i],
                            'memo' => $all['suumo_seller_memo' . $i],
                            'type'  => 1,
                            'order' =>  $all['seller_order' . $i] == '' ? $num_order: $all['order' . $i],
                            'company_id' => auth()->user()->company_id
                        ];
                        if (!empty($suumo_seller_id)) {
                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_seller_id)->where('type', 1)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }else{
                        if (!empty($suumo_seller_id)) {
                            $photo_data = [
                                'property' => $all['seller_property_sub' . $i],
                                'memo' => $all['suumo_seller_memo' . $i],
                                'order' =>  $all['seller_order' . $i] == '' ? $num_order: $all['order' . $i]

                            ];

                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_seller_id)->where('type', 1)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $suumo_seller_id = $all['suumo_seller_id'.$val];
                    $file_path = $all['file_path_suumo_seller'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'property' => $all['seller_property_sub' . $val],
                            'memo' => $all['suumo_seller_memo' . $val],
                            'order' =>  $all['seller_order'.$val],
                            'company_id' => auth()->user()->company_id
                        ];

                        if (!empty($suumo_seller_id)) {
                            $relationArticlePhoto = PortalSuumoPhoto::where('id', $suumo_seller_id)->where('type', 1)->first();
                            if (!empty($relationArticlePhoto)) {
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->del_seller_id)) {

                $list = explode(',', $request->del_seller_id);
                foreach ($list as $key => $val) {
                    PortalSuumoPhoto::where('id', '=', $val)->delete();
                }
            }
        }
    }

    private function saveImageSuumoContruction($request, $article){
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_construction_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_construction_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->file_construction)) {
                $last_order = PortalSuumoPhoto::where('article_id', $request->id)->where('type', 3)->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $suumo_construction_id = $all['suumo_construction_id' . $i];

                    if(isset($request->file_construction[$i])) {
                        $num_order++;
                        $photo = $request->file_construction[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/construction/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'facility_name' => $all['suumo_construction_name' . $i],
                            'memo' => $all['suumo_construction_memo' . $i],
                            'type'  => 3,
                            'order' =>  $all['construction_order' . $i] == '' ? $num_order: $all['order' . $i],
                            'company_id' => auth()->user()->company_id
                        ];
                        if (!empty($suumo_construction_id)) {
                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_construction_id)->where('type', 3)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }else{
                        if (!empty($suumo_construction_id)) {
                            $photo_data = [
                                'facility_name' => $all['suumo_construction_name' . $i],
                                'memo' => $all['suumo_construction_memo' . $i],
                                'order' =>  $all['construction_order' . $i] == '' ? $num_order: $all['order' . $i]

                            ];

                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_construction_id)->where('type', 3)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $suumo_construction_id = $all['suumo_construction_id'.$val];
                    $file_path = $all['file_path_suumo_cons'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'facility_name' => $all['suumo_construction_name' . $val],
                            'memo' => $all['suumo_construction_memo' . $val],
                            'order' =>  $all['construction_order'.$val],
                            'company_id' => auth()->user()->company_id
                        ];

                        if (!empty($suumo_construction_id)) {
                            $relationArticlePhoto = PortalSuumoPhoto::where('id', $suumo_construction_id)->where('type', 3)->first();
                            if (!empty($relationArticlePhoto)) {
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }
                }
            }

            if (isset($request->del_construction_id)) {
                $list = explode(',', $request->del_construction_id);
                foreach ($list as $key => $val) {
                    PortalSuumoPhoto::where('id', '=', $val)->delete();
                }
            }
        }

    }

    private function saveImageSuumoSpec($request, $article){
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/suumo_spec_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('suumo_spec_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->file_spec)) {
                $last_order = PortalSuumoPhoto::where('article_id', $request->id)->where('type', 2)->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $suumo_spec_id = $all['suumo_spec_id' . $i];

                    if(isset($request->file_spec[$i])) {
                        $num_order++;
                        $photo = $request->file_spec[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/suumo/spec/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'property' => $all['spec_property_sub' . $i],
                            'facility_name' => $all['spec_facility_name' . $i],
                            'memo' => $all['suumo_spec_memo' . $i],
                            'type'  => 2,
                            'order' =>  $all['spec_order' . $i] == '' ? $num_order: $all['spec_order' . $i],
                            'company_id' => auth()->user()->company_id
                        ];
                        if (!empty($suumo_spec_id)) {
                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_spec_id)->where('type', 2)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }else{
                        if (!empty($suumo_spec_id)) {
                            $photo_data = [
                                'property' => $all['spec_property_sub' . $i],
                                'memo' => $all['suumo_spec_memo' . $i],
                                'facility_name' => $all['spec_facility_name' . $i],
                                'order' =>  $all['spec_order' . $i] == '' ? $num_order: $all['spec_order' . $i]

                            ];

                            $relationArticleFancility = PortalSuumoPhoto::where('id', $suumo_spec_id)->where('type', 2)->first();
                            if (!empty($relationArticleFancility)) {
                                $relationArticleFancility->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $suumo_spec_id = $all['suumo_spec_id'.$val];
                    $file_path = $all['file_path_suumo_spec'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'property' => $all['spec_property_sub' . $val],
                            'memo' => $all['suumo_spec_memo' . $val],
                            'facility_name' => $all['spec_facility_name' . $val],
                            'order' =>  $all['spec_order'.$val],
                            'company_id' => auth()->user()->company_id
                        ];

                        if (!empty($suumo_spec_id)) {
                            $relationArticlePhoto = PortalSuumoPhoto::where('id', $suumo_spec_id)->where('type', 2)->first();
                            if (!empty($relationArticlePhoto)) {
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            PortalSuumoPhoto::create($photo_data);
                        }
                    }
                }
            }

            if (isset($request->del_spec_id)) {

                $list = explode(',', $request->del_spec_id);
                foreach ($list as $key => $val) {
                    PortalSuumoPhoto::where('id', '=', $val)->delete();
                }
            }
        }
    }

    private function saveImageHomes($request, $article) {
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/homes_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('homes_photo_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }

        if (isset($request->id)) {
            if (isset($request->homes_file_input)) {
                $last_order = RelationPortalPhoto::ofImage(null, $request->id, config('const.HOMES'))->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $article_portal_id = $all['homes_photo_id'.$i];
                    if(isset($request->homes_file_input[$i])) {
                        $num_order++;
                        $photo = $request->homes_file_input[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/homes/image/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'memo' => $all['homes_photo_comment' . $i],
                            'order' =>  $all['homes_order' . $i] == '' ? $num_order: $all['homes_order' . $i],
                            'company_id' =>  auth()->user()->company_id,
                            'property_sub' =>  $all['homes_property_sub' . $i],
                            'type' => config('const.HOMES'),
                            'facility' => !empty($all['homes_facility' . $i]) ? $all['homes_facility' . $i] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }else{
                        $photo_data = [
                            'memo' => $all['homes_photo_comment' . $i],
                            'order' =>  $all['homes_order' . $i] == '' ? $num_order: $all['homes_order' . $i],
                            'property_sub' =>  $all['homes_property_sub' . $i],
                            'facility' => !empty($all['homes_facility' . $i]) ? $all['homes_facility' . $i] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_portal_id = $all['homes_photo_id'.$val];
                    $file_path = $all['homes_file_path'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'memo' => $all['homes_photo_comment'.$val],
                            'order' =>  $all['homes_order'.$val],
                            'company_id' =>  auth()->user()->company_id,
                            'property_sub' =>  $all['homes_property_sub'.$val],
                            'type' => config('const.HOMES'),
                            'facility' => !empty($all['homes_facility'.$val]) ? $all['homes_facility'.$val] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];

                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->homes_del_photo_id)) {

                $list = explode(',', $request->homes_del_photo_id);
                foreach ($list as $key => $val) {
                    $relationPortalPhoto = RelationPortalPhoto::findOrFail($val);
                    $relationPortalPhoto->update(['del'  =>  1]);
                }
            }
        }
    }

    private function saveImageHomesPanorama($request, $article) {
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/panorama_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('panorama_photo_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->panorama_file_input)) {
                $last_order = PortalHomesPanorama::where('article_id', $request->id)->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    if(isset($request->panorama_file_input[$i])) {
                        $num_order++;
                        $photo = $request->panorama_file_input[$i];
                        $article_portal_id = $all['panorama_photo_id' . $i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/homes/image/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'order' =>  $all['panorama_order' . $i] == '' ? $num_order: $all['panorama_order' . $i],
                            'company_id' =>  auth()->user()->company_id,
                            'title' =>  $all['panorama_title' . $i],
                            'reins_type' =>  $all['panorama_reins_type' . $i],
                            'type' => config('const.PANORAMA_TYPE_IMAGE'),
                            'del' => 0
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = PortalHomesPanorama::where('id', $article_portal_id)->first();
                            if (!empty($relationArticlePhoto)) {
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            PortalHomesPanorama::create($photo_data);
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_portal_id = $all['panorama_photo_id'.$val];
                    $file_path = $all['panorama_file_path'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'order' =>  $all['panorama_order'.$val],
                            'company_id' =>  auth()->user()->company_id,
                            'title' =>  $all['panorama_title'.$val],
                            'reins_type' =>  $all['panorama_reins_type'.$val],
                            'type' => config('const.PANORAMA_TYPE_IMAGE'),
                            'del' => 0
                        ];

                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = PortalHomesPanorama::where('id', $article_portal_id)->first();
                            if (!empty($relationArticlePhoto)) {
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            PortalHomesPanorama::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->panorama_del_photo_id)) {

                $list = explode(',', $request->panorama_del_photo_id);
                foreach ($list as $key => $val) {
                    $portalHomesPanorama = PortalHomesPanorama::findOrFail($val);
                    $portalHomesPanorama->update(['del'  =>  1]);
                }
            }
        }

        $panoramaDefault =[
            'article_id' => $article->building_id,
            'name' => $request->panorama_name,
            'public_type' => $request->panorama_public_type,
            'type' => config('const.PANORAMA_TYPE_DEFAULT'),
            'del' => 0,
            'company_id' =>  auth()->user()->company_id,
        ];
        $portalHomesPanoramaDefault = PortalHomesPanorama::ofImage($article->building_id, config('const.PANORAMA_TYPE_DEFAULT'));
        if (!empty($portalHomesPanoramaDefault->first())) {
            $portalHomesPanoramaDefault->update($panoramaDefault);
        } else {
            PortalHomesPanorama::create($panoramaDefault);
        }
    }

    private function saveImageAthome($request, $article) {
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/athome_photo_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('athome_photo_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }

        if (isset($request->id)) {
            if (isset($request->athome_file_input)) {
                $last_order = RelationPortalPhoto::ofImage(null, $request->id, config('const.ATHOME'))->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $article_portal_id = $all['athome_photo_id'.$i];
                    $status = 0;
                    if(isset($all['status' . $i])){
                        $status = $all['status' . $i];
                    }
                    if(isset($request->athome_file_input[$i])) {
                        $num_order++;
                        $photo = $request->athome_file_input[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/athome/image/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'memo' => $all['athome_photo_comment' . $i],
                            'created_at' => $all['athome_photo_created_at' . $i],
                            'order' =>  $all['athome_order' . $i] == '' ? $num_order: $all['athome_order' . $i],
                            'company_id' =>  auth()->user()->company_id,
                            'property_sub' =>  $all['athome_property_sub' . $i],
                            'type' => config('const.ATHOME'),
                            'status'    =>  $status,
                            'facility' => !empty($all['athome_facility' . $i]) ? $all['athome_facility' . $i] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }else{
                        $photo_data = [
                            'memo' => $all['athome_photo_comment' . $i],
                            'created_at' => $all['athome_photo_created_at' . $i],
                            'order' =>  $all['athome_order' . $i] == '' ? $num_order: $all['athome_order' . $i],
                            'property_sub' =>  $all['athome_property_sub' . $i],
                            'status'    =>  $status,
                            'facility' => !empty($all['athome_facility' . $i]) ? $all['athome_facility' . $i] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_portal_id = $all['athome_photo_id'.$val];
                    $file_path = $all['athome_file_path'.$val];
                    $status = 0;
                    if(isset($all['status' . $val])){
                        $status = $all['status' . $val];
                    }
                    if($file_path != ''){
                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $file_path,
                            'memo' => $all['athome_photo_comment'.$val],
                            'created_at' => $all['athome_photo_created_at' . $val],
                            'order' =>  $all['athome_order'.$val],
                            'company_id' =>  auth()->user()->company_id,
                            'property_sub' =>  $all['athome_property_sub'.$val],
                            'type' => config('const.ATHOME'),
                            'status'    =>  $status,
                            'facility' => !empty($all['athome_facility'.$val]) ? $all['athome_facility'.$val] : config('const.TYPE_FACILITY_UPLOAD'),
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                        ];

                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalPhoto::where('id', $article_portal_id)
                                ->where('del','=', 0)->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalPhoto::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->athome_del_photo_id)) {
                $list = explode(',', $request->athome_del_photo_id);
                foreach ($list as $key => $val) {
                    $query = RelationPortalPhoto::where('id', $val)->first();
                    $query->update(['del'  =>  1]);
                }
            }
        }
    }

    private function saveImageAthomeFacility($request, $article) {
        $all = $request->all();
        $user = Auth::user();
        $array_keys = array_keys($all);
        $matched_keys = array_filter(
            $array_keys,
            function ($k) {
                return preg_match("/athome_facility_id[0-9]*/u", $k);
            }
        );
        $tag = [];
        foreach ($matched_keys as $key) {
            $target_key = str_replace('athome_facility_id', '', $key);
            if ($target_key != "") {
                $tag[] = $target_key;
            }

        }
        if (isset($request->id)) {
            if (isset($request->athome_facility_file_input)) {
                $last_order = RelationPortalFacility::where('article_id', $request->id)->where('type', config('const.ATHOME'))->orderBy('order', 'desc')->first();
                $num_order = 0;
                if(!empty($last_order)){
                    $num_order = $last_order->order;
                }
                foreach ($tag as $i){
                    $article_portal_id = $all['athome_facility_id' . $i];
                    if(isset($request->athome_facility_file_input[$i])) {
                        $num_order++;
                        $photo = $request->athome_facility_file_input[$i];
                        $extension = $photo->getClientOriginalExtension();

                        $image = \Image::make($photo->getPathName());
                        $org_height = $image->height();
                        $org_width = $image->width();

                        $rate = 0;
                        $height = 0;
                        $width = 0;
                        if ($org_height > $org_width) {
                            $rate = config('const.MAX_LENGTH') / $org_height;
                            $width = $org_width * $rate;
                            $height = config('const.MAX_LENGTH');

                        } else {
                            $rate = config('const.MAX_LENGTH') / $org_width;
                            $width = config('const.MAX_LENGTH');
                            $height = $org_height * $rate;

                        }
                        $image = \Image::make($photo);
                        $image->orientate();
                        $image_url = 'public/company_'.$user->company_id.'/portal/athome/facility/portal_image_' . $article->building_id . '_' . $i . '.' . $extension;
                        $image->resize($width, null, function ($constraint) {
                            return $constraint->aspectRatio();
                        });
                        $streamedImage = $image->stream();
                        Storage::put($image_url, $streamedImage->__toString());

                        $photo_data = [
                            'article_id' => $article->building_id,
                            'file_path' => $image_url,
                            'file_type' => $extension,
                            'type'      =>  config('const.ATHOME'),
                            'facility_property' => $all['athome_facility_property_sub' . $i],
                            'facility_name' => $all['athome_facility_name' . $i],
                            'distance' => $all['athome_facility_distance' . $i],
                            'facility_memo' => $all['athome_facility_memo' . $i],
                            'order' =>  $all['athome_facility_order' . $i] == '' ? $num_order: $all['athome_facility_order' . $i],
                            'company_id' => auth()->user()->company_id,
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                            'created_at' => $all['athome_facility_created_at' . $i],
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalFacility::where('id', $article_portal_id)->where('type', config('const.ATHOME'))->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalFacility::create($photo_data);
                        }
                    }else{
                        $photo_data = [
                            'facility_property' => $all['athome_facility_property_sub' . $i],
                            'facility_name' => $all['athome_facility_name' . $i],
                            'distance' => $all['athome_facility_distance' . $i],
                            'facility_memo' => $all['athome_facility_memo' . $i],
                            'order' =>  $all['athome_facility_order' . $i],
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                            'created_at' => $all['athome_facility_created_at' . $i],
                        ];
                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalFacility::where('id', $article_portal_id)->where('type', config('const.ATHOME'))->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        }
                    }
                }
            }else{
                foreach ($tag as $val){
                    $article_portal_id = $all['athome_facility_id'.$val];
                    $file_path = $all['athome_facility_file_path'.$val];
                    if($file_path != ''){
                        $photo_data = [
                            'facility_property' => $all['athome_facility_property_sub' . $val],
                            'facility_name' => $all['athome_facility_name' . $val],
                            'distance' => $all['athome_facility_distance' . $val],
                            'facility_memo' => $all['athome_facility_memo' . $val],
                            'order' =>  $all['athome_facility_order' . $val],
                            'type_upload' => config('const.TYPE_UPLOAD_PORTAL'),
                            'created_at' => $all['athome_facility_created_at' . $val],
                        ];

                        if (!empty($article_portal_id)) {
                            $relationArticlePhoto = RelationPortalFacility::where('id', $article_portal_id)->where('type', config('const.ATHOME'))->first();
                            if (!empty($relationArticlePhoto)) {
                                $photo_data['del'] = 0;
                                $relationArticlePhoto->update($photo_data);
                            }
                        } else {
                            RelationPortalFacility::create($photo_data);
                        }
                    }
                }
            }
            if (isset($request->athome_del_facility_id)) {
                $list = explode(',', $request->athome_del_facility_id);
                foreach ($list as $key => $val) {
                    $query = RelationPortalFacility::where('id', $val)->first();
                    $query->update(['del'  =>  1]);
                }
            }
        }
    }

    private function parseData($data) {
        $result = [['code' => '', 'name' => '']];
        foreach ($data as $key => $value) {
            $item = ['code' => $key+1, 'name' => $value];
            array_push($result, $item);
        }
        return $result;
    }
}
