<?php

namespace App\Http\Controllers\Business;

use App\Http\Requests\Buyer\StoreRequest;
use App\Models\Article;
use App\Models\Buyer;
use App\Models\MstCity;
use App\Models\MstFloorType;
use App\Models\MstGenkyou;
use App\Models\MstManner;
use App\Models\MstPrefecture;
use App\Models\MstPropertyType;
use App\Models\MstPropertyTypeSub;
use App\Models\MstSchool;
use App\Models\MstStatus;
use App\Models\MstTown;
use App\Models\RelationArticlePhoto;
use App\Models\RelationPriceHistory;
use App\Models\Vendor;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BuyerController extends Controller
{
    public function index()
    {
        $data = [];
        $buyers = Buyer::getDataByUser();
        $data['buyers'] = $buyers;
        return view('business.pages.buyer.index', $data);
    }

    public function store(StoreRequest $request)
    {
        $name = $request->get('name');
        $user = auth()->user();
        if (!empty($name)) {
            $buyer = Buyer::create([
                'user_id' => $user->id,
                'name' => $name
            ]);

            if ($request->ajax()) {
                $ids = $request->get('ids');
                $ids = explode(',', $ids);
                if (!empty($ids)) {
                    foreach ($ids as $article_id) {
                        if (!empty($article_id)) {
                            if (empty( $buyer->articles()->where('article_id', $article_id)->first())) {
                                $buyer->articles()->create(['article_id'=> $article_id]);
                            }
                        }
                    }
                }

                session(['buyer_active' => $buyer]);

                return 1;
            }
            $request->session()->flash('success', '「'.$name.'」ボードを新規作成しました。');
            return redirect()->route('buyer.append', [$buyer->id]);
        }

    }

    public function append($id, Request $request)
    {
        $all = $request->all();

        $data = [];
        $buyer = Buyer::findOrFail($id);
        session(['buyer_active' => $buyer]);
        $user = auth()->user();
        $forgetItem = 0;
        $article_list = $buyer->articles();

        $sort = \request()->get('sort');
        $type = !empty(\request()->get('type')) ? \request()->get('type') : 'asc';
        if ($sort == 'created_at') {
            $article_list = $article_list->orderBy($sort, $type);
        }

        if (empty($sort)) {
            $article_list = $article_list->orderBy('created_at', 'desc');
        }

        $article_list = $article_list->get();

        $floor_type_list = MstFloorType::getData();
        $floor_type = [];
        foreach ($floor_type_list as $row) {
            $floor_type[$row['code']] = $row['name'];
        }

        foreach ($article_list as $key => &$row) {
            if(isset($all['status'])){
                if(in_array($row->article->status, [1,2,3])){
                    $article_list[$key] = Article::getDataById($row->article->building_id, $row['article_id']);
                    if($article_list[$key] != null){
                        $article_list[$key]->joined_day = $row->created_at;
                    }
                }else{
                    unset($article_list[$key]);
                }
            }else{
                $article_list[$key] = Article::getDataById($row->article->building_id, $row['article_id']);
                if($article_list[$key] != null){
                    $article_list[$key]->joined_day = $row->created_at;
                }
            }
        }


        if ($sort == 'price') {
            $article_list = $article_list->sortBy($sort);
            if ($type == 'desc') {
                $article_list = $article_list->reverse();
            }
        }
        $j = 0;
        if (!$article_list->isEmpty()) {
            foreach ($article_list as &$row) {
                if ($row != null) {
                    $row->article_name = $row->name;
                    // NEW判定
                    if ($row->created_at > date("Y-m-d", strtotime("-" . config('const.NEW') . " day"))) {
                        $row->new = true;
                    } else {
                        $row->new = false;
                    }
                    if ($row != false) {
                        $j++;
                        $row->article_name = $row->name;
                        // NEW判定
                        if ($row->created_at > date("Y-m-d", strtotime("-" . config('const.NEW') . " day"))) {
                            $row->new = true;
                        } else {
                            $row->new = false;
                        }

                        $address = "";
                        if (isset($row->address1)) {
                            $add = MstPrefecture::getData($row->address1);
                            if (!empty($add)) {
                                $address .= $add[0]["name"];
                            }
                        }
                        if (isset($row->address2)) {
                            $add = MstCity::getData($row->address1, $row->address2);
                            if (!empty($add)) {
                                $address .= $add[0]["name"];
                            }
                        }
                        if (isset($row->address3)) {
                            $add = MstTown::getData($row->address1, $row->address2, $row->address3);
                            if (!empty($add)) {
                                $address .= $add[0]["name"];
                            }
                        }
                        if (isset($row->address4)) {
                            $address .= $row->address4;
                        }
                        $row->address = $address;
                        if (isset($row->floor_plan_type)) {
                            $row['floor_plan_text'] = $row->floor_plan . $floor_type[$row->floor_plan_type];

                        }
                        if (isset($row->current_status)) {
                            $status = MstGenkyou::getDataByCode($row->current_status);
                            $row->current_status = $status->name ?? '';
                        }
                        if (isset($row->age_month)) {
                            $row->age = intval(date('Y')) - intval($row->age_year);
                        }

                        if (isset($row->primary_school_school)) {
                            $primary = MstSchool::getSchoolByCode($row->primary_school_school);
                            if (isset($primary->name)) {
                                $row->primary_school_name = str_replace('学校', '', $primary->name);
                            }
                        }
                        if (isset($row->secondary_school_school)) {
                            $secondary = MstSchool::getSchoolByCode($row->secondary_school_school);
                            if (isset($secondary->name)) {
                                $row->secondary_school_name = str_replace('学校', '', $secondary->name);
                            }
                        }

                        // 間取り画像取得
                        $count = 0;
                        if (isset($row->floor_file_path)) {
                            $row->floor_file_path = str_replace('public', '/storage', $row->floor_file_path);
                            $count = 1;
                        } else {
                            $row->floor_file_path = '';
                        }

                        // 写真
                        $top_image = RelationArticlePhoto::getTopImagePath($row->building_id);
                        if (isset($top_image->file_path)) {
                            $row->top_file_path = str_replace('public', '/storage', $top_image->file_path);
                        } else {
                            $row->top_file_path = '';
                        }

                        // 写真の枚数
                        $count = RelationArticlePhoto::getCountImgByArticleId($row->building_id);
                        $row->file_count = $count;

                        // 価格履歴の取得
                        $history = RelationPriceHistory::getHistoryById($row->building_id);
                        $row->history = $history;

                        if (!empty($row->mansion_id)) {
                            $row->mansion_file_count = RelationArticlePhoto::getCountImgByArticleId($row->mansion_id, 1);
                            $row->file_count = RelationArticlePhoto::getCountImgByArticleId($row->building_id, 2);
                            $row->image_mansion = RelationArticlePhoto::getTopImagePath($row->mansion_id);
                        } elseif ($row->property == 4 || $row->property == 5) {
                            $row->mansion_file_count = RelationArticlePhoto::getCountImgByArticleId($row->building_id, 1);
                            $row->file_count = RelationArticlePhoto::getCountImgByArticleId($row->building_id, 2);
                        }

                    // 物件種別名、業者取得
                    if (is_null($row->property)) {
                        // マンションの場合
                        $mansion = Article::getDataById($row->mansion_id);

                            if ($mansion) {
                                $row->property_name = $this->getPropertyName($mansion->property, $mansion->property_sub);
                                $vendor_info = Vendor::getDataListByArticleId($row->building_id);

                                // 学校
                                if (isset($mansion->primary_school_school)) {
                                    $primary = MstSchool::getSchoolByCode($mansion->primary_school_school);
                                    if (isset($primary->name)) {
                                        $row->primary_school_name = str_replace('学校', '', $primary->name);
                                    }
                                }
                                if (isset($mansion->secondary_school_school)) {
                                    $secondary = MstSchool::getSchoolByCode($mansion->secondary_school_school);
                                    if (isset($secondary->name)) {
                                        $row->secondary_school_name = str_replace('学校', '', $secondary->name);
                                    }
                                }

                                // 築年月
                                $row->age_year = $mansion->age_year;
                                $row->age_month = $mansion->age_month;
                                $row->age = intval(date('Y')) - intval($mansion->age_year);
                            }
                        } else {
                            // それ以外
                            $row->property_name = $this->getPropertyName($row->property, $row->property_sub);
                            $vendor_info = Vendor::getDataListByArticleId($row->building_id);
                        }

                        $row['vendor_info'] = $vendor_info ?? [];
                    }
                }
            }
        }

        $data['article_list'] = $article_list;
        $data['count_article_list'] = $j;
        $listId = $article_list->pluck('building_id')->toArray();
        $data['artPrint'] = implode(',', $listId);

        $manner = MstManner::getData();
        array_unshift($manner, ['code' => '', 'name' => '']);
        $data['manner'] = $manner;
        $data['statuses'] = MstStatus::getData();

        $data['ad_conf'] = [
            ['code' => '', 'name' => ''],
            ['code' => 1, 'name' => 'TEL'],
            ['code' => 2, 'name' => 'FAX'],
        ];

        return view('business.pages.buyer.append', $data);
    }

    public function delete($id)
    {
        $buyer = Buyer::findOrFail($id);
        $buyer->articles()->delete();
        $buyer->delete();
        request()->session()->forget('buyer_active');
        return redirect()->route('buyer.index');
    }

    public function select(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            $request->session()->forget('buyer_active');
            $request->session()->flash('success', '「未選択」に設定しました');
            return back();
        }
        $buyer = Buyer::findOrFail($id);
        session(['buyer_active' => $buyer]);
        $request->session()->flash('success', '「'.$buyer->name.'」に設定しました');
        return back();
    }

    public function update(StoreRequest $request, $id)
    {
        $buyer = Buyer::findOrFail($id);
        $name = $request->get('name');
        $buyer->update(['name' => $name]);
        session(['buyer_active' => $buyer]);
        return back();
    }

    public function saveArticle(Request $request)
    {
        $ids = $request->get('ids');
        $ids = explode(',', $ids);
        $buyer = session('buyer_active');
        foreach ($ids as $article_id) {
            if (empty( $buyer->articles()->where('article_id', $article_id)->first())) {
                $buyer->articles()->create(['article_id'=> $article_id]);
            }
        }

        $buyerNew = Buyer::findOrFail(optional($buyer)->id);
        session(['buyer_active' => $buyerNew]);

        return count($buyerNew->articles);
    }

    public function deleteArticle(Request $request)
    {
        $ids = $request->get('ids');
        $ids = explode(',', $ids);
        $buyer = session('buyer_active');
        $buyer->articles()->whereIn('article_id', $ids)->delete();

        if ($request->ajax()) {
            if (!empty($ids)) {
                $buyerNew = Buyer::findOrFail(optional($buyer)->id);
                session(['buyer_active' => $buyerNew]);
                return $buyer->articles()->count();
            }
        }

        return redirect()->route('buyer.append', [optional($buyer)->id]);
    }

    public static function getPropertyName($property, $property_sub)
    {
        $res = '';
        if ($property > 3) {
            $res .= MstPropertyTypeSub::find($property_sub)->name ?? '';
        }

        $res .= MstPropertyType::find($property)->name ?? '';

        return $res;
    }

    public function print(Request $request)
    {
        $buyer = session('buyer_active');
        $user = auth()->user();
        $data['condition'] = [];
        $manner = MstManner::getData();
        array_unshift($manner, ['code' => '', 'name' => '']);
        $data['manner'] = $manner;
        $data['ad_conf'] = [
            ['code' => '', 'name' => ''],
            ['code' => 1, 'name' => 'TEL'],
            ['code' => 2, 'name' => 'FAX'],
        ];
        $data['statuses'] = MstStatus::getData();
        $floor_type_list = MstFloorType::getData();
        $floor_type = [];
        foreach ($floor_type_list as $row) {
            $floor_type[$row['code']] = $row['name'];
        }
        if (!empty($buyer)) {
            $onlyItems = !empty($request->get('only_items')) ? $request->get('only_items') : [];
            $article_list = $buyer->articles()->orderByRaw("FIELD(article_id, $onlyItems)")->get();
            foreach ($article_list as $key => $row) {
                $article_list[$key] = Article::getDataById($row->article->building_id);
            }
            foreach ($article_list as &$row) {
                $address = "";
                if (isset($row->address1)) {
                    $add = MstPrefecture::getData($row->address1);
                    if (!empty($add)) {
                        $address .= $add[0]["name"];
                    }
                }
                if (isset($row->address2)) {
                    $add = MstCity::getData($row->address1, $row->address2);
                    if (!empty($add)) {
                        $address .= $add[0]["name"];
                    }
                }
                if (isset($row->address3)) {
                    $add = MstTown::getData($row->address1, $row->address2, $row->address3);
                    if (!empty($add)) {
                        $address .= $add[0]["name"];
                    }
                }
                if (isset($row->address4)) {
                    $address .= $row->address4;
                }
                $row->address = $address;
                if (isset($row->floor_plan_type)) {
                    $row['floor_plan_text'] = $row->floor_plan . $floor_type[$row->floor_plan_type];
                }

                if (isset($row->primary_school_school)) {
                    $primary = MstSchool::getSchoolByCode($row->primary_school_school);
                    if (isset($primary->name)) {
                        $row->primary_school_name = str_replace('学校', '', $primary->name);
                    }
                }
                if (isset($row->secondary_school_school)) {
                    $secondary = MstSchool::getSchoolByCode($row->secondary_school_school);
                    if (isset($secondary->name)) {
                        $row->secondary_school_name = str_replace('学校', '', $secondary->name);
                    }
                }

                // 物件種別名、業者取得
                if (is_null($row->property)) {
                    // マンションの場合
                    $mansion = Article::getDataById($row->mansion_id);
                    if (is_object($mansion)) {
                        $row->property_name = $this->getPropertyName($mansion->property, $mansion->property_sub);
                        $row->age_year = $mansion->age_year;
                        $row->age_month = $mansion->age_month;
                        $this->mapTrafficMansion($row, $mansion);
                    }
                } else {
                    // それ以外
                    $row->property_name = $this->getPropertyName($row->property, $row->property_sub);
                }
            }
            $data['article_list'] = $article_list;
            return view('business.pages.buyer.print', $data);
        }
    }

    private function mapTrafficMansion($article, $mansion)
    {
        $article->main_traffic = $mansion->main_traffic;
        $article->main_traffic_line = $mansion->main_traffic_line;
        $article->main_traffic_station = $mansion->main_traffic_station;
        $article->main_traffic_time = $mansion->main_traffic_time;
        $article->main_traffic_bus = $mansion->main_traffic_bus;
        $article->main_traffic_bus_time = $mansion->main_traffic_bus_time;
        $article->main_traffic_bus_walk = $mansion->main_traffic_bus_walk;

        $article->sub_traffic1 = $mansion->sub_traffic1;
        $article->sub_traffic1_line = $mansion->sub_traffic1_line;
        $article->sub_traffic1_station = $mansion->sub_traffic1_station;
        $article->sub_traffic1_time = $mansion->sub_traffic1_time;
        $article->sub_traffic1_bus = $mansion->sub_traffic1_bus;
        $article->sub_traffic1_bus_time = $mansion->sub_traffic1_bus_time;
        $article->sub_traffic1_bus_walk = $mansion->sub_traffic1_bus_walk;

        $article->sub_traffic2 = $mansion->sub_traffic2;
        $article->sub_traffic2_line = $mansion->sub_traffic2_line;
        $article->sub_traffic2_station = $mansion->sub_traffic2_station;
        $article->sub_traffic2_time = $mansion->sub_traffic2_time;
        $article->sub_traffic2_bus = $mansion->sub_traffic2_bus;
        $article->sub_traffic2_bus_time = $mansion->sub_traffic2_bus_time;
        $article->sub_traffic2_bus_walk = $mansion->sub_traffic2_bus_walk;
    }
}
