<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Redirector;
use App\Http\Requests\ArticlePost;
use App\Http\Requests\LandPost;
use App\Http\Requests\HousePost;
use App\Http\Requests\MansionPost;
use App\Http\Requests\RoomPost;
use App\Http\Requests\LotPost;
use App\Models\Article;
use App\Models\Facility;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\CustomContent;
use App\Models\MstPropertyType;
use App\Models\MstPropertyTypeSub;
use App\Models\MstStatus;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstSchool;
use App\Models\MstStation;
use App\Models\MstLawrestriction;
use App\Models\MstOtherrestriction;
use App\Models\RelationCitySchool;
use App\Models\MstStore;
use App\Models\MstFloorType;
use App\Models\MstGenkyou;
use App\Models\MstParking;
use App\Models\MstStructure;
use App\Models\MstStructureSub;
use App\Models\MstManner;
use App\Models\MstVendorManner;
use App\Models\MstFacilityType;
use App\Models\MstUseArea;
use App\Models\MstUseDistrict;
use App\Models\MstManagementForm;
use App\Models\MstShared;
use App\Models\MstOtherReason;
use App\Models\RelationVendorArticle;
use App\Models\RelationSpring;
use App\Models\RelationInterior;
use App\Models\RelationExterior;
use App\Models\RelationShared;
use App\Models\RelationLawrestriction;
use App\Models\RelationOtherrestriction;
use App\Models\RelationEventDay;
use App\Models\RelationArticlePhoto;
use App\Models\RelationCustomContent;
use App\Models\RelationArticleFacility;
use App\Models\History;
use App\Models\Vendor;
use Artisan;


class ArticleController extends Controller
{
    private $parentProperty;

    private function getDataSaiKyoto($data)
    {
        $data["pref"] = [
            ["code" => 11, "name" => "京都府"],
  	    ["code" => 12, "name" => "滋賀県"],
        ];
        $data["city"] = [
            ["code" => 100, "name" => "京都市山科区"],
            ["code" => 102, "name" => "京都市伏見区"]
        ];
        $data["town"] = [
            ["code" => 100, "name" => "西野岸ノ下町"],
            ["code" => 101, "name" => "安朱堂ノ後町"],
            ["code" => 102, "name" => "梅林1丁目"],
            ["code" => 103, "name" => "稲葉台"],
            ["code" => 104, "name" => "醍醐僧尊坊町"],
            ["code" => 105, "name" => "安朱馬場ノ東町"],
            ["code" => 106, "name" => "御陵荒巻町"],
            ["code" => 107, "name" => "醍醐古道町"],
            ["code" => 108, "name" => "安朱馬場ノ東町"],
            ["code" => 109, "name" => "音羽山等地"],
            ["code" => 110, "name" => "安朱堂ノ後町"],
            ["code" => 111, "name" => "横木1丁目"],
            ["code" => 112, "name" => "茶戸町"],
            ["code" => 113, "name" => "北花山横田町"],
            ["code" => 114, "name" => "四ノ宮岩久保町"],
            ["code" => 115, "name" => "横木"],
            ["code" => 116, "name" => "安朱堂ノ後町"],
            ["code" => 117, "name" => "四ﾉ宮神田町"]
        ];
        return $data;
    }

    /**
     * 仮登録物件一覧画面の表示
     */
    public function showProvisionalForm(Request $request)
    {
        $user = Auth::user();
        $selected = $user->store_id;


        $params = $request->all();
        
        if(isset($params['store']) && !empty($params['store'])) {
            $store_info = MstStore::getDataByCode($user->company_id, $params['store']);
            if(is_null($store_info)) {
                print('不正なアクセスです。');
                exit;
            }
            $selected = $params['store'];
            $data['uri'] = '?store='.$params['store'];
        }

        $data = [];
        $article = Article::getProvisionalData($user->company_id, 20, $selected);
        foreach($article as &$row) {
            $mansion = Article::getParentMansion($user->company_id, $row->mansion_id);
            $row->mansion_info = $mansion;
        }

        // 表示中のページの最初のアイテムのインデックス番号
        $first = $article->firstItem();
        
        // 表示中のページの最後のアイテムのインデックス番号
        $last = $article->lastItem();
        
        $data['article'] = $article;
        $data['first'] = $first;
        $data['last'] = $last;
        // 店舗一覧
        $data['store'] = MstStore::getDataAll($user->company_id);
        $data['selected_store'] = $selected;
        $data['pager_params'] = ['store' => $selected];
        return view('admin.pages.provisional', $data);
    }
    
    /**
     * 土地情報ー新規登録画面の表示
     */
    public function showRegistrationLandForm(Request $request)
    {
        $old = $request->session()->all();
        // マスターデータの取得
        $this->parentProperty = 1;
        $data = $this->getMasterData(null, null, $old, 1);

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
        if ($user->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-land', $data);
    }
    
    /**
     * 土地情報ー新規登録
     */
    public function registerLand(LandPost $request)
    {
        $this->parentProperty = 1;

        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        
        $all['building_id'] = $building_id+1;
        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        }
        $all['provisional'] = 0; 

        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * 土地情報ー編集登録画面の表示
     */
    public function showEditLandForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 1;
        $article = $this->getDataById($request->id);
        if(isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 1);
        $data['article'] = $article;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved??'';
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.edit-land', $data);
    }
    
    /**
     * 土地情報ー編集登録
     */
    public function editLand(LandPost $request)
    {
        $user = Auth::user();

        // 保存せずに画像編集画面へ
        if($request->toimage == 1) {
            $URL = url('');
            header('Location: '.$URL.'/admin/registImage/'.$request->id);
            die();
        }

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        $all = $request->all();

        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        
        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 

        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            $data = [];
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 土地情報ー編集登録画面の表示
     */
    public function showCopyLandForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 1;
        $article = $this->getDataById($request->copy);
        if($article->property != 99) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }
        
