<?php

namespace App\Http\Controllers\Admin\Ajax;

use Illuminate\Http\Request;
use \SplFileObject;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\MstPrefecture;   
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstLine;
use App\Models\MstStation; 
use App\Models\MstSchool;   
use App\Models\MstStore;
use App\Models\Article;
use App\Models\Vendor;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\News;
use App\Models\RelationCitySchool;
use App\Models\RelationVendorArticle;
use App\Models\RelationDuplicateVendorArticle;
use App\Models\RainsDuplicateArticle;
use App\Models\RainsDuplicateVendor;
use App\Models\RelationPriceHistory;
use App\Models\Facility;
use App\Models\Reform;
use App\Models\TempImage;
use App\Models\TempImageStore;
use App\Models\TempImageReform;
use App\Models\RelationStorePhoto;
use App\Models\RelationReformPhoto;
use App\Models\RelationArticleFacility;
use App\Models\RelationStoreArea;
use App\Models\MstParking;
use App\Models\RelationArticlePhoto;

class AjaxController extends Controller
{
    private $csv_item_num = 196;

    /**
     * 住所セレクトボックスの子要素を取得
    */
    public function changeAddress(Request $request)
    {
        $response = array();

        switch($request->code) {
            case 'pref':
                $response = MstCity::getData($request->prefId);
                break;

            case 'city':
                $response = MstTown::getData($request->prefId, $request->cityId);
                break;
        }

        return response()->json($response);
    }

    /**
     * 都道府県セレクトボックスの子要素を取得
    */
    public function changeAddressPref(Request $request)
    {
        $response = MstCity::getData($request->prefId);
        return response()->json($response);
    }

    /**
     * 市区町村セレクトボックスの子要素を取得
    */
    public function changeAddressCity(Request $request)
    {
        $response = [];
        $response[] = MstTown::getData($request->prefId, $request->cityId);
        $prefInfo = MstPrefecture::getData($request->prefId);
        $cityInfo = MstCity::getData($request->prefId, $request->cityId);
        $response[] = RelationCitySchool::getCityListByCityId($request->prefId.$request->cityId);
        // $response[] = $this->get_gps_from_address($prefInfo[0]['name'].$cityInfo[0]['name']);
        return response()->json($response);
    }

    public function changeAddressCityName(Request $request)
    {
        $response = [];
        $pref_info = MstPrefecture::where('name', $request->prefName)->first();
        $city_info = MstCity::where('name', $request->cityName)->first();

        $response[] = MstTown::getData($pref_info->code, $city_info->code);
        $response[] = RelationCitySchool::getCityListByCityId($request->code.$request->code);
        $response[] = $city_info->code;
        // $response[] = $this->get_gps_from_address($prefInfo[0]['name'].$cityInfo[0]['name']);
        return response()->json($response);
    }

    /**
     * 市区町村セレクトボックスの子要素を取得
    */
    public function changeAddressCityToSearch(Request $request)
    {
        $response = [];
        $response[] = MstTown::getData($request->prefId, $request->cityId);
        $response[] = MstSchool::getPrimarySchoolByAddress($request->prefId, $request->cityId);
        $response[] = MstSchool::getSecondarySchoolByAddress($request->prefId, $request->cityId);
        return response()->json($response);
    }

    /**
     * 市区郡、路線・駅名を取得
    */
    public function changeAddressPrefStation(Request $request)
    {
        $response = [];
        if(isset($request->prefId)) {
            // 市区郡を取得
            $response[] = MstCity::getData($request->prefId);
            // 路線・駅名を取得
            $response[] = MstStation::getDataByCode($request->prefId);
        }
        return response()->json($response);
    }

