<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\RainsPost;
use App\Models\Article;
use Illuminate\Support\Facades\Auth;
use App\Models\RelationVendorArticle;
use App\Models\RelationPriceHistory;
use App\Models\RelationDuplicateVendorArticle;
use App\Models\RainsDuplicateArticle;
use App\Models\RainsDuplicateVendor;;
use App\Models\MstPrefecture;   
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstPropertyType;
use App\Models\MstStatus;
use App\Models\MstManner;
use App\Models\MstLine;
use App\Models\MstStation;
use App\Models\MstStore;

class RainsController extends Controller
{
    /**
     * @return string
     */
    public function show()
    {
        $user = Auth::user();

        // 登録予定データの取得
        $duplication_article = RainsDuplicateArticle::getDuplicateData($user->company_id, 1);

        // if($duplication_article->total() != 0) {
        //     $URL = url('');
        //     header('Location: '.$URL.'/admin/duplicateCsv');
        //     die();
        // }
        return view('admin.pages.rains');
    }

    /**
     * @return string
     */
    public function showSuccess()
    {
        return view('admin.pages.rains-success');
    }

    /**
     * @return string
     * 
     */
    public function showDuplicate(Request $request)
    {
        $user = Auth::user();
        $data['data'] = null;
        $selected = $user->store_id;

        $params = $request->all();

        $total_count = RainsDuplicateArticle::getCountDuplicateData($user->company_id);
        // if($total_count == 0) {
        //     $URL = url('');
        //     header('Location: '.$URL.'/admin/rainsCsv');
        //     die();
        // }

        $data['uri'] = '';
        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'];
        }

        // 登録予定データの取得
        $duplication_article = RainsDuplicateArticle::getDuplicateData($user->company_id, 1, null, $selected);
      
        if($duplication_article->total() > 0) {
            if($duplication_article->lastPage() < $duplication_article->currentPage()) {
                $URL = url('');
                header('Location: '.$URL.'/admin/duplicateCsv?page='.$duplication_article->lastPage());
                die();
            }

            $target_article = $duplication_article[0];
            $data['data'] = $duplication_article;
            $data['duplicate_article'] = $this->moldingData($target_article);

            // 業者情報の取得
            $duplication_vendor = RelationDuplicateVendorArticle::getRelationVendorInfo($target_article->id);
            $data['duplicate_vendor'] = $duplication_vendor;
            // 重複データの取得
            $saved_duplicate = $this->checkDuplicate($target_article);
if (request("debug")) {dd($saved_duplicate);}
            $saved = [];
            foreach($saved_duplicate as $key => $row) {
                if($key < 4) {
                    $tmp = [];
                    foreach($row as $item) {
                        $tmp[] = [ 'item' => $this->moldingData($item), 'vendor_list' => RelationVendorArticle::getVendorDataByRainsNo($item->building_id)];
    
                    }
                    $saved[] = $tmp;
                } else {
                    $tmp = [];
                    foreach($row as $mansion) {
                        // 部屋を取得
                        $room_list = Article::getRoomList($mansion->building_id);
                        $tmp_room = [];
                        foreach($room_list as $room) {
                            $tmp_room[] = [ 'item' => $this->moldingData($room), 'vendor_list' => RelationVendorArticle::getVendorDataByRainsNo($room->building_id)];
                        }

                        $mansion->room_list = $tmp_room;

                        $tmp[] = [ 'item' => $this->moldingData($mansion), 'vendor_list' => RelationVendorArticle::getVendorDataByRainsNo($mansion->building_id)];

                    }
                    $saved[] = $tmp;
                }
                
            }

            $data['saved_article'] = $saved;

            

            // 処理種別
            $target = [];

            if(empty($saved_duplicate[0]) && empty($saved_duplicate[1]) && $saved_duplicate[2]->isEmpty() && empty($saved_duplicate[3]) && empty($saved_duplicate[4])) {
                if($target_article->property == 6 || $target_article->property == 7) {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                } else {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '1', 'name' => '仮登録'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                }

            } else {
                if($target_article->property == 6 || $target_article->property == 7) {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '2', 'name' => '重複'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                } else {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '1', 'name' => '仮登録'],
                        ['code' => '2', 'name' => '重複'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                }

            }
            $data['target'] = $target;
        }
        
        // 要確認状態のデータ件数取得
        $count = RainsDuplicateArticle::getCountHoldData($user->company_id, $selected);
        $data['hold_count'] = $count;
        