        $article->sale_no = $article->building_id;
        $article->sale_name = $article->article_name;
        $article->building_id = null;
        $article->article_name = null;
        
        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 1);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-land', $data);
    }

    /**
     * 土地情報ー新規登録
     */
    public function registerCopyLand(LandPost $request)
    {
        $this->parentProperty = 1;

        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        
        $all['building_id'] = $building_id+1;
        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        }
        $all['provisional'] = 0; 

        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }
            
            $data = [];
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    


    /**
     * 戸建情報ー新規登録画面の表示
     */
    public function showRegistrationHouseForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 2;
        $data = $this->getMasterData(null, 2, $old, 2);

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
	if ($user->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-house', $data);
    }
    
    /**
     * 戸建情報ー新規登録
     */
    public function registerHouse(HousePost $request)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        $article = new Article;
        $all = $request->all();
        $all['building_id'] = $building_id+1; 

        if(!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if(!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if(!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if(!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if(!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 
        
        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            if(isset($request->exterior_place)) {
                foreach($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if(isset($request->interior_place)) {
                foreach($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 戸建情報ー編集登録画面の表示
     */
    public function showEditHouseForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 2;

        $article = $this->getDataById($request->id);

        if(isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }
        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 2);
        $data['article'] = $article;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved??'';
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.edit-house', $data);
    }
    
    /**
     * 戸建情報ー編集登録
     */
    public function editHouse(HousePost $request)
    {
        $user = Auth::user();

        // 保存せずに画像編集画面へ
        if($request->toimage == 1) {
            $URL = url('');
            header('Location: '.$URL.'/admin/registImage/'.$request->id);
            die();
        }

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        $all = $request->all();

        if(!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if(!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if(!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if(!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if(!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 

        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

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

            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            RelationExterior::where('article_id', $request->id)->delete();
            if(isset($request->exterior_place)) {
                foreach($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            RelationInterior::where('article_id', $request->id)->delete();
            if(isset($request->interior_place)) {
                foreach($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }

            // 施設削除
            $del_facility_list = explode(',', $request->delete_facility_list);

            foreach($del_facility_list as $del_id) {
                RelationArticleFacility::where('article_id', '=', $article->building_id)->where('facility_id', $del_id)->delete();
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

        /**
     * 戸建情報ー編集登録画面の表示
     */
    public function showCopyHouseForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 2;

        $article = $this->getDataById($request->copy);
        if($article->property != 99) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        $article->sale_no = $article->building_id;
        $article->sale_name = $article->article_name;
        $article->building_id = null;
        $article->article_name = null;

        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 2);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-house', $data);
    }

        /**
     * 戸建情報ー新規登録
     */
    public function registerCopyHouse(HousePost $request)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        $article = new Article;
        $all = $request->all();
        $all['building_id'] = $building_id+1; 

        if(!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if(!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if(!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if(!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if(!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if(!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if(!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if(!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 
        
        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            if(isset($request->exterior_place)) {
                foreach($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if(isset($request->interior_place)) {
                foreach($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    
    /**
     * マンション検索
     */
    public function showTopMansionForm(Request $request)
    {
	$user = $request->user();
        $old = $request->session()->all();
        $params = $request->all();

        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData(null, null, $old, 3);
        $data['active'] = "top";

        if(!empty($request->all())) {
            $mansion_list = Article::getMansionList($request, 20);
            foreach($mansion_list as &$mansion) {
                $room_list = Article::getRoomList($mansion->building_id);
                $mansion->room_list = $room_list;
                $mansion->room_count = count($room_list);
                foreach($room_list as &$room) {
                    $vendor = Vendor::getDataByArticleId($room->building_id);
                    $room->vendor = $vendor->name??'';
                    $room->vendor_tel = $vendor->vendor_tel??'';
                    $room->floor_plan_name = MstFloorType::find($room->floor_plan_type)->name??'';
                    $room->status_name = MstStatus::find($room->status)->name??'';
                    $vendor = RelationVendorArticle::getVendorDataByRainsNo($room->buiding_id);
                }

            }
            // 表示中のページの最初のアイテムのインデックス番号
            $first = $mansion_list->firstItem();

            // 表示中のページの最後のアイテムのインデックス番号
            $last = $mansion_list->lastItem();

            $data['list'] = $mansion_list;
            $data['first'] = $first;
            $data['last'] = $last;
        }

        // 都道府県マスターを取得
        $data['pref'] = MstPrefecture::getData(null, $user->company_id);
        $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $data['town'] = [];
        if($request->search_address2) {
            $data['town'] = MstTown::getData($request->search_address1, $request->search_address2);
        }

        $data['params'] = $params;
        
        return view('admin.pages.top-mansion', $data);
    }

    /**
     * マンション情報ー新規登録画面の表示
     */
    public function showRegistrationMansionForm(Request $request)
    {
        $old = $request->session()->all();
        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData(null, null, $old, 3);
        $data['active'] = "regist";

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-mansion', $data);
    }
    
    /**
     * マンション情報ー新規登録
     */
    public function registerMansion(MansionPost $request)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }
        
        $article = new Article;

        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0; 
        $all['first'] = 1; 
        $all['building_id'] = $building_id+1; 
        unset($all['_token']);
        $all['name_apartment'] = $all['name'];
        $result = $article->fill($all)->save();
        $saved_id = $article->building_id;

        if(isset($article->building_id)) {
            // 共用部
            if(isset($request->shared)) {
                foreach($request->shared as $row) {
                    RelationShared::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditMansion', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showEditMansionForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 3;

        $article = $this->getDataById($request->id);

        $room = Article::getDataByRoom($article->building_id);
        foreach($room as &$row) {
            $row->floor_plan_name = MstFloorType::find($row->floor_plan_type)->name??'';
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 3);
        $data['article'] = $article;
        $data['room'] = $room;
        $data['saved'] = $request->saved??'';
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.edit-mansion', $data);
    }
    
    /**
     * マンション情報ー編集登録
     */
    public function editMansion(MansionPost $request)
    {
        $user = Auth::user();

        // 保存せずに画像編集画面へ
        if($request->toimage == 1) {
            $URL = url('');
            header('Location: '.$URL.'/admin/registImage/'.$request->id);
            die();
        } elseif(isset($request->toroom)) {
            $URL = url('');
            header('Location: '.$URL.'/admin/editRoom/'.$request->id.'/'.$request->toroom);
            die();
        }

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0; 
        $all['first'] = 1;
        $all['name_apartment'] = $all['name'];
        $result = $article->fill($all)->save();

        if(isset($request->id)) {
            // 共用部
            RelationShared::where('company_id', '=', $user->company_id)->where('article_id', $request->id)->delete();
            if(isset($request->shared)) {
                foreach($request->shared as $row) {
                    RelationShared::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            $URL = url('');
            if($request->room == 1) {
                header('Location: '.$URL.'/admin/registRoom/'.$request->id);
                die();
            } else {
                $data = [];
                $data['action'] = route('showEditMansion', ['id' => $article->building_id]);
                return view('admin.pages.redirect', $data);
            }
            
        }
    }

        /**
     * マンション情報ー新規登録画面の表示
     */
    public function showRegistrationRoomForm(Request $request)
    {
        $user = Auth::user();
        $old = $request->session()->all();
        // マンションデータの取得
        $article = $this->getDataById($request->id);
        $article->own_company = 1;
        if($article->property != 6 && $article->property != 7) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }
        // 共用部
        $shared_text = "";
        
        $checked_shared = RelationShared::getDataByArticleId($user->company_id, $article->building_id);
        if(count($checked_shared) > 0) {
            foreach($checked_shared as $row) {
                $shared_item = MstShared::getName($row);
                if($shared_text != "") {
                    $shared_text .= " / ";
                }
                $shared_text .= $shared_item->name;
            }    
        }
        $article->shared_text = $shared_text;


        // 学校データの取得
        $disp_school = "";
        if(isset($article->primary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->primary_school_school);
            $article->primary_school_name = $school_tmp->name;
            if(isset($article->primary_school_distance)) {
                $article->primary_school_time = ceil($article->primary_school_distance / 80);
            }

        }
        if(isset($article->primary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->primary_school2_school);
            $article->primary_school_name2 = $school_tmp->name;
            if(isset($article->primary_school2_distance)) {
                $article->primary_school_time2 = ceil($article->primary_school2_distance / 80);
            }

        }

        if(isset($article->secondary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->secondary_school_school);
            $article->secondary_school_name = $school_tmp->name;
            if(isset($article->secondary_school_distance)) {
                $article->secondary_school_time = ceil($article->secondary_school_distance / 80);
            }
        }
        if(isset($article->secondary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->secondary_school2_school);
            $article->secondary_school_name2 = $school_tmp->name;
            if(isset($article->secondary_school2_distance)) {
                $article->secondary_school_time2 = ceil($article->secondary_school2_distance / 80);
            }
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 3);
        $data['article'] = $article;

        return view('admin.pages.regist-room', $data);
    }
    
    /**
     * マンション情報ー新規登録
     */
    public function registerRoom(RoomPost $request)
    {

        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }
        
        // 登録
        $article = new Article;
        $all = $request->all();
        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['maisonette'])) {
            $all['maisonette'] = 0;
        }
        $all['company_id'] = $user->company_id;
        $all['building_id'] = $building_id+1;
        $all['mansion_id'] = $request->id;
        if($all['own_company'] == 2) {
            $all['disp'] = 1;
            // 親マンションも本登録
            Article::where('building_id', $request->id)->where('company_id', '=', $user->company_id)->update(['provisional' => 0, 'own_company' => 2]);
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 

        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }
        

        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if(isset($request->interior_place)) {
                foreach($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditRoom', ['mid' => $request->id,'id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showEditRoomForm(Request $request)
    {
        $user = Auth::user();
        $old = $request->session()->all();
        $this->parentProperty = 3;

        $mansion = $this->getDataById($request->mid);
        $article = $this->getDataById($request->id);
        $mansion->shop = $article->shop;

        // マスターデータの取得
        $data = $this->getMasterData($mansion, null, $old, 3);

        // 共用部
        $shared_text = "";
        
        $checked_shared = RelationShared::getDataByArticleId($user->company_id, $mansion->building_id);
        if(count($checked_shared) > 0) {
            foreach($checked_shared as $row) {
                $shared_item = MstShared::getName($row);
                if($shared_text != "") {
                    $shared_text .= " / ";
                }
                $shared_text .= $shared_item->name;
            }    
        }
        $mansion->shared_text = $shared_text;

        $spring_kind = [
            ['code' => 1, 'name' => '加温'],
            ['code' => 2, 'name' => '加水'],
            ['code' => 3, 'name' => '運び湯'],
            ['code' => 4, 'name' => '循環装置使用'],
            ['code' => 5, 'name' => '循環ろ過装置使用'],
        ];
        $checked_spring = RelationSpring::getDataByArticleId($user->company_id, $article->building_id);

        if(count($checked_spring) > 0) {
            foreach($spring_kind as &$row) {
                if(in_array($row['code'], $checked_spring)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['spring_kind'] = $spring_kind;

        $interior = [
            ['code' => '1', 'name' => 'キッチン'],
            ['code' => '2', 'name' => '浴室'],
            ['code' => '3', 'name' => 'トイレ'],
            ['code' => '4', 'name' => '壁'],
            ['code' => '5', 'name' => '床'],
            ['code' => '6', 'name' => '全室'],
            ['code' => '7', 'name' => 'その他'],
        ];
        $checked_interior = RelationInterior::getDataByArticleId($user->company_id, $article->building_id);

        if(count($checked_interior) > 0) {
            foreach($interior as &$row) {
                if(in_array($row['code'], $checked_interior)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['interior'] = $interior;


        // 学校データの取得
        $disp_school = "";
        // 学校データの取得
        $disp_school = "";
        if(isset($mansion->primary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school_school);
if(request()->get("debug")) {dd($mansion->primary_school_school);}
            $mansion->primary_school_name = $school_tmp->name;
            if(isset($mansion->primary_school_distance)) {
                $mansion->primary_school_time = ceil($mansion->primary_school_distance / 80);
            }
        }
        if(isset($mansion->primary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school2_school);
            $mansion->primary_school_name2 = $school_tmp->name;
            if(isset($mansion->primary_school2_distance)) {
                $mansion->primary_school_time2 = ceil($mansion->primary_school2_distance / 80);
            }
        }
 
        if(isset($mansion->secondary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school_school);
            $mansion->secondary_school_name = $school_tmp->name;
            if(isset($mansion->secondary_school_distance)) {
                $mansion->secondary_school_time = ceil($mansion->secondary_school_distance / 80);
            }
        }
        if(isset($mansion->secondary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school2_school);
            $mansion->secondary_school_name2 = $school_tmp->name;
            if(isset($mansion->secondary_school2_distance)) {
                $mansion->secondary_school_time2 = ceil($mansion->secondary_school2_distance / 80);
            }
        }

        $data['mansion'] = $mansion;
        $data['article'] = $article;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved??'';


        return view('admin.pages.edit-room', $data);
    }
    
    /**
     * マンション情報ー編集登録
     */
    public function editRoom(RoomPost $request)
    {
        $user = Auth::user();

        // 保存せずに画像編集画面へ
        if($request->toimage == 1) {
            $URL = url('');
            header('Location: '.$URL.'/admin/registImage/'.$request->id);
            die();
        }

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        $all = $request->all();
        if(!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if(!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if(!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if(!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if(!isset($all['maisonette'])) {
            $all['maisonette'] = 0;
        }
        if($all['own_company'] == 2) {

            $all['disp'] = 1;
            
            // 親マンションも本登録
            Article::where('building_id', $request->mid)->where('company_id', '=', $user->company_id)->update(['provisional' => 0, 'own_company' => 2]);
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0; 
        
        if($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }
        
        if($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if(isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            RelationInterior::where('article_id', $request->id)->delete();
            if(isset($request->interior_place)) {
                foreach($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach($vendor_list as $key => $val) {
                if(empty($val)) {
                    continue;
                }
                
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if(is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                    
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }          
            }
        }
        if($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }
        if($article->homes == 2) {
            // Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if($result) {
            $data = [];
            $data['action'] = route('showEditRoom', ['mid' => $request->mid,'id' => $request->id]);
            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showTopLotForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData($request->all(), null, $old, 4);
        $data['active'] = "top";
        $data['search'] = $request->all();


        if(!empty($request->all())) {

            $list = Article::getLotDataByCondition($request);
            foreach($list as &$row) {
                $row->count = Article::getCountBySaleNo($row->building_id);

                $row->relation_article = Article::getDataBySaleNo($row->building_id);
                foreach($row->relation_article as $info) {
                    $vendor = Vendor::getDataByArticleId($info->building_id);
                    $info->vendor = $vendor->name??'';
                    if($info->property == 1) {
						$info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 2) {
                        $info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 3) {
                        $info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 4) {
                        $info->url = '/admin/editHouse/'.$info->building_id;
                    } elseif($info->property == 5) {
                        $info->url = '/admin/editHouse/'.$info->building_id;
                    }

                    if(isset($info->status)) {
                        $info->status_name = MstStatus::find($info->status)->name??'';
                    }
                }
            }
            $data['list'] = $list;
        }
        return view('admin.pages.top-lot', $data);
    }

       /**
     * マンション情報ー編集登録画面の表示
     */
    public function showPostTopLotForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData($request->all(), null, $old, 4);
        $data['active'] = "top";
        $data['search'] = $request->all();


        if(!empty($request->all())) {

            $list = Article::getLotDataByCondition($request);
            foreach($list as &$row) {
                $row->count = Article::getCountBySaleNo($row->building_id);

                $row->relation_article = Article::getDataBySaleNo($row->building_id);
                foreach($row->relation_article as $info) {
                    $vendor = Vendor::getDataByArticleId($info->building_id);
                    $info->vendor = $vendor['name'];
                    if($info->property == 1) {
						$info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 2) {
                        $info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 3) {
                        $info->url = '/admin/editLand/'.$info->building_id;
                    } elseif($info->property == 4) {
                        $info->url = '/admin/editHouse/'.$info->building_id;
                    } elseif($info->property == 5) {
                        $info->url = '/admin/editHouse/'.$info->building_id;
                    }

                    if(isset($info->status)) {
                        $info->status_name = MstStatus::find($info->status)->name??'';
                    }
                }
            }
            $data['list'] = $list;
        }
        return view('admin.pages.top-lot', $data);
    }

    /**
     * 分譲地情報ー新規登録画面の表示
     */
    public function showRegistrationLotForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 4;
        $data = $this->getMasterData(null, null, $old, 4);
        $data['active'] = "regist";

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-lot', $data);
    }
    
    /**
     * 分譲地情報ー新規登録
     */
    public function registerLot(LotPost $request)
    {
        $this->parentProperty = 4;

        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }
        
        // 登録
        $article = new Article;
        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0; 
        $all['building_id'] = $building_id+1; 
        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 温泉
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }
        }

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }
            
            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 分譲地情報ー編集登録画面の表示
     */
    public function showEditLotForm(Request $request)
    {
        $old = $request->session()->all();
        
        $this->parentProperty = 4;

        $article = $this->getDataById($request->id);

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 4);
        $data['article'] = $article;
        $data['saved'] = $request->saved??'';
	if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.edit-lot', $data);
    }
    
    /**
     * 分譲地情報ー編集登録
     */
    public function editLot(LotPost $request)
    {
        $user = Auth::user();

        // 保存せずに画像編集画面へ
        if($request->toimage == 1) {
            $URL = url('');
            header('Location: '.$URL.'/admin/registImage/'.$request->id);
            die();
        }

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0; 
        $result = $article->fill($all)->save();

        if(isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if(isset($request->spring_kind)) {
                foreach($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            
            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if(isset($request->law_restriction)) {
                foreach($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if(isset($request->other_restriction)) {
                foreach($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if(isset($request->event_day)) {
                foreach($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }      
        }

        if($result) {
            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

/**
     * 分譲地情報ー編集登録画面の表示
     */
    public function showCopyLotForm(Request $request)
    {
        $old = $request->session()->all();
        
        $this->parentProperty = 4;

        $article = $this->getDataById($request->copy);

        if($article->property != 1 && $article->property != 2 && $article->property != 3 && 
        $article->property != 4 && $article->property != 5) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        $article->building_id = null;
        $article->article_name = null;

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 4);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-lot', $data);
    }

    public function copyLot(LotPost $request)
    {
        $this->parentProperty = 4;

        $user = Auth::user();
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0; 
        $all['building_id'] = $building_id+1; 
        $result = $article->fill($all)->save();

        if(isset($article->building_id)) {
            // 元の物件をこの分譲地に登録
            Article::where('building_id', $request->copy)->where('company_id', '=', $user->company_id)->update(['sale_no' => $article->building_id]);

        }

        if($result) {
            // 保存して画像編集画面へ
            if($request->toimage == 1) {
                $URL = url('');
                header('Location: '.$URL.'/admin/registImage/'.$article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }



/**
     * 画像情報ー編集登録画面の表示
     */
    public function showRegistrationImageForm(Request $request)
    {
        $user = Auth::user();
        $data = [];

        $article = $this->getDataById($request->id);
        $referer = $_SERVER['HTTP_REFERER']??null;

        if(isset($request->referer)) {
            $referer = $request->referer;
        }
        $article = $this->getDataById($request->id);

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

        if(is_null($referer) || (
            strpos($referer, route('showRegistLand')) === false && strpos($referer, route('showEditLand', ['id' => $request->id])) === false && 
            strpos($referer, route('showRegistHouse')) === false && strpos($referer, route('showEditHouse', ['id' => $request->id])) === false && 
            strpos($referer, route('regist-mansion')) === false && strpos($referer, route('showEditMansion', ['id' => $request->id])) === false && 
            strpos($referer, route('regist-room', ['id' => $article->mansion_id])) === false && strpos($referer, route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $request->id])) === false && 
            strpos($referer, route('regist-lot')) === false && strpos($referer, route('showEditLot', ['id' => $request->id])) === false && 
            strpos($referer, route('showCopyLand')) === false && strpos($referer, route('showCopyHouse')) === false && 
            strpos($referer, route('copy-lot')) === false && strpos($referer, route('showRegistImage', ['id' => $request->id])) === false)) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        $data['back'] = $back;
        $data['referer'] = $referer;
        $data['saved'] = $request->saved??'';
        
        $old = $request->session()->all();

        
        $data['article'] = $article;

        $property_name = $this->getPropertyName($article->property, $article->property_sub);
        $title = "物件登録-".$property_name."-画像登録「{$article->article_name}」";
        $data['main_title'] = $title;

        $disp_flag = 1;
        if($article->property == 6 || $article->property == 7) {
            $disp_flag = 2;
        } else if($article->property == 99) {
            $disp_flag = 3;
        }

        $data['disp_flag'] = $disp_flag;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach($facility as &$row){
            $row->kind_name = MstFacilityType::find($row->kind)->name??'';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $data['image_kind'] = [
            ['code' => 1, 'name' => '区画図'],
            ['code' => 2, 'name' => '間取り'],
            ['code' => 3, 'name' => '参考プラン'],
            ['code' => 0, 'name' => '未選択'],
        ];

        if($article->property == 6 || $article->property == 7) {
            $data['photo_property'] = [
                ['code' => 3, 'name' => '外観'],
                ['code' => 4, 'name' => '内観'],
            ];
        } else {
            $data['photo_property'] = [
                ['code' => 1, 'name' => '屋外'],
                ['code' => 2, 'name' => '室内'],
            ];
        }

        
        // イベント予約
        $data['vendor_building_photo'] = [
            ['code' => 1, 'name' => '優先使用'],
            ['code' => 2, 'name' => '不使用'],
        ];

        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;

        $data['facility_property'] = MstFacilityType::getData();
        $data['facility_distance'] = [
            ['code'=> 0, 'name' => 0],
            ['code'=> 5, 'name' => 5],
            ['code'=> 10, 'name' => 10],
            ['code'=> 15, 'name' => 15],
            ['code'=> 20, 'name' => 20],
            ['code'=> 25, 'name' => 25],
            ['code'=> 30, 'name' => 30],
            ['code'=> 35, 'name' => 35],
            ['code'=> 40, 'name' => 40],
            ['code'=> 45, 'name' => 45],
            ['code'=> 50, 'name' => 50],
            ['code'=> 55, 'name' => 55],
            ['code'=> 60, 'name' => 60],
            ['code'=> 65, 'name' => 65],
        ];

        return view('admin.pages.edit-image', $data);
    }

    /**
     * 土地情報ー編集登録
     */
    public function registImage(Request $request)
    {
        $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();

        Article::where('building_id', $request->id)->where('company_id', '=', $user->company_id)->update(['floor_file_type' => $request->floor_file_type, 'sheet_file_type' => $request->sheet_file_type]);

        if(isset($request->id)) {
            // 間取り画像
            if(isset($request->floor_file_delete_flg)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['floor_file_path' => '']);
            }
            if(isset($request->file_single_input)) {
                $extension = $request->file_single_input->getClientOriginalExtension();
                $image_url = $request->file_single_input->storeAs('public/floor', 'floor_image_'.$article->building_id.'.'. $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['floor_file_path' => $image_url]);
            }

            // 間取り画像
            if(isset($request->floor_file_delete_flg2)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path2' => '']);
            }
            if(isset($request->file_single_input2)) {
                $extension = $request->file_single_input2->getClientOriginalExtension();
                $image_url = $request->file_single_input2->storeAs('public/sheet', 'sheet_image_'.$article->building_id.'.'. $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path2' => $image_url]);
            }

            // 間取り画像
            if(isset($request->floor_file_delete_flg3)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path3' => '']);
            }
            if(isset($request->file_single_input3)) {
                $extension = $request->file_single_input3->getClientOriginalExtension();
                $image_url = $request->file_single_input3->storeAs('public/sheet', 'sub_sheet_image_'.$article->building_id.'.'. $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path3' => $image_url]);
            }

            // 写真
            $this->updateImage($request, $article);

            // 施設削除
            $del_facility_list = explode(',', $request->delete_facility_list);

            foreach($del_facility_list as $del_id) {
                RelationArticleFacility::where('article_id', '=', $article->building_id)->where('facility_id', $del_id)->delete();
            }

            // 施設登録
            $facility_id_list = $request->save_facility_id??[];
            foreach($facility_id_list as $key => $value) {
                if(is_null($value)) {
                    continue;
                }
                $relation = RelationArticleFacility::getArticleRelation($article->building_id, $value);
                $facility = [];
                $facility['article_id'] = $article->building_id;
                $facility['facility_id'] = $value;
                $facility['distance'] = $request->save_facility_distance[$key];
                $facility['time'] = ceil($request->save_facility_distance[$key] / 80);
                if(is_null($relation)) {
                    $facility_obj = new RelationArticleFacility;
                    $facility_obj->fill($facility)->save();
                    
                } else {
                    RelationArticleFacility::where('id', $relation->id)->update($facility);
                }  
            }
        }

        $user = Auth::user();
        $history_data = [
            'company_id' => $user->company_id,
            'name' => '物件番号'.$article->building_id."を更新しました。",
        ];
        $history = new History;
        $history->fill($history_data)->save();

        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;

        $data = [];
        $data['action'] = route('showRegistImage', ['id' => $article->building_id]);
        $data['referer'] = $request->referer;
        return view('admin.pages.redirect', $data);
    }




    public 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 getMasterData($article_data = null, $type = null, $old = null, $property = null) {
        $user = Auth::user();

        $data = [];

        // 独自項目
        $custom = CustomContent::getData($user->company_id); 

        // 種別
        if($this->parentProperty < 4) {
            $data['property'] = MstPropertyType::getDataByParentId($this->parentProperty);
            $data['property_sub'] = MstPropertyTypeSub::getData();
        }
        
        // ステータス
        $data['statuses'] = MstStatus::getData();

        // 取引態様
        $data['manner'] = MstManner::getData();

        // 都道府県マスターを取得

        if(isset($old['_old_input'])) {
            $data['pref'] = MstPrefecture::getData();
            $data['city'] = MstCity::getData($old['_old_input']['address1']);
            $data['town'] = MstTown::getData($old['_old_input']['address1'], $old['_old_input']['address2']);
            $stown = RelationCitySchool::getCityListByCityId($old['_old_input']['address1'].$old['_old_input']['address2']);
            $sres = [];
            foreach($stown as $row) {
                $sres[] = ['code' => $row->name, 'name' => $row->name];
            }
            $data['school_town'] = $sres;

            if(empty($old['_old_input']['primary_school_city'])) {
                $data['primary_school_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($old['_old_input']['primary_school_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school_list'] = $pschool;
            }

            if(empty($old['_old_input']['primary_school2_city'])) {
                $data['primary_school2_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($old['_old_input']['primary_school2_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school2_list'] = $pschool;
            }

            if(empty($old['_old_input']['primary_school3_city'])) {
                $data['primary_school3_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($old['_old_input']['primary_school3_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school3_list'] = $pschool;
            }

            if(empty($article_data['secondary_school_city'])) {
                $data['secondary_school_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($old['_old_input']['secondary_school_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school_list'] = $sschool;
            }
            if(empty($article_data['secondary_school2_city'])) {
                $data['secondary_school2_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($old['_old_input']['secondary_school2_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school2_list'] = $sschool;
            }
            if(empty($article_data['secondary_school3_city'])) {
                $data['secondary_school3_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($old['_old_input']['secondary_school3_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school3_list'] = $sschool;
            }
        
        } else if(empty($article_data)) {
            $data['pref'] = MstPrefecture::getData();
            $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
            $data['town'] = [];
        } else {
            $data['pref'] = MstPrefecture::getData();
            $data['city'] = MstCity::getData($article_data['address1']);
            $data['town'] = MstTown::getData($article_data['address1'], $article_data['address2']);
            $stown = RelationCitySchool::getCityListByCityId($article_data['address1'].$article_data['address2']);
            $sres = [];
            foreach($stown as $row) {
                $sres[] = ['code' => $row->name, 'name' => $row->name];
            }
            $data['school_town'] = $sres;

            if(empty($article_data['primary_school_city'])) {
                $data['primary_school_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($article_data['primary_school_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school_list'] = $pschool;
            }

            if(empty($article_data['primary_school2_city'])) {
                $data['primary_school2_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($article_data['primary_school2_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school2_list'] = $pschool;
            }

            if(empty($article_data['primary_school3_city'])) {
                $data['primary_school3_list'] = [];
            } else {
                $pschool = [];
                $schools = RelationCitySchool::getDataElementarySchool($article_data['primary_school3_city']);
                if(!empty($schools)) {
                    $pschool = MstSchool::getSchoolName($schools);
                }
                $data['primary_school3_list'] = $pschool;
            }

            if(empty($article_data['secondary_school_city'])) {
                $data['secondary_school_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($article_data['secondary_school_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school_list'] = $sschool;
            }

            if(empty($article_data['secondary_school2_city'])) {
                $data['secondary_school2_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($article_data['secondary_school2_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school2_list'] = $sschool;
            }

            if(empty($article_data['secondary_school3_city'])) {
                $data['secondary_school3_list'] = [];
            } else {
                $sschool = [];
                $schools = RelationCitySchool::getDataJuniorSchool($article_data['secondary_school3_city']);
                if(!empty($schools)) {
                    $sschool = MstSchool::getSchoolName($schools);
                }
                $data['secondary_school3_list'] = $sschool;
            }
            
        }

        // 取扱店の取得
        $shops = MstStore::getDataAll($user->company_id);
        $data['shops'] = $shops;

        // 学校のエリア取得
        $schoolTown = RelationCitySchool::getCityList();

        $arr = [];
        foreach($schoolTown as $town) {
            $arr[] = ['code' => $town->name, 'name' => $town->name];
        }
        $data['school_area'] = $arr;

        // 構造
        $construction = [['code' => 0, 'name' => '未選択']];
        $tmp_construction = MstStructure::getData();
        foreach($tmp_construction as $row) {
            $construction[] = $row;
        }
        $data['construction'] = $construction;

        $arr_construction = [];
        foreach($data['construction'] as $row) {
            $arr_construction[$row['code']] = $row['name'];
        }
        $data['arr_construction'] = $arr_construction;

        $data['construction_sub'] = MstStructureSub::getData();
        $arr_construction_sub = [];
        foreach($data['construction_sub'] as $row) {
            $arr_construction_sub[$row['code']] = $row['name'];
        }
        $data['arr_construction_sub'] = $arr_construction_sub;

        $data['floor'] = [
            ['code' => 0, 'name' => 1],
            ['code' => 1, 'name' => 1],
            ['code' => 2, 'name' => 2],
            ['code' => 3, 'name' => 3],
            ['code' => 4, 'name' => 4],
            ['code' => 5, 'name' => 5],
            ['code' => 6, 'name' => 6],
            ['code' => 7, 'name' => 7],
            ['code' => 8, 'name' => 8],
            ['code' => 9, 'name' => 9],
            ['code' => 10, 'name' => 10],
            ['code' => 11, 'name' => 11],
            ['code' => 12, 'name' => 12],
            ['code' => 13, 'name' => 13],
            ['code' => 14, 'name' => 14],
            ['code' => 15, 'name' => 15],
        ];
        

        $management_form = MstManagementForm::getData();
        array_push($management_form, ['code' => 0, 'name' => '未設定']);
        $data['management_form'] = $management_form;
        $arr_management_form = [];
        foreach($data['management_form'] as $row) {
            $arr_management_form[$row['code']] = $row['name'];
        }
        $data['arr_management_form'] = $arr_management_form;

        // 間取り
        $floor_plan = [];
        for($i = 1; $i < 11; $i++) {
            $floor_plan[] = ['code' => $i, 'name' => $i];

        }
        $data['floor_plan'] = $floor_plan;
        $data['floor_type'] = MstFloorType::getData();

        //　完成時期
        $comp_start = config('const.COMP_YEAR_START');
        $comp_end = date('Y') + config('const.COMP_YEAR');
        $comp_year = [];
        for($i = $comp_start; $i <= $comp_end; $i++) {
            $comp_year[] = ['code' => $i, 'name' => $i];
        }
        $data['comp_year'] = $comp_year;

        // 引き渡し
        $data['move_in'] = [
            ['code' => 1, 'name' => '即引き渡し可', 'add_text' => '検索', 'add_class' => ''],
            ['code' => 2, 'name' => '相談'],
            ['code' => 3, 'name' => '指定有'], 
            ['code' => 4, 'name' => '契約後'],
            ['code' => 0, 'name' => '未選択'],
        ];

        $data['reform'] = [
            ['code' => 1, 'name' => '無'],
            ['code' => 2, 'name' => '済'],
            ['code' => 3, 'name' => '完了予定'],
        ];


        // 現況
        if($property != 4) {
            $data['genkyou'] = MstGenkyou::getDataByProperty($property);
        } else {
            $data['genkyo'] = [];
        }
        

        // 駐車場
        if(is_null($type)) {
            $data['parking'] = [];
        } else {
            $parking = MstParking::getDataByType($type);
            array_push($parking, ['code' => 0, 'name' => '未設定']);
            $data['parking'] = $parking;
        }
        

        $data['pet'] = [
            ['code' => 0, 'name' => '未設定'],
            ['code' => 1, 'name' => '不可'],
            ['code' => 2, 'name' => '可（制限あり）'],
        ];
        $arr_pet = [];
        foreach($data['pet'] as $row) {
            $arr_pet[$row['code']] = $row['name'];
        }
        $data['arr_pet'] = $arr_pet;

        
        $data['pet_num'] = [
            ['code' => 0, 'name' => '未設定'],
            ['code' => 1, 'name' => 1],
            ['code' => 2, 'name' => 2],
            ['code' => 3, 'name' => 3],
            ['code' => 4, 'name' => 4],
            ['code' => 5, 'name' => 5],
        ];

       

        $data['other_reason'] = MstOtherReason::getData();


        // リフォーム
                
        $interior = [
            ['code' => '1', 'name' => 'キッチン'],
            ['code' => '2', 'name' => '浴室'],
            ['code' => '3', 'name' => 'トイレ'],
            ['code' => '4', 'name' => '壁'],
            ['code' => '5', 'name' => '床'],
            ['code' => '6', 'name' => '全室'],
            ['code' => '7', 'name' => 'その他'],
        ];

        $exterior = [
            ['code' => '1', 'name' => '外壁'],
            ['code' => '2', 'name' => '屋根'],
            ['code' => '3', 'name' => 'その他'],
        ];

        $spring_kind = [
            ['code' => 1, 'name' => '加温'],
            ['code' => 2, 'name' => '加水'],
            ['code' => 3, 'name' => '運び湯'],
            ['code' => 4, 'name' => '循環装置使用'],
            ['code' => 5, 'name' => '循環ろ過装置使用'],
        ];


        // 制限事項
        $law = MstLawrestriction::getData();
        $other = MstOtherrestriction::getData();
        $shared = MstShared::getData();

        $checked_shared = [];
        $checked_interior = [];
        $checked_exterior = [];
        $checked_spring = [];
        $checked_law = [];
        $checked_other = [];


        if(isset($old['_old_input']['shared'])) {
            $checked_shared = $old['_old_input']['shared'];
        } elseif(isset($article_data->article_id)) {
            $checked_shared = RelationShared::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if(isset($old['_old_input']['interior_place'])) {
            $checked_interior = $old['_old_input']['interior_place'];
        } elseif(isset($article_data->article_id)) {
            $checked_interior = RelationInterior::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if(isset($old['_old_input']['exterior_place'])) {
            $checked_exterior = $old['_old_input']['exterior_place'];
        } elseif(isset($article_data->article_id)) {
            $checked_exterior = RelationExterior::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if(isset($old['_old_input']['spring_kind'])) {
            $checked_spring = $old['_old_input']['spring_kind'];
        } elseif(isset($article_data->article_id)) {
            $checked_spring = RelationSpring::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if(isset($old['_old_input']['law_restriction'])) {
            $checked_law = $old['_old_input']['law_restriction'];
        } elseif(isset($article_data->article_id)) {
            $checked_law  = RelationLawrestriction::getDataByArticleId($article_data->building_id);
        }

        if(isset($old['_old_input']['other_restriction'])) {
            $checked_other = $old['_old_input']['other_restriction'];
        } elseif(isset($article_data->article_id)) {
            $checked_other = RelationOtherrestriction::getDataByArticleId($article_data->building_id);
        }

        foreach($shared as &$row) {
            if(in_array($row['code'], $checked_shared)) {
                $row['checked'] = 1;
            }
        }

        foreach($interior as &$row) {
            if(in_array($row['code'], $checked_interior)) {
                $row['checked'] = 1;
            }
        }

        foreach($exterior as &$row) {
            if(in_array($row['code'], $checked_exterior)) {
                $row['checked'] = 1;
            }
        }

        foreach($spring_kind as &$row) {
            if(in_array($row['code'], $checked_spring)) {
                $row['checked'] = 1;
            }
        }
        
        foreach($law as &$row) {
            if(in_array($row['code'], $checked_law)) {
                $row['checked'] = 1;
            }
        }

        foreach($other as &$row) {
            if(in_array($row['code'], $checked_other)) {
                $row['checked'] = 1;
            }
        }

        
        $data['shared'] = $shared;
        $data['interior'] = $interior;
        $data['exterior'] = $exterior;
        $data['spring_kind'] = $spring_kind;
        $data['law'] = $law;
        $data['other'] = $other;

        $data['land_right'] = [
            ['code' => 1, 'name' => '所有権'],
            ['code' => 2, 'name' => '借地権のみ'],
            ['code' => 3, 'name' => '所有権・借地権混在'], 
            ['code' => 0, 'name' => '未選択'], 
        ];
        $data['arry_land_right'] = [
            1 => '所有権',
            2 => '借地権のみ',
            3 => '所有権・借地権混在',
            0 => '未設定',
        ];
        
        $data['leasehold'] = [
            ['code' => 1, 'name' => '旧法賃借権'],
            ['code' => 2, 'name' => '普通賃借権'],
            ['code' => 3, 'name' => '一般定期賃借権'],
            ['code' => 4, 'name' => '建物譲渡特約付き定期賃借権'],
            ['code' => 5, 'name' => '旧法地上権'],
            ['code' => 6, 'name' => '普通地上権'],
            ['code' => 7, 'name' => '一般定期地上権'],
            ['code' => 8, 'name' => '建物譲渡特約付き定期地上権'],
        ];
        
        $data['land_rent_unit'] = [
            ['code' => 1, 'name' => '月'],
            ['code' => 2, 'name' => '年'],
            ['code' => 3, 'name' => '一括'],
        ];
        
        $data['leasehold_period'] = [
            ['code' => 1, 'name' => '残存'],
            ['code' => 2, 'name' => '新規'],
        ];
        
        $data['right_cost'] = [
            ['code' => 0, 'name' => '無'],
            ['code' => 1, 'name' => '有(価格に含む)'],
        ];
        
        // 未入居
        $data['occupied'] = [
            ['code' => 1, 'name' => '未入居'],
        ];
        // 収益物件
        $data['revenue'] = [
            ['code' => 1, 'name' => '収益物件'],
        ];

        // 町会費
        $data['council_cost'] = [
            ['code' => 1, 'name' => '町会費'],
            ['code' => 2, 'name' => '町内会費'],
            ['code' => 3, 'name' => '自治会費'],
            ['code' => 0, 'name' => '未選択'], 
        ];

        // 温泉
        $data['spring_cost'] = [
            ['code' => 1, 'name' => '温泉使用料'],
            ['code' => 2, 'name' => '温泉権利金'],
            ['code' => 0, 'name' => '未選択'], 
        ];

        // 道路(向き)
        $data['land_direction'] = [
            ['code' => 0, 'name' => ''],
            ['code' => 1, 'name' => '北'],
            ['code' => 2, 'name' => '北東'],
            ['code' => 3, 'name' => '東'],
            ['code' => 4, 'name' => '南東'],
            ['code' => 5, 'name' => '南'],
            ['code' => 6, 'name' => '南西'],
            ['code' => 7, 'name' => '西'],
            ['code' => 8, 'name' => '北西'],
        ];

        // 道路(種別)
        $data['land_kind'] = [
            ['code' => 0, 'name' => ''],
            ['code' => 1, 'name' => '公道'],
            ['code' => 2, 'name' => '私道'],
        ];
        
        // 施設
        // $data['facility'] = Facility::getData();
        $data['facility'] = [];
        $data['facility_property'] = MstFacilityType::getData();
        $data['facility_distance'] = [
            ['code'=> 0, 'name' => 0],
            ['code'=> 5, 'name' => 5],
            ['code'=> 10, 'name' => 10],
            ['code'=> 15, 'name' => 15],
            ['code'=> 20, 'name' => 20],
            ['code'=> 25, 'name' => 25],
            ['code'=> 30, 'name' => 30],
            ['code'=> 35, 'name' => 35],
            ['code'=> 40, 'name' => 40],
            ['code'=> 45, 'name' => 45],
            ['code'=> 50, 'name' => 50],
            ['code'=> 55, 'name' => 55],
            ['code'=> 60, 'name' => 60],
            ['code'=> 65, 'name' => 65],
        ];

        $data['original1'] = [['code' => 1, 'name' => '　']];
        $data['original2'] = [['code' => 1, 'name' => '　']];
        $data['original3'] = [
            ['code'=> 0, 'name' => '0'],
            ['code'=> 1, 'name' => '1'],
            ['code'=> 2, 'name' => '2'],
            ['code'=> 3, 'name' => '3'],
        ];
        $data['original4'] = [['code' => 1, 'name' => '　']];

        // 営業担当者
        // $data['hp_charge'] = User::getDataByCompanyId($user->company_id, 3);
        if(isset($article_data->shop)) {
            $data['hp_charge'] = UserInfo::getCharge($user->company_id, $article_data->shop);
        } else {
            if(isset($shops[0])) {
                $data['hp_charge'] = UserInfo::getCharge($user->company_id, $shops[0]['code']);
            } else {
                $data['hp_charge'] = [];
            }
            // $data['hp_charge'] = [];
        }

        // 物件価格
        $data['tax'] = [
            ['code' => 1, 'name' => '税抜'],
            ['code' => 2, 'name' => '税込'],
        ];

        // 用途地域
        $data['use_area'] = MstUseArea::getData();
        $arr_use_area = [];
        foreach($data['use_area'] as $row) {
            $arr_use_area[$row['code']] = $row['name'];
        }
        $data['arr_use_area'] = $arr_use_area;

        $data['use_area_district'] = MstUseDistrict::getData();
        $arr_use_area_district = [];
        foreach($data['use_area_district'] as $row) {
            $arr_use_area_district[$row['code']] = $row['name'];
        }
        $data['arr_use_area_district'] = $arr_use_area_district;

        $data['city_plan'] = [
            ['code' => 1, 'name' => '市街化区域'],
            ['code' => 2, 'name' => '調整区域'],
            ['code' => 3, 'name' => '非線引区域'],
            ['code' => 4, 'name' => '区域外'],
            ['code' => 5, 'name' => '準都市区域'],
        ];
        $arr_city_plan = [];
        foreach($data['city_plan'] as $row) {
            $arr_city_plan[$row['code']] = $row['name'];
        }
        $data['arr_city_plan'] = $arr_city_plan;

        $data['city_plan_reason'] = [
            ['code' => 1, 'name' => '開発許可などによる分譲地内'],
            ['code' => 2, 'name' => '都市開発法施行令36条1項3号口に該当'],
            ['code' => 3, 'name' => '調整区域につき建築許可要'],
            ['code' => 4, 'name' => '調整区域につき建築許可要。建築主の許可要件あり'],
        ];
        $arr_city_plan_reason = [];
        foreach($data['city_plan_reason'] as $row) {
            $arr_city_plan_reason[$row['code']] = $row['name'];
        }
        $data['arr_city_plan_reason'] = $arr_city_plan_reason;

        // 施設の市区群を取得
        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;

        return $data;
    }

    public function setCount() {
        $user = Auth::user();
        // 駅に設定されている物件の件数を設定
        $stations = MstStation::getAllId();
        foreach($stations as $row) {
            $count = Article::getCountByStation($row->id, $user->company_id);
            $data = ['count' => $count];
            MstStation::where('id', '=', $row->id)->update($data);
        }

        $primary_schools = MstSchool::getAllId(1);
        foreach($primary_schools as $row) {
            $count = Article::getCountByPrimarySchool($row->code, $user->company_id);
            $data = ['count' => $count];
            MstSchool::where('code', '=', $row->code)->update($data);
        }
        
        $secondary_schools = MstSchool::getAllId(2);
        foreach($secondary_schools as $row) {
            $count = Article::getCountBySecondarySchool($row->code, $user->company_id);
            $data = ['count' => $count];
            MstSchool::where('code', '=', $row->code)->update($data);
        }
    }

    public function updateImage($request, $article) {
        $all = $request->all();

        $image_len = 0;
        $runk = 1;
        if(isset($request->saved_photo_id)) {
            $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;
                }
                
            }

            $list = explode(',', $request->saved_photo_id);
            $image_len = count($list);

            foreach($tag as $val) {
                $target_id = $request->{'article_photo_id'.$val};
                $disp = 1;
                if(isset($request->{'photo_disp_change'.$val})) {
                    $disp = $request->{'photo_disp_change'.$val};
                }

                $photo_data = [
                    'file_disp' => $disp,
                    'property' => $request->{'photo_property'.$val},
                    'property_sub' => $request->{'photo_property_sub'.$val},
                    'memo' => $request->{'photo_comment'.$val},
                    'order' => $runk,
                ];
                RelationArticlePhoto::where('id', '=', $target_id)->update($photo_data);
                $runk++;
            }
        }

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

        if(isset($request->photo_images)) {
            $img_list = RelationArticlePhoto::where('article_id', '=', $article->building_id)->get();
            $max = 0;
            foreach($img_list as $img) {
                $tmp_path = $img->file_path;
                $tmp_path = str_replace('public/photo/photo_image_'.$article->building_id.'_', '', $tmp_path);
                $tmp_path = str_replace('.'.$img->file_type, '', $tmp_path);
                if($max < $tmp_path) {
                    $max = $tmp_path;
                }
            }
            if($max != 0) {
                $max++;
            }

            $num = 0;
            $saved = $request->saved_photo_id;
            $saved_info = explode(',', $saved);
            $saved_info = array_filter($saved_info, "strlen");
            $deleted = $request->del_photo_id;
            $deleted_info = explode(',', $deleted);
            $deleted_info = array_filter($deleted_info, "strlen");
            $num += count($saved_info);
            // $num += count($deleted_info);

            $len = $max;
            
            foreach($request->photo_images as $key => $photo) {
                $len = $len+1;
                $extension = $photo->getClientOriginalExtension();
                
                $image = \Image::make($photo)->exif();
                $org_height = $image['COMPUTED']['Height'];
                $org_width = $image['COMPUTED']['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->resize($width, $height)->save(storage_path().'/app/public/photo/photo_image_'.$article->building_id.'_'.$len.'.'. $extension);

                $image_url = 'public/photo/photo_image_'.$article->building_id.'_'.$len.'.'. $extension;

                $disp = 1;
                if(isset($request->{'photo_disp_change'.$num})) {
                    $disp = $request->{'photo_disp_change'.$num};
                }
                $photo_data = [
                    'article_id' => $article->building_id,
                    'file_path' => $image_url,
                    'file_type' => $extension,
                    'file_disp' => $disp,
                    'property' => $request->{'photo_property'.$num},
                    'property_sub' => $request->{'photo_property_sub'.$num},
                    'memo' => $request->{'photo_comment'.$num},
                    'order' => $runk,
                ];
                RelationArticlePhoto::create($photo_data);
                $runk++;
                $num++;
            }
        }
    }


    public function image(Request $request, User $user) {

        // バリデーション省略
        $originalImg = $request->user_image;
      
        if($originalImg->isValid()) {
            $filePath = $originalImg->store('public');
            $user->image = str_replace('public/', '', $filePath);
            $user->save();
        }
        return redirect("/user/{$user->id}")->with('user', $user);
      
      }

      public function getDataById($id) {
        $user = Auth::user();

        $article = Article::getDataById($user->company_id, $id);

        if($article == null) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        if(isset($article->create) && !empty($article->create)) {
            $article->disp_create = date('Y/m/d',  strtotime($article->create));
        }
        if(!empty($article->floor_file_path)) {
            $article->file_path = str_replace('public', '/storage', $article->floor_file_path);
        }
        if(!empty($article->sheet_file_path2)) {
            $article->sheet_file_path2 = str_replace('public', '/storage', $article->sheet_file_path2);
        }
        if(!empty($article->sheet_file_path3)) {
            $article->sheet_file_path3 = str_replace('public', '/storage', $article->sheet_file_path3);
        }

        if(!empty($article->event_day)) {
            $article->event_day = explode(',', $article->event_day);
        }

        $images = RelationArticlePhoto::getImgByArticleId($article->building_id);
        $image_id = "";
        foreach($images as &$img) {
            $img->file_path = str_replace('public', '/storage', $img->file_path);
            if($image_id != "") {
                $image_id .= ",";
            }
            $image_id .= $img->id;
        }
        $article->images = $images;
        $article->images_id = $image_id;

        return $article;
      }


      function distance($lat1, $lon1, $lat2, $lon2, $mode=true) {
        // 緯度経度をラジアンに変換
        $radLat1 = deg2rad($lat1); // 緯度１
        $radLon1 = deg2rad($lon1); // 経度１
        $radLat2 = deg2rad($lat2); // 緯度２
        $radLon2 = deg2rad($lon2); // 経度２

        // 緯度差
        $radLatDiff = $radLat1 - $radLat2;

        // 経度差算
        $radLonDiff = $radLon1 - $radLon2;

        // 平均緯度
        $radLatAve = ($radLat1 + $radLat2) / 2.0;

        // 測地系による値の違い
        $a = $mode ? 6378137.0 : 6377397.155; // 赤道半径
        $b = $mode ? 6356752.314140356 : 6356078.963; // 極半径
        //$e2 = ($a*$a - $b*$b) / ($a*$a);
        $e2 = $mode ? 0.00669438002301188 : 0.00667436061028297; // 第一離心率^2
        //$a1e2 = $a * (1 - $e2);
        $a1e2 = $mode ? 6335439.32708317 : 6334832.10663254; // 赤道上の子午線曲率半径

        $sinLat = sin($radLatAve);
        $W2 = 1.0 - $e2 * ($sinLat*$sinLat);
        $M = $a1e2 / (sqrt($W2)*$W2); // 子午線曲率半径M
        $N = $a / sqrt($W2); // 卯酉線曲率半径

        $t1 = $M * $radLatDiff;
        $t2 = $N * cos($radLatAve) * $radLonDiff;
        $dist = sqrt(($t1*$t1) + ($t2*$t2));

        return $dist;
    }
}