    public function changeAddressCityStation(Request $request)
    {
        $response = [];
        if(isset($request->prefId) && isset($request->cityId)) {
            $code = $request->prefId;
            if($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $response[] = MstStation::getDataByCode($code);
        }
        return response()->json($response);
    }

    /**
     * 路線を取得
    */
    public function getLine(Request $request)
    {
        $response = [];
        if(isset($request->prefId)) {
            $code = $request->prefId;
            if($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $response = MstStation::getDataDistinctByCode($code, $request->key);
        }
        return response()->json($response);
    }

    /**
     * 駅を取得
    */
    public function getStation(Request $request)
    {
        $response = [];
        if(isset($request->line)) {
            // 路線・駅名を取得
            $response = MstStation::getDataStation($request->line, $request->key);
        }
        return response()->json($response);
    }

    public function changeAddressCityStationSub(Request $request)
    {
        $response = [];
        if(isset($request->prefId) && isset($request->cityId)) {
            $code = $request->prefId;
            if($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $response[] = MstStation::getDataDistinctByCode($code, $request->key);
        }
        return response()->json($response);
    }

    public function changeAddressCityESchool(Request $request)
    {
        $response = [];
        $schools = RelationCitySchool::getDataElementarySchool($request->town);
        if(!empty($schools)) {
            $response = MstSchool::getSchoolName($schools);
        }
        return response()->json($response);
    }

    public function changeAddressCityJSchool(Request $request)
    {
        $response = [];
        $schools = RelationCitySchool::getDataJuniorSchool($request->town);
        if(!empty($schools)) {
            $response = MstSchool::getSchoolName($schools);
        }
        return response()->json($response);
    }

    /**
     * 指定ユーザーを削除
    */
    public function deleteUser(Request $request)
    {
        $user = Auth::user($request);

        $response = [];
        $id = $request->id;
        if($user->id != $id) {
            $user_info = UserInfo::where('employee_number', $id)->first();
            User::where('id', $user_info->id)->delete();
            UserInfo::where('employee_number', $id)->delete();
        }
        return response()->json($response);
    }

    /**
     * 指定お知らせを削除
    */
    public function deleteNews(Request $request)
    {
        $response = [];
        News::where('id', $request->id)->delete();
        return response()->json($response);
    }

    /**
     * 指定施設を削除
    */
    public function deleteFacility(Request $request)
    {
        $response = [];
        Facility::where('id', $request->id)->delete();
        RelationArticleFacility::where('facility_id', '=', $request->id)->delete();
        return response()->json($response);
    }

    /**
     * 指定施設を削除
    */
    public function deleteStore(Request $request)
    {
        $response = [];
        MstStore::where('id', $request->id)->delete();
        return response()->json($response);
    }
    

    /**
     * 指定おすすめ登録
    */
    public function saveRecommend(Request $request)
    {
        $user = Auth::user();

        // 既に登録されているオススメを取得
        $old = Article::select('building_id')->where('company_id', '=', $user->company_id)->where('recommend', '=', 1)->orderby('recommend_num')->get();

        $id_list = explode(',', $request->id);
        $response = [];
        $num = 1;
        foreach($id_list as $id) {
            $data = ['recommend' => 1, 'recommend_num' => $num];
            Article::where('building_id', '=', $id)->update($data);
            $num++;
        }

        foreach($old as $row) {
            $data = ['recommend' => 1, 'recommend_num' => $num];
            Article::where('building_id', '=', $row->id)->update($data);
            $num++;
        }

        return response()->json($response);
    }


    /**
     * 指定おすすめ削除
    */
    public function deleteRecommend(Request $request)
    {
        $user = Auth::user();
        $response = [];
        $data = ['recommend' => 0, 'recommend_num' => null];
        Article::where('building_id', '=', $request->id)->update($data);

        $article = Article::where('recommend', '=', 1)->where('company_id', '=', $user->company_id)->orderBy('recommend_num')->get();
        $num = 1;
        foreach($article as $row) {
            $data = ['recommend_num' => $num];
            Article::where('building_id', '=', $row->id)->update($data);
            $num++;
        }

        
        return response()->json($response);
    }

    /**
     * おすすめソート
    */
    public function setRecommendRank(Request $request)
    {
        $response = [];
        $data = ['recommend_num' => $request->num];
        Article::where('id', '=', $request->id)->update($data);
        
        return response()->json($response);
    }

    /**
     * 指定リフォーム削除
    */
    public function deleteReform(Request $request)
    {
        $user = Auth::user();
        $response = [];

        Reform::where('code', $request->id)->where('company_id', $user->company_id)->delete();

        $reform = Reform::where('company_id', '=', $user->company_id)->orderBy('reform_num')->get();
        $num = 1;
        foreach($reform as $row) {
            $data = ['reform_num' => $num];
            Reform::where('code', $row->code)->where('company_id', $user->company_id)->update($data);
            $num++;
        }

        return response()->json($response);
    }

    /**
     * リフォームソート
    */
    public function setReformRank(Request $request)
    {
        $response = [];
        $data = ['reform_num' => $request->num];
        Reform::where('id', '=', $request->id)->update($data);
        
        return response()->json($response);
    }

    public function searchShopCharge(Request $request) {
        $user = Auth::user();
        $response = UserInfo::getCharge($user->company_id, $request->id);

        return response()->json($response);
    }

    public function setImage(Request $request) {
        $file = $request->file('photo');
        $content = $this->convertImageSource(file_get_contents($file->getRealPath()));
        $data = ['num' => $request['num'], 'id' => '', 'flag' => $request['flag']??'', 'content' => $content??''];
        return view('admin.objects.components.add-photo-image', $data);
    }

    /*
    * レインズCSVのアップロード
    */
    public function uploadCsv(Request $request) {
        try {
            $res = "success";

            // CSVファイルのアップロードと読み込み
            $aryDataList = $this->readCsv();

            foreach($aryDataList as $row) {
                if (mb_detect_encoding(implode($row)) != 'UTF-8') {
                    mb_convert_variables("UTF-8", "SJIS", $row); 
                }
                
                // 物件情報の登録
                $this->saveRainsData($row);
            }

            return $res;
        } catch(Exception $e) {
            echo "例外キャッチ：",$e->getMessage(),"\n";
        }
    }

    function saveRainsData($data) {
        $user = Auth::user();

        // CSVの物件情報を登録予定物件として登録
        $article = new RainsDuplicateArticle;
        $article->company_id = $user->company_id;
        $article->rains_no = intval($data[0]);
        $article->status = intval($data[1]);
        $property = "";
        if($data[2] == "1") {
            $property = 1;
        } else if($data[2] == "2") {
            $property = 4;
        } else if($data[2] == "3") {
            $property = 6;
        }
        $article->property = $property;
        $article->property_sub = intval($data[3]);
        $address_info = MstTown::getDataByAddress($data[16]);
        $address = $data[14].$data[15].$data[16];
        $zip = $this->getZipCode($address);
        $article->zip = $zip;
        $address1 = 0;
        $address2 = 0;
        $address3 = 0;
        if(isset($address_info[0]['pref_code'])) {
            $address1 = intval($address_info[0]['pref_code']);
        }
        if(isset($address_info[0]['pref_code'])) {
            $address2 = intval($address_info[0]['city_code']);
        }
        if(isset($address_info[0]['pref_code'])) {
            $address3 = intval($address_info[0]['code']);
        }
        $article->address1 = $address1;
        $article->address2 = $address2;
        $article->address3 = $address3;
        
        $article->address4 = $data[17];
        $article->name = empty($data[18])? $data[15].$data[16]: $data[18];
        $article->name_portal = empty($data[18])? $data[15].$data[16]: $data[18];
        if($data[2] == 3) {
            $article->name_apartment = $data[18];
        }
        if(empty($data[19])) {
            $room_num = null;
        } else {
            $room_num = intval($data[19]);
        }
        $article->room_num = $room_num;
        
        $article->revenue = 0;

        // 対象店舗の取得
        $shop = RelationStoreArea::getShopId($user->company_id, $address1, $address2, $address3);
        $other_shop = MstStore::getIdByName($user->company_id, 'その他');
        $article->shop = $shop->store_id??$other_shop->code;

        // 主要交通
        if(!empty($data[22])) {
            $line_data = MstLine::getDataByName($data[22]);
            
            $station_data = null;
            if(!empty($data[23])) {
                $station_data = MstStation::getDataByName($data[22], $data[23]);
            }

            $article -> main_traffic = 1;
            if($data[22] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } elseif($data[22] == 'いずみ野線') {
                $line_name = '相鉄いずみ野線';
            } elseif($data[22] == '京急逗子線') {
                $line_name = '京急逗子線';
            } elseif($data[22] == '京浜急行線') {
                $line_name = '京急本線';
            } elseif($data[22] == '京浜東北線') {
                $line_name = 'JR京浜東北線';
            } elseif($data[22] == 'こどもの国') {
                $line_name = '東急こどもの国線';
            } elseif($data[22] == 'シーサイド') {
                $line_name = '横浜シーサイドライン';
            } elseif($data[22] == '相鉄線') {
                $line_name = '相鉄本線';
            } elseif($data[22] == '鶴見線') {
                $line_name = 'JR鶴見線';
            } elseif($data[22] == '田園都市線') {
                $line_name = '東急田園都市線';
            } elseif($data[22] == '東海道線') {
                $line_name = 'JR東海道本線';
            } elseif($data[22] == '東横線') {
                $line_name = '東急東横線';
            } elseif($data[22] == '根岸線') {
                $line_name = 'JR根岸線';
            } elseif($data[22] == 'みなとM線') {
                $line_name = '横浜高速鉄道みなとみらい線';
            } elseif($data[22] == '横須賀線') {
                $line_name = 'JR横須賀線';
            } elseif($data[22] == '横浜グリー') {
                $line_name = '横浜市営グリーンライン';
            } elseif($data[22] == '横浜線') {
                $line_name = 'JR横浜線';
            } elseif($data[22] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } else {
                $line_name = $data[22];
            }
            $article -> main_traffic_line = $line_name;
            if(!empty($line_data)) {
                $article -> main_traffic_line_id = $line_data->id;
            }
            $article -> main_traffic_station = $data[23];
            if(!empty($station_data)) {
                $article -> main_traffic_station_id = $station_data->id;
            }
            $article -> main_traffic_time = empty($data[24])? null: intval($data[24]);
        }

        // 補助交通１
        if(!empty($data[27])) {
            $line_data = MstLine::getDataByName($data[27]);

            $station_data = null;
            if(!empty($data[28])) {
                $station_data = MstStation::getDataByName($data[27],$data[28]);
            }
            
            $article -> sub_traffic1 = 2;
            if($data[27] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } elseif($data[27] == 'いずみ野線') {
                $line_name = '相鉄いずみ野線';
            } elseif($data[27] == '京急逗子線') {
                $line_name = '京急逗子線';
            } elseif($data[27] == '京浜急行線') {
                $line_name = '京急本線';
            } elseif($data[27] == '京浜東北線') {
                $line_name = 'JR京浜東北線';
            } elseif($data[27] == 'こどもの国') {
                $line_name = '東急こどもの国線';
            } elseif($data[27] == 'シーサイド') {
                $line_name = '横浜シーサイドライン';
            } elseif($data[27] == '相鉄線') {
                $line_name = '相鉄本線';
            } elseif($data[27] == '鶴見線') {
                $line_name = 'JR鶴見線';
            } elseif($data[27] == '田園都市線') {
                $line_name = '東急田園都市線';
            } elseif($data[27] == '東海道線') {
                $line_name = 'JR東海道本線';
            } elseif($data[27] == '東横線') {
                $line_name = '東急東横線';
            } elseif($data[27] == '根岸線') {
                $line_name = 'JR根岸線';
            } elseif($data[27] == 'みなとM線') {
                $line_name = '横浜高速鉄道みなとみらい線';
            } elseif($data[27] == '横須賀線') {
                $line_name = 'JR横須賀線';
            } elseif($data[27] == '横浜グリー') {
                $line_name = '横浜市営グリーンライン';
            } elseif($data[27] == '横浜線') {
                $line_name = 'JR横浜線';
            } elseif($data[27] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } else {
                $line_name = $data[27];
            }
            $article -> sub_traffic1_line = $line_name;
            if(!empty($line_data)) {
                $article -> sub_traffic1_line_id = $line_data->id;
            }
            $article -> sub_traffic1_station = $data[28];
            if(!empty($station_data)) {
                $article -> sub_traffic1_station_id = $station_data->id;
            }
            $article -> sub_traffic1_time = empty($data[29])? null: intval($data[29]);
        }

        $article -> memo1 = empty($data[193])? null: $data[193];
        $article -> memo2 = empty($data[194])? null: $data[194];


        $article -> price = empty($data[46])? null: intval($data[46])/10000;
        $article -> tax = empty($data[47])? 1: 2;

        $article -> building_rate = empty($data[85])? null: intval($data[85]);
        $article -> volume_rate = empty($data[86])? null: intval($data[86]);

        $article -> road_burden = empty($data[58])? null: intval($data[58]);
        $article -> road_burden_area = empty($data[59])? null: intval($data[59]);

        if(!empty($data[60])) {
            $article -> balcony_area = 1;
            $article -> balcony_area_val = intval($data[60]);
        }

        if(!empty($data[61])) {
            $article -> balcony_area = 1;
            $article -> balcony_area_val = intval($data[61]);
        }

        $article -> ground = empty($data[80])? null: intval($data[80]);

        $article -> set = empty($data[62])? null: intval($data[62]);
        $article -> set_area = empty($data[64])? null: intval($data[64]);





        $article -> total_unit = empty($data[179])? null: $data[179];
        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[178], $age);
        $article -> age_year = empty($age[1])? null: $age[1];
        $article -> age_month = empty($age[2])? null: $age[2];
        $article -> construction = empty($data[172])? null: $data[172];
        $article -> floor = empty($data[175])? null: $data[175];
        $article -> whereabouts = empty($data[177])? null: $data[177];
        $article -> underground = empty($data[176])? null: $data[176];

        $article -> land_area = empty($data[51])? null: $data[51];
        $article -> land_area_val = empty($data[52])? null: $data[52];

        if($data[2] == "1") {
            $article -> total_area_val = empty($data[70])? null: $data[70];
        } else if($data[2] == "2") {
            $article -> total_area_val = empty($data[56])? null: $data[56];
        } else if($data[2] == "3") {
            $article -> total_area_val = empty($data[57])? null: $data[57];
        }

        if(!empty($data[37]) && $data[37] == 4) {
            $article -> land_delivery = 3;
        } else {
            $article -> land_delivery = empty($data[37])? null: $data[37];
        }
        
        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[38], $age);
        $article -> delivery_year = empty($age[1])? null: $age[1];
        $article -> delivery_month = empty($age[2])? null: $age[2];

        $article -> land_kind1 = empty($data[111])? null: $data[111];
        $article -> land_direction1 = empty($data[114])? null: $data[114];
        $article -> road_width1 = empty($data[115])? null: $data[115];
        $article -> frontage1 = empty($data[112])? null: $data[112];
        
        $article -> land_kind2 = empty($data[116])? null: $data[116];
        $article -> land_direction2 = empty($data[119])? null: $data[119];
        $article -> road_width2 = empty($data[120])? null: $data[120];
        $article -> frontage2 = empty($data[117])? null: $data[117];

        $article -> land_kind3 = empty($data[121])? null: $data[121];
        $article -> land_direction3 = empty($data[124])? null: $data[124];
        $article -> road_width3 = empty($data[125])? null: $data[125];
        $article -> frontage3 = empty($data[122])? null: $data[122];

        $article -> city_plan = empty($data[81])? null: $data[81];

        $article -> use_area = empty($data[82])? null: $data[82];
        $article -> land_use = empty($data[83])? null: $data[83];

        $article -> section = empty($data[67])? null: $data[67];


        if(!empty($data[101])) {
            $article -> management = 1;
            $article -> management_cost = intval($data[101]);
        }

        if(!empty($data[103])) {
            $article -> repair = 1;
            $article -> repair_cost = intval($data[103]);
        }
        


        $article -> sales_company = empty($data[108])? null: $data[108];
        $article -> construction_company = empty($data[107])? null: $data[107];
        $article -> management_company = empty($data[99])? null: $data[99];
        $article -> management_form = empty($data[70])? null: $data[70];


        $article -> land_condition = empty($data[95])? null: $data[95];
        $article -> current_status = empty($data[35])? null: $data[35];
        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[36], $age);
        $article -> current_status_year = empty($age[1])? null: $age[1];
        $article -> current_status_month = empty($age[2])? null: $age[2];

        $floor_plan = null;
        if($data[132] == 1) {
            $floor_plan = 3;
        } elseif($data[132] == 2) {
            $floor_plan = 4;
        } elseif($data[132] == 3) {
            $floor_plan = 1;
        } elseif($data[132] == 4) {
            $floor_plan = 7;
        } elseif($data[132] == 5) {
            $floor_plan = 2;
        } elseif($data[132] == 6) {
            $floor_plan = 5;
        } elseif($data[132] == 7) {
            $floor_plan = 6;
        } elseif($data[132] == 8) {
            $floor_plan = 8;
        } elseif($data[132] == 9) {
            $floor_plan = 9;
        }
        $article -> floor_plan = empty($data[133])? null: $data[133];
        $article -> floor_plan_type = $floor_plan;
        
        $article -> sales_company = $data[108];
        $article -> construction_company = $data[107];
        $article -> management_company = $data[99];
        $article -> management_form = empty($data[98])? null: $data[98];

        $article -> land_not = empty($data[196])? null: $data[196];

        $article->save();

        // 業者登録
        $vendor_data = [];
        $vendor_data['name'] = $data[4];
        $vendor_data['company_id'] = $user->company_id;
        $vendor_data['vendor_charge'] = $data[6];
        $vendor_data['vendor_tel1'] = $data[5];
        $vendor_data['vendor_tel2'] = $data[7];
        $vendor_data['vendor_mail'] = $data[8];
 
        // 重複する業者がなければ登録
        $vendor = Vendor::where(['name' => $data[4]])->first();
        if(is_null($vendor)) {
            $vendor = new Vendor;
            $vendor->fill($vendor_data)->save();
        }
        
 

        $relation = new RelationDuplicateVendorArticle;
        $relation -> article_id = $article -> id;
        $relation -> vendor_id = $vendor -> id;
        $relation -> charge = $data[6];
        // $relation -> manner = $data[42];
        $relation->save();
        


        return $article->id;
    }