        // 店舗一覧
        $data['store'] = MstStore::getDataAll($user->company_id);
        $data['selected_store'] = $selected;

        // ステータス
        $data['statuses'] = MstStatus::getData();

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

        $ad_conf = [
            ['code' => 1, 'name' => '未'],
            ['code' => 2, 'name' => '可'],
            ['code' => 3, 'name' => '不可'],
        ];
        $data['ad_conf'] = $ad_conf;

        // 確認手法
        $method_conf = [
            ['code' => 1, 'name' => 'TEL'],
            ['code' => 2, 'name' => 'FAX'],
        ];
        $data['method_conf'] = $method_conf;

        $data['active'] = "con1";
        $data['params'] = $params;
         return view('admin.pages.rains-duplicate', $data);

    }

        /**
     * @return string
     */
    public function showHoldDuplicate(Request $request)
    {
        $user = Auth::user();
        $data['data'] = null;
        $selected = $user->store_id;

        $params = $request->all();

        $count = RainsDuplicateArticle::getCountDuplicateData($user->company_id);
        if($count == 0) {
            $URL = url('');
            header('Location: '.$URL.'/admin/rainsCsv');
            die();
        }

        $data['uri'] = '';
        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'];
        }

        // 登録予定データの取得
        $duplication_article = RainsDuplicateArticle::getDuplicateData($user->company_id, 1, 1, $selected);
        if($duplication_article->total() > 0) {
            if($duplication_article->lastPage() < $duplication_article->currentPage()) {
                $URL = url('');
                header('Location: '.$URL.'/admin/holdDuplicateCsv?page='.$duplication_article->lastPage());
                die();
            }

            $target_article = $duplication_article[0];
            $data['data'] = $duplication_article;
            $data['duplicate_article'] = $this->moldingData($target_article);

            // 業者情報の取得
            $duplication_vendor = RelationDuplicateVendorArticle::getVendorDataByRainsNo($target_article->id);
            $data['duplicate_vendor'] = $duplication_vendor;

            // 重複データの取得
            $saved_duplicate = $this->checkDuplicate($target_article);
            $saved = [];
            foreach($saved_duplicate as $row) {
                $tmp = [];
                foreach($row as $item) {
                    $tmp[] = [ 'item' => $this->moldingData($item), 'vendor_list' => RelationVendorArticle::getVendorDataByRainsNo($item->building_id)];

                }
                $saved[] = $tmp;
            }

            $data['saved_article'] = $saved;

            

            // 処理種別
            $target = [];

            if(empty($saved_duplicate[0]) && empty($saved_duplicate[1]) && $saved_duplicate[2]->isEmpty() && empty($saved_duplicate[3]) && empty($saved_duplicate[4])) {
                if($target_article->property == 6 || $target_article->property == 7) {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                } else {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '1', 'name' => '仮登録'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                }

            } else {
                if($target_article->property == 6 || $target_article->property == 7) {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '2', 'name' => '重複'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                } else {
                    $target = [
                        ['code' => '0', 'name' => '選択する'],
                        ['code' => '1', 'name' => '仮登録'],
                        ['code' => '2', 'name' => '重複'],
                        ['code' => '3', 'name' => '要確認'],
                        ['code' => '4', 'name' => '削除'],
                    ];
                }

            }
            $data['target'] = $target;
        }
        
        // 要確認状態のデータ件数取得
        $count = RainsDuplicateArticle::getCountHoldData($user->company_id);
        $data['hold_count'] = $count;
        

        // 店舗一覧
        $data['store'] = MstStore::getDataAll($user->company_id);
        $data['selected_store'] = $selected;

        // ステータス
        $data['statuses'] = MstStatus::getData();

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

        $ad_conf = [
            ['code' => 1, 'name' => '未'],
            ['code' => 2, 'name' => '可'],
            ['code' => 3, 'name' => '不可'],
        ];
        $data['ad_conf'] = $ad_conf;

        // 確認手法
        $method_conf = [
            ['code' => 1, 'name' => 'TEL'],
            ['code' => 2, 'name' => 'FAX'],
        ];
        $data['method_conf'] = $method_conf;

        $data['active'] = "con1";
        $data['params'] = $params;
        $data['hold'] = 1;
         return view('admin.pages.rains-duplicate', $data);

    }

    function editDuplicate(RainsPost $request) {
        $uri = '';
        if(isset($request->store)) {
            $uri = '?store='.$request->store;
        }

        if($request->target == 1) {
            // 仮登録
            $this->saveRainsDataNew($request);
        } elseif($request->target == 2) {
            // 重複
            $this->saveRainsDataDuplicate($request);
        } elseif($request->target == 3) {
            // 要確認
            $this->saveRainsDataHold($request);
        } elseif($request->target == 4) {
            // 削除
            $this->deleteRainsData($request);
        } elseif($request->target == 5) {
            // マンション部屋
            $this->saveRoomData($request);
        }

        $URL = url('');
        header('Location: '.$URL.'/admin/duplicateCsv'.$uri);
        die();
    }

    function editHoldDuplicate(RainsPost $request) {
        $uri = '';
        if(isset($request->store)) {
            $uri = '?store='.$request->store;
        }

        if($request->target == 1) {
            // 仮登録
            $this->saveRainsDataNew($request);
        } elseif($request->target == 2) {
            // 重複
            $this->saveRainsDataDuplicate($request);
        } elseif($request->target == 3) {
            // 要確認
            $this->saveRainsDataHold($request);
        } elseif($request->target == 4) {
            // 削除
            $this->deleteRainsData($request);
        } elseif($request->target == 5) {
            // マンション部屋
            $this->saveRoomData($request);
        }



        $URL = url('');
        header('Location: '.$URL.'/admin/holdDuplicateCsv'.$uri);
        die();
    }


    function saveRainsDataNew($request) {
        $user = Auth::user();
        $duplication_article_id = $request->duplicate_id;
        $relation_article = RelationDuplicateVendorArticle::where('article_id', '=', $duplication_article_id)->first();

        // 実物件へ登録
        $duplication_data = RainsDuplicateArticle::find($duplication_article_id);

        // 企業内の物件の最大idを取得
        $building_id = Article::getMaxNo($user->company_id);
        if(empty($building_id)) {
            $building_id = 0;
        }

        $building_id = $building_id + 1;
        $org_building_id = $building_id;
        $duplication_data->building_id = $building_id;
        $duplication_data->disp = 0;
        $duplication_data->provisional = 1;
        $duplication_data->store = $user->store_id;
        $price = 0;
        $room_num = "";
        if($duplication_data->property == 6 || $duplication_data->property == 7) {
            $duplication_data->name_apartment = $duplication_data->name;
            $price = $duplication_data->price;
            $room_num = $duplication_data->room_num;
            $duplication_data->price = null;
            $duplication_data->room_num = null;
            $duplication_data->status = null;
        }
        
        

        $article = new Article;
        $article->fill($duplication_data->toArray())->save();

        // 物件と業者のひも付きを登録
        $relation = [
            'company_id' => $user->company_id,
            'article_id' => $org_building_id,
            'vendor_id' => $relation_article->vendor_id,
            'charge' => $relation_article->charge,
        ];

        $relation = RelationVendorArticle::firstOrNew(['article_id' => $org_building_id, 'vendor_id' => $relation_article->vendor_id], $relation);
        $relation->save();

        // 価格ー物件情報の更新
        $history_obj = new RelationPriceHistory;
        $history = [
            'company_id' => $user->company_id,
            'article_id' => $org_building_id,
            'price' => $duplication_data->price,
            'regist_date' => date("Y/m/d")
        ];
        $history_obj->fill($history)->save();

        if($duplication_data->property == 6 || $duplication_data->property == 7) {
            // マンション部屋の登録
            $building_id = $building_id + 1;
            $article_room = new Article;
            $duplication_data->room_num = $room_num;
            $duplication_data->property = null;
            $duplication_data->property_sub = null;
            $duplication_data->price = $price;
            $duplication_data->mansion_id = $org_building_id;
            $duplication_data->building_id = $building_id;

            $article_room->fill($duplication_data->toArray())->save();

            // 物件と業者のひも付きを登録
            $relation = [
                'article_id' => $building_id,
                'vendor_id' => $relation_article->vendor_id,
                'charge' => $relation_article->charge,
            ];
            $relation = RelationVendorArticle::firstOrNew(['article_id' => $building_id, 'vendor_id' => $relation_article->vendor_id], $relation);
            $relation->save();

            // 価格ー物件情報の更新
            $history_obj = new RelationPriceHistory;
            $history = [
                'article_id' => $building_id,
                'price' => $duplication_data->price,
                'regist_date' => date("Y/m/d")
            ];
            $history_obj->fill($history)->save();

        }


        // 予定物件と業者のひも付きを削除
        RelationDuplicateVendorArticle::where('article_id', '=', $duplication_article_id)->where('vendor_id', '=', $relation_article->vendor_id)->delete();

        // 予定物件の削除
        $duplication_data->delete();

    }

    function saveRainsDataDuplicate($request) {
        $user = Auth::user();
        $target = $request->change_target[0];

        // レインズ元データの取得
        $rains = RainsDuplicateArticle::find($request->duplicate_id);
        // 物件情報の更新
        $article = [];
        if(isset($request->{'change_flag_'.$target})) {
            $article['price'] = $rains->price;
        }
        
        $article['status'] = $request->{'status_'.$target};
        if(!is_null($request->{'price_closing_'.$target})) {
            $article['price_closing'] = $request->{'price_closing_'.$target};
            $article['close_date'] = date('Y/m/d');
        }

        Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->{'article_id_'.$target})->update($article);

        // 業者情報の更新
        // 対象を取得
        $target_vendor_list = $request->{'vendor_id_'.$target};
        if(!is_null($target_vendor_list)) {
            foreach($target_vendor_list as $vendor) {
                $vendor_obj = RelationVendorArticle::where('company_id', '=', $user->company_id)->where('article_id', '=', $request->{'article_id_'.$target})->where('vendor_id', '=', $vendor)->first();
                $vendor_data = [
                    'company_id' => $user->company_id,
                    'vendor_id' => $vendor,
                    'article_id' => $request->{'article_id_'.$target},
                    'charge' => $request->{'charge_'.$target.'_'.$vendor},
                    'manner' => $request->{'manner_'.$target.'_'.$vendor},
                    'ad_conf_day' => $request->{'ad_conf_day_'.$target.'_'.$vendor},
                    'flyer' => $request->{'flyer_'.$target.'_'.$vendor},
                    'freepaper' => $request->{'freepaper_'.$target.'_'.$vendor},
                    'house_hp' => $request->{'house_hp_'.$target.'_'.$vendor},
                    'portal' => $request->{'portal_'.$target.'_'.$vendor},
                    'signboard' => $request->{'signboard_'.$target.'_'.$vendor},
                    'ad_conf' => $request->{'ad_conf_'.$target.'_'.$vendor},
                    'article_conf_day' => $request->{'article_conf_day_'.$target.'_'.$vendor},
                ];
                if(is_null($vendor_obj)) {
                    $vendor_obj = new RelationVendorArticle;
                }
                $result = $vendor_obj->fill($vendor_data)->save();
            }
        }
        

        // 価格ー物件情報の更新
        $history_obj = new RelationPriceHistory;
        $history = [
            'company_id' => $user->company_id,
            'article_id' => $request->{'article_id_'.$target},
            'price' => $rains->price,
            'regist_date' => date("Y/m/d")
        ];
        $history_obj->fill($history)->save();

        // 予定物件と業者のひも付きを削除
        $relation_article = RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->first();
        if(!is_null($relation_article)) {
            RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->where('vendor_id', '=', $relation_article->vendor_id)->delete();
        }


        // 予定物件の削除
        $rains->delete();
    }

    function saveRainsDataHold($request) {
        // レインズ元データの更新
        $data = [
            'hold' => 1
        ];

        RainsDuplicateArticle::where('id', $request->duplicate_id)->update($data);
    }

    function deleteRainsData($request) {

        // レインズ元データの取得
        $rains = RainsDuplicateArticle::where('id', '=', $request->duplicate_id)->delete();
        $relation_article = RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->first();


        // 予定物件と業者のひも付きを削除
        RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)
            ->where('vendor_id', '=', $relation_article->vendor_id)->delete();
    }

    function moldingData($row) {
        $tmp = [];
        $tmp['id'] = $row->id;
        $tmp['building_id'] = $row->building_id??'';
        $tmp['rains_no'] = $row->rains_no;
        $tmp['name'] = $row->article_name;
        $tmp['status'] = $row->status;
        $tmp['address'] = $row->pref_name.$row->city_name.$row->town_name.$row->address;
        $tmp['price'] = $row->price;
        $tmp['price_closing'] = $row->price_closing;
        $tmp['land_area_val'] = $row->land_area_val;
        $school = empty($row->primary_school_school)? "-":$row->primary_school_school;
        $school .= '/';
        $school .= empty($row->secondary_school_school)? "-":$row->secondary_school_school;
        $tmp['school'] = $school;
        if($row->property != null) {
            $property = MstPropertyType::getData($row->property);
            $tmp['property'] = $property[0]['name'];
        } else {
            $tmp['property'] = "マンション（部屋）";
        }
        $tmp['property_num'] = $row->property;
        $floor_plan = "-";
        if($row->floor_type == 1) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "DK";
        } elseif($row->floor_type == 2) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "LDK";
        } elseif($row->floor_type == 3) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "R";
        } elseif($row->floor_type == 4) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "K";
        } elseif($row->floor_type == 5) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "SK";
        } elseif($row->floor_type == 6) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "SDK";
        } elseif($row->floor_type == 7) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "LK";
        } elseif($row->floor_type == 8) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "SLK";
        } elseif($row->floor_type == 9) {
            $floor_plan = $row->floor_plan;
            $floor_plan .= "SLDK";
        }
        $tmp['room_num'] = $row->room_num;
        $tmp['floor_plan'] = $floor_plan;
        $time = empty($row->main_traffic_time)? "-":$row->main_traffic_time;
        $tmp['traffic'] = $row->main_traffic_line;
        $tmp['traffic'] .= ' 「'. $row->main_traffic_station . '」';
        $tmp['traffic'] .= ' 徒歩' . $time . '分';
        $age = empty($row->age_year)? "-":$row->age_year;
        $age .= '/';
        $age .= empty($row->age_month)? "-":$row->age_month;
        $tmp['age'] = $age;
        $tmp['area'] = $row->total_area_val;
        $floor = empty($row->floor)? "-":$row->floor;
        $floor .= '階/';
        $floor .= empty($row->whereabouts)? "-":$row->whereabouts;
        $floor .= '階';
        $tmp['floor'] = $floor;

        if(isset($row->room_list)) {
            $tmp['room_list'] = $row->room_list;
        } else {
            $tmp['room_list'] = [];
        }
        

        return $tmp;
    }

    function checkDuplicate($data) {
        $res = [];
        
        // 市・土地面積
        if($data->land_area_val == null) {
            $res[] = [];
        } else {
            $res[] = Article::getDuplicateAritcleData(1, $data);
        }
        
        // 市・建物面積
        if($data->total_area_val == null) {
            $res[] = [];
        } else {
            $res[] = Article::getDuplicateAritcleData(2, $data);
        }

        // 市・丁目・物件種別
        $res[] = Article::getDuplicateAritcleData(3, $data);


        // マンション名
        if($data->property == 6 || $data->property == 7) {
            $res[] = Article::getDuplicateAritcleData(4, $data);
        } else {
            $res[] = [];
        }

        if($data->property == 6 || $data->property == 7) {
            // 市・丁目・物件種別
            $mansion_list = Article::getDuplicateAritcleData(5, $data);
            $res[] = $mansion_list;
        } else {
            $res[] = [];
        }

        
        
        return $res;
    }

    function saveRoomData($request) {

        $user = Auth::user();
        $target = $request->m_target;
        $target_list = explode('_', $target);

        // レインズ元データの取得
        $rains = RainsDuplicateArticle::find($request->duplicate_id);

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

        $mansion_comment = Article::getComment($user->company_id, $target_list[0]);

        $rains->building_id = $building_id+1;
        $rains->property = null;
        $rains->property_sub = null;
        $rains->mansion_id = $target_list[0];
        $rains->disp = 0;
        $rains->provisional = 1;
        $rains->comment = $mansion_comment->comment;

        $article = new Article;
        $article->fill($rains->toArray())->save();

        $relation_article = RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->first();
        if(!is_null($relation_article)) {
            // 物件と業者のひも付きを登録
            $relation = [
                'company_id' => $user->company_id,
                'article_id' => $building_id+1,
                'vendor_id' => $relation_article->vendor_id,
                'charge' => $relation_article->charge,
            ];
            $relation = RelationVendorArticle::firstOrNew(['article_id' => $building_id+1, 'vendor_id' => $relation_article->vendor_id], $relation);
            $relation->save();

            // 予定物件と業者のひも付きを削除
            $relation_article = RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->first();
            RelationDuplicateVendorArticle::where('article_id', '=', $request->duplicate_id)->where('vendor_id', '=', $relation_article->vendor_id)->delete();
        }
        

        

        // 予定物件の削除
        $rains->delete();

    }

    
}