    public function getZipCode($address) {
        $res = "";
        $baseurl = "https://zipcoda.net/api/"; 
        
        $ch = curl_init(); //1.初期化
        curl_setopt($ch, CURLOPT_URL,$baseurl . '?address=' . $address); //2.URLをセット
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); //3.HTTP リクエストをセット（GET,POST等)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); //文字列で返す
        //curl_setopt($ch, CURLOPT_HEADER, true);   // ヘッダーも出力する
        
         //..4.その他必要オプション
        $result = curl_exec($ch); //5.実行して、レスポンスを取得
        // var_dump($result); // 出力
        print("-------------------------------");
        $resultarr = json_decode($result,true); //jsonを配列に
        // var_dump($resultarr); //配列で出力
        
        curl_close($ch); // 6.終了

        if($resultarr['status'] == 'success') {
            if(isset($resultarr['items'][0]['zipcode'])) {
                $tmp = $resultarr['items'][0]['zipcode'];
                $res = substr($tmp, 0, 3).'-'.substr($tmp, 3);
            }
        }

        return $res;
        
    }

    public function readCsv() {
        $targetFolder = '/admin/upload'; //アップロード先フォルダを指定します。
        $aryDataList = [];

        //POSTでアップロードされたファイルの保存場所、読み込み指定をします。
        if(is_uploaded_file($_FILES["file"]["tmp_name"])){
            $tempFile = $_FILES['file']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['file']['name'];
            
            // Validate the file type
            $fileTypes = array('csv', 'txt');// File extensions
            $fileParts = pathinfo($_FILES['file']['name']);

            if (in_array($fileParts['extension'], $fileTypes)) {
                move_uploaded_file($tempFile, $targetFile);

                $aryDataList = [];
                
                $data = file_get_contents($targetFile);
                $data = preg_replace('/(\r\n|\r|\n)/s',"\r\n", $data);
                $utf8 = mb_convert_encoding($data, 'UTF-8', 'SJIS-win');
                $targetFile_utf = rtrim($targetPath,'/') . '/rains.csv';
                file_put_contents($targetFile_utf, $utf8);
                $data = file_get_contents($targetFile_utf
            );

                // 一時ファイルの作成
                $temp = tmpfile();
                // メタデータからファイルパスを取得して読み込み
                $meta = stream_get_meta_data($temp);
                
                // 一時ファイル書き込み
                fwrite($temp, $data);

                // ファイルポインタの位置を先頭に
                rewind($temp);
                
                $objFile = new SplFileObject($meta['uri'], 'rb');
                $objFile->setFlags(SplFileObject::READ_CSV);

                $num = 0;
                
                foreach ($objFile as $line) {
                    // mb_convert_variables('UTF-8', 'sjis-win', $line);
                    if($num ==0) {
                        $num++;
                        continue;
                    }
                    $aryDataList[] = $line;
                }

                fclose($temp);

            } else {
                // csvではない
                echo 'Invalid file type.';
            }
        }

        return $aryDataList;
    }

    function checkDuplicate($data) {
        $res = 0;
        $address_info = MstTown::getDataByAddress($data[16]);
        if(isset($address_info[0]['city_code'])) {
            $city = intval($address_info[0]['city_code']);
        }
        
        // 市・土地面積
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('land_area_val', '=', $data[52]);
        $res1 = $q->get()->count();
        if($res1 != 0) {
            $res += $res1;
        }

        // 市・建物面積
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('total_area_val', '=', $data[56]);
        $res2 = $q->get()->count();
        if($res2 != 0) {
            $res += $res2;
        }

        // 市・丁目・物件種別
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('address4', '=', $data[17]);
        $property = "";
        if($data[2] == "1") {
            $property = 1;
        } else if($data[2] == "2") {
            $property = 4;
        } else if($data[2] == "3") {
            $property = 6;
        }
        $q->where('property', '=', intval($property));
        $res3 = $q->get()->count();
        if($res3 != 0) {
            $res += $res3;
        }

        // マンション名
        $res4 = 0;
        if(!empty($data[18])) {
            $q = Article::query();
            $q->where('name_apartment', '=', $data[18]);
            $res4 = $q->get()->count();
            if($res4 != 0) {
                $res += $res4;
            }
        }

        return $res;
    }

    public function changeAccess1(Request $request) {
        $response = [];
        if(isset($request->line)) {
            // 路線・駅名を取得
            $response = MstStation::getDataStationByLine($request->line);
        }
        return response()->json($response);
    }
    
    public function searchFacility(Request $request) {
        $res = 0;
        $all = $request->all();
        $res = Facility::getDataByCondition($all);

        return response()->json($res);
    }

    public function searchFacilityShop(Request $request) {
        $user = Auth::user();
        $res = [];
        $property = $request->property;
        if($property == "") {
        } else {
            $facility = Facility::where('kind', '=', $property)->where('company_id', '=', $user->company_id)->get();
            foreach($facility as &$row) {
                $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
                $tmp = [
                    'id' => $row->id,
                    'name' => $row->name
                ];
                $res[] = $tmp;
            }
        }
        

        return response()->json($res);
    }

    public function searchFacilityProperty(Request $request) {
        $user = Auth::user();
        $res = [];

        $all = $request->all();
        if(isset($all['area'])) {
            $res = Facility::getFacilityProperty($user->company_id, $all['area']);
        }
        
        
        return response()->json($res);
    }

    public function saveVendorInfo(Request $request) {
        $user = Auth::user();

        $all = $request->all();

        $vendor_id = $all['vendor_id'];
        $article_id = $all['article_id'];

        // 物件ー業者情報の更新
        $article_vendor_data = [];
        $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'];
        $article_vendor_data['flyer'] = $all['flyer'];
        $article_vendor_data['freepaper'] = $all['freepaper'];
        $article_vendor_data['house_hp'] = $all['house_hp'];
        $article_vendor_data['portal'] = $all['portal'];
        $article_vendor_data['signboard'] = $all['signboard'];
        $article_vendor_data['ad_conf'] = $all['ad_conf'];
        $article_vendor_data['article_conf_day'] = $all['article_conf_day'];
        $article_vendor_data['charge'] = $all['charge'];
        $article_vendor_data['manner'] = $all['manner'];
        RelationVendorArticle::where('company_id', '=', $user->company_id)->
            where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];
        Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        // 物件価格履歴の更新
        if(isset($all['change_flag']) && $all['change_flag'] == 1) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article_id;
            $history_data['price'] = $all['change_price'];
            $history_data['regist_date'] = $all['change_price_date'];
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();

            $article_data = [];
            $article_data['price'] = $all['change_price'];

            Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        }


        return response()->json($all);
    }


    public function saveVendorBusiness(Request $request) {
        $user = Auth::user();

        $all = $request->all();

        $vendor_id_list = $all['id'];
        $article_id = $all['article_id'];

        $num = 0;
        foreach($vendor_id_list as $vendor_id) {
            // 物件ー業者情報の更新
            $article_vendor_data = [];
            $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'][$num];
            $article_vendor_data['flyer'] = $all['flyer'][$num];
            $article_vendor_data['freepaper'] = $all['freepaper'][$num];
            $article_vendor_data['house_hp'] = $all['house_hp'][$num];
            $article_vendor_data['portal'] = $all['portal'][$num];
            $article_vendor_data['signboard'] = $all['signboard'][$num];
            $article_vendor_data['ad_conf'] = $all['ad_conf'][$num];
            $article_vendor_data['article_conf_day'] = $all['article_conf_day'][$num];
            $article_vendor_data['charge'] = $all['charge'][$num];
            $article_vendor_data['manner'] = $all['manner'][$num];
            RelationVendorArticle::where('company_id', '=', $user->company_id)->
                where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

            $vendor = [];
            $vendor['vendor_tel1'] = $all['vender_tel'][$num];
            $vendor['vendor_fax'] = $all['vender_fax'][$num];

            Vendor::where('id', '=', $vendor_id)->update($vendor);
        }

        

        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];
        $article_data['bk'] = $all['bk'];
        $article_data['key_text'] = $all['key_text'];
        $article_data['memo1'] = $all['memo1'];
        Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        // 物件価格履歴の更新
        if(isset($all['change_flag']) && $all['change_flag'] == 1) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article_id;
            $history_data['price'] = $all['change_price'];
            $history_data['regist_date'] = $all['change_price_date'];
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();

            $article_data = [];
            $article_data['price'] = $all['change_price'];

            Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        }


        return response()->json($all);
    }

    public function changeDispUser(Request $request) {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        UserInfo::where('company_id', '=', $user->company_id)->where('employee_number', '=', $request->id)->update($data);
        return response()->json($response);
    }

    public function changeDispReform(Request $request) {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        Reform::where('code', '=', $request->id)->where('company_id', $user->company_id)->update($data);
        return response()->json($response);
    }

    public function changeDispNews(Request $request) {
        $response = [];
        $data = ['disp' => $request->check];
        News::where('id', '=', $request->id)->update($data);
        return response()->json($response);
    }

    public function changeDispStore(Request $request) {
        $response = [];
        $data = ['disp' => $request->check];
        MstStore::where('id', '=', $request->id)->update($data);
        return response()->json($response);
    }

    public function searchFacilityData(Request $request) {
        $res = 0;
        $all = $request->all();
        
        if($request->id == "") {
            $res = [
                'img' => '../../img/noimage2.jpg',
                'id' => '',
                'distance' => 0,
                'time' => 0
            ];
        } else {
            $result = Facility::getDataByCondition($all);
            $result->disp_file_path = str_replace('public', '/storage', $result->file_path);
            $distance = 0;
            if(isset($all['lat']) && isset($all['lng']) && isset($result->lat) && isset($result->lng)) {
                $distance = $this->calDistance($all['lat'], $all['lng'], $result->lat, $result->lng);
                $distance = $distance + (5 - $distance % 5) % 5;
            }
            
            $time = ceil($distance / 80);
            $res = [
                'img' => $result->disp_file_path,
                'id' => $result->id,
                'distance' => $distance,
                'time' => $time
            ];
        }
        
        return response()->json($res);
    }

    function calDistance($start_lat, $start_lng, $end_lat, $end_lng) {
        if($start_lat == null || $start_lng == null || $end_lat == null || $end_lng == null) {
            return 0;
        }
        //緯度、経度の移動量を計算
        $lat_dist = ($start_lat - $end_lat);
        if($lat_dist<0)$lat_dist=$lat_dist*-1;
        $lng_dist = ($start_lng - $end_lng);
        if($lng_dist<0)$lng_dist=$lng_dist*-1;


        //緯度位置における経度量を計算　地球は丸い
        $m_lng = 30.9221438 * cos($start_lat / 180 * pi());
        if($m_lng<0)$m_lng=$m_lng*-1;

        //移動量を計算
        $distance = (int)(sqrt(pow(abs($lat_dist / 0.00027778 * 30.9221438), 2) + pow(abs($lng_dist / 0.00027778 * $m_lng), 2)));

        return $distance;
    }

    function convertImageSource($imgData) {
        $base64 = base64_encode($imgData);
        $mime = 'image/jpg';
        return 'data:'.$mime.';base64,'.$base64;
    }
    
    function get_gps_from_address(Request $request){
        $res = array();
        if($request->address != "") {
            $req = 'http://www.geocoding.jp/api/?q=';
            $req .= urlencode($request->address);  
            $xml = simplexml_load_file($req) or die('XML parsing error');
            $location = $xml->coordinate;
            $res['lat'] = (string)$location->lat;
            $res['lng'] = (string)$location->lng;
        }

        return response()->json($res);
    }

    function getParking(Request $request) {
        $res = [];
        $type = 0;
        if($request->property < 6) {
            $type = 2;
        } else {
            $type = 1;
        }
        if($type != 0) {
            $res = MstParking::getDataByType($type);
        }

        return $res;
    }

    function saveVendor(Request $request) {

        if(empty($request -> id)) {
            $vendor = new Vendor;
            $vendor -> name = $request -> name;
            $vendor -> manner = $request -> manner;
            $vendor -> vendor_tel1 = $request -> vendor_tel1;
            $vendor -> vendor_fax = $request -> vendor_fax;
            $vendor -> vendor_charge = $request -> vendor_charge;
            $vendor -> flyer = $request -> flyer;
            $vendor -> freepaper = $request -> freepaper;
            $vendor -> house_hp = $request -> house_hp;
            $vendor -> portal = $request -> portal;
            $vendor -> signboard = $request -> signboard;
            $vendor -> ad_conf_day = $request -> ad_conf_day;
            $vendor->save();
        } else {
            $vendor = Vendor::where('id', $request -> id)->first();
            $vendor -> name = $request -> name;
            $vendor -> manner = $request -> manner;
            $vendor -> vendor_tel1 = $request -> vendor_tel1;
            $vendor -> vendor_fax = $request -> vendor_fax;
            $vendor -> vendor_charge = $request -> vendor_charge;
            $vendor -> flyer = $request -> flyer;
            $vendor -> freepaper = $request -> freepaper;
            $vendor -> house_hp = $request -> house_hp;
            $vendor -> portal = $request -> portal;
            $vendor -> signboard = $request -> signboard;
            $vendor -> ad_conf_day = $request -> ad_conf_day;
            $vendor->save();
        }

        

        echo $vendor->id; 


    }

    function convertEOL($string, $to = "\r\n") {   
        return preg_replace("/\r\n|\r|\n/", $to, $string);
    }

    public function searchVendor(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $vendor = Vendor::query();
        $vendor->where('company_id', $user->company_id);
        if(isset($request->name)) {
            $vendor->where('name', 'LIKE', '%'.$request->name.'%');
        }
        if(isset($request->shop)) {
            $vendor->where('store', '=', $request->shop);
        }
        if(isset($request->tel)) {
            $vendor->where('vendor_tel1', '=', $request->tel);
        }
        if(isset($request->fax)) {
            $vendor->where('vendor_fax', '=', $request->fax);
        }
        if(isset($request->dup)) {
            $id_list = explode(',', $request->dup);
            $vendor->whereNotIn('id', $id_list);
        }

        $response = $vendor->get();
        
        return response()->json($response);
    }

    public function saveChangeVendor(Request $request) {
        $response = $request->change;
        // dump($request->vendor);

        return response()->json($response);
    }

    public function delProvisional(Request $request) {
        $user = Auth::user($request);
        $response = [];
        $id = $request->del;
        $save = ['del' => 1];
        Article::where('building_id', '=', $id)->where('company_id', '=', $user->company_id)->update($save);

        return response()->json($response);
    }

    public function searchLot(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $article = Article::query();
        $article->where('property', '=', 99);
        $article->where('company_id', '=', $user->company_id);
        if(isset($request->name)) {
            $article->where('search_lot_name', 'LIKE', '%'.$request->name.'%');
        }
        if(isset($request->num)) {
            $article->where('building_id', '=', $request->num);
        }
        if(isset($request->address1)) {
            $article->where('address1', '=', $request->address1);
        }
        if(isset($request->address2)) {
            $article->where('address2', '=', $request->address2);
        }
        if(isset($request->address3)) {
            $article->where('address3', '=', $request->address3);
        }

        $response = $article->get();
        
        return response()->json($response);
    }

    public function searchLotBuild(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $article = Article::query();
        $article->where('property', '=', 99);
        $article->where('company_id', '=', $user->company_id);

        if(isset($request->address1)) {
            $article->where('address1', '=', $request->address1);
        }
        if(isset($request->address2)) {
            $article->where('address2', '=', $request->address2);
        }
        if(isset($request->address3)) {
            $article->where('address3', '=', $request->address3);
        }
        if(isset($request->address4)) {
            $article->where('address3', '=', $request->address3);
        }

        $response = $article->get();
        
        return response()->json($response);
    }

    public function saveTmpImageStore(Request $request) {
        $response = [];
        if(isset($request->tmp_image)) {

            $num = $request->num;
            $extension = $request->tmp_image->getClientOriginalExtension();
            $photo_data = [
                'file_type' => $extension,
            ];
            $photo = TempImageStore::create($photo_data);

            $image_url = $request->tmp_image->storeAs('public/tmp', 'photo_image_xxx_'.$photo->id.'.'. $extension);
            $photo_data = [
                'file_path' => $image_url,
            ];
            TempImageStore::where('id', '=', $photo->id)->update($photo_data);

            $response = $photo->id;
        }

        return response()->json($response);
    }

    public function saveTmpImageReform(Request $request) {
        $response = [];
        if(isset($request->tmp_image)) {

            $num = $request->num;
            $extension = $request->tmp_image->getClientOriginalExtension();
            $photo_data = [
                'file_type' => $extension,
            ];
            $photo = TempImageReform::create($photo_data);

            $image_url = $request->tmp_image->storeAs('public/tmp', 'photo_image_xxx_'.$photo->id.'.'. $extension);
            $photo_data = [
                'file_path' => $image_url,
            ];
            TempImageReform::where('id', '=', $photo->id)->update($photo_data);

            $response = $photo->id;
        }

        return response()->json($response);
    }

    public function delReformTmpImage(Request $request) {
        $response = [];
        $tmp = TempImageReform::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        TempImageReform::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function delStoreTmpImage(Request $request) {
        $response = [];
        $tmp = TempImageStore::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        TempImageStore::where('id', $request->id)->delete();
        return response()->json($response);
    }
    public function delReformImage(Request $request) {
        $response = [];
        $tmp = RelationReformPhoto::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);
        
        RelationReformPhoto::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function delStoreImage(Request $request) {
        $response = [];
        $tmp = RelationStorePhoto::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);
        
        RelationStorePhoto::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function getSearchCount(Request $request) {
        $count = Article::getSearchDataByCondition($request, null, null, 2, 1);
        return $count;
    }
    public function getSearchCountClose(Request $request) {
        $count = Article::getSearchDataByCondition($request, null, null, 1, 1);
        return $count;
    }
    public function getSearchCountMansion(Request $request) {
        $count = Article::getMansionDataByCondition($request, null, null, null, 1);
        return $count;
    }
    public function getSearchCountLot(Request $request) {
        $count = Article::getSearchDataByCondition($request, null, null, null, 1);
        return $count;
    }
    public function delArticle(Request $request) {
        $response = [];
        $user = Auth::user();
        $data = ['del' => 1];
        $id = $request->id;
        Article::where('building_id', '=', $id)->where('company_id', '=', $user->company_id)->update($data);
        return response()->json($response);
    }

    public function saveSearchVendor(Request $request) {
        $user = Auth::user();
        $article_id = $request->target_article;
        $vendor_id = $request->vendor_id;

        $all = $request->all();

        $article_vendor_data = [];
        $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'];
        $article_vendor_data['flyer'] = $all['flyer'];
        $article_vendor_data['freepaper'] = $all['freepaper'];
        $article_vendor_data['house_hp'] = $all['house_hp'];
        $article_vendor_data['portal'] = $all['portal'];
        $article_vendor_data['signboard'] = $all['signboard'];
        $article_vendor_data['ad_conf'] = $all['ad_conf'];
        $article_vendor_data['article_conf_day'] = $all['article_conf_day'];
        $article_vendor_data['charge'] = $all['charge'];
        $article_vendor_data['manner'] = $all['manner'];
        RelationVendorArticle::where('company_id', '=', $user->company_id)->
            where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];

        $article_data['bk'] = $all['bk'];
        $article_data['key_text'] = $all['key_text'];
        $article_data['memo1'] = $all['memo1'];

        Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        // 物件価格履歴の更新
        if(isset($all['change_flag']) && $all['change_flag'] == 1) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article_id;
            $history_data['price'] = $all['change_price'];
            $history_data['regist_date'] = $all['change_price_date'];
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();

            $article_data = [];
            $article_data['price'] = $all['change_price'];

            Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        }


    }

    public function uploadArticleImage(Request $request) {

        $photo = $request->image;
        $id = $request->article_id;

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

        $len = $max+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_'.$id.'_'.$len.'.'. $extension);

        $image_url = 'public/photo/photo_image_'.$id.'_'.$len.'.'. $extension;

        $photo_data = [
            'article_id' => $id,
            'file_path' => $image_url,
            'file_type' => $extension,
            'file_disp' => 0,
            // 'property' => $request->{'photo_property'.$num},
            // 'property_sub' => $request->{'photo_property_sub'.$num},
            // 'memo' => $request->{'photo_comment'.$num},
            // 'order' => $runk,
        ];
        $obj = RelationArticlePhoto::create($photo_data);



        return response()->json($obj->id);
    }
}

