<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ReformPost;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\Reform;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\RelationReformPhoto;
use App\Models\TempImageReform;

class ReformController extends Controller
{
   /**
     * リフォーム事例一覧画面の表示
     */
    public function showReform()
    {   
        $category = ['未選択', 'マンション', '戸建'];
        $data = [];
        $user = Auth::user();
 
        $data['active'] = "list";

        $reform_list = Reform::getDataAll($user->company_id);
        $count = 0;

        foreach($reform_list as &$row) {
            $top_photo = RelationReformPhoto::getListImageByReformId($row->id);

            if(!is_null($top_photo)) {
                $row->disp_file = str_replace('public', '/storage', $top_photo->file_path);
            }
            

            $row->category_name = $category[$row->category];
            if($row->disp == 1) {
                $count++;
            }
        }

        $data['disp_count'] = $count;
        $data['reform'] = $reform_list;
        return view('admin.pages.hp-reform', $data);
    }

    /**
     * リフォーム事例新規登録画面の表示
     */
    public function registReformForm()
    {
        $data = [];
        $category = [
            ['code' => 1, 'name' => 'マンション'],
            ['code' => 2, 'name' => '戸建'],
            ['code' => 0, 'name' => '未選択'],
        ];
        $user = Auth::user();
        
        $data['active'] = "regist";
        // 都道府県マスターを取得
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $data['town'] = [];
        $data['category'] = $category;


        $data['today'] = date('Y/m/d');
        return view('admin.pages.hp-regist-reform', $data);
    }

    /**
     * リフォーム事例新規登録処理
     */
    public function registReform(Request $request)
    {
        $user = Auth::user();
        $max = Reform::getMaxNo($user->company_id);
        if(empty($max)) {
            $max = 0;
        }

        // 並び順の設定
        $keys = array_keys($request->all());
        $matched = preg_grep('/.*reform_photo_id_[0-9]/', $keys);
        $rank = [];
        $no = 1;
        foreach($matched as $row) {
            preg_match('/.*reform_photo_id_(.*)/', $row, $match);
            $rank[$match[1]] = $no; 
            $no++;
        }

        // リフォーム事例登録
        $reform = new Reform;
        $code = $max+1;
        $save = [];
        $save['code'] = $code;
        $save['company_id'] = $user->company_id;
        $save['regist_date'] = $request->regist_date;
        $save['category'] = $request->category;
        $save['title'] = $request->title;
        $save['area'] = $request->area;
        $save['from_year'] = $request->from_year;
        $save['from_month'] = $request->from_month;
        $save['cost'] = $request->cost;
        $save['target'] = $request->target;
        $save['plan'] = $request->plan;
        $save['point'] = $request->point;
        $save['disp'] = 1;
        $save['reform_num'] = $max+1;
        $result = $reform->fill($save)->save();

       // 写真
       $keys = array_keys($request->all());

       // 一時保存されてる画像を本登録
       $matched_tmp = preg_grep('/tmp_reform_photo_id_[0-9]/', $keys);
       foreach($matched_tmp as $key) {
           preg_match('/tmp_reform_photo_id_(.*)/', $key, $match);
           $num = $match[1];
           $tmp_img_id = $request->{$key};
           $photo_data = [
               'company_id' => $user->company_id,
               'reform_id' => $code,
               'property' => $request->{'tmp_photo_property_'.$num},
               'memo' => $request->{'tmp_photo_comment_'.$num},
           ];
           if('tmp_'.$tmp_img_id == $request->photo_list) {
               $photo_data['list'] = 1;
           } else {
               $photo_data['list'] = null;
           }

           $res = RelationReformPhoto::create($photo_data);

           
           $tmp_img = TempImageReform::where('id', $tmp_img_id)->first();
           $old_path = $tmp_img->file_path;
           $new_path = str_replace('xxx', $code, preg_replace('/[0-9]/', $res->id, str_replace('photo', 'reform', str_replace('tmp', 'reform', $old_path))));
           Storage::delete($new_path);
           Storage::move($old_path, $new_path);
           //public/tmp/photo_image_xxx_2.jpg
           $photo_data = [
               'file_path' => $new_path,
               'file_type' => $tmp_img->file_type,
           ];
           RelationReformPhoto::where('id', '=', $res->id)->update($photo_data);
           
            // 一時ファイルの削除
           TempImageReform::where('id', $tmp_img_id)->delete();
       }

        // 間取り画像
       if(isset($request->file_single_input2)) {
        $extension = $request->file_single_input2->getClientOriginalExtension();
        $image_url = $request->file_single_input2->storeAs('public/sheet', 'reform_image_'.$reform->id.'_before.'. $extension);
        Reform::where('id', $reform->id)->update(['before_file_path' => $image_url]);
    }

        // 間取り画像
        if(isset($request->file_single_input3)) {
            $extension = $request->file_single_input3->getClientOriginalExtension();
            $image_url = $request->file_single_input3->storeAs('public/sheet', 'reform_image_'.$reform->id.'_after.'. $extension);
            Reform::where('id', $reform->id)->update(['after_file_path' => $image_url]);
        }

        return redirect("/admin/editReform/{$code}")->with('message', 'リフォームを登録しました。');
    }

    /**
     * リフォーム事例新規登録画面の表示
     */
    public function editReformForm(Request $request)
    {
        $data = [];
        $user = Auth::user();
        
        $category = [
            ['code' => 1, 'name' => 'マンション'],
            ['code' => 2, 'name' => '戸建'],
            ['code' => 0, 'name' => '未選択'],
        ];

        // リフォーム事例情報の取得
        $reform = Reform::getReformDataByCode($user->company_id, $request->id);
        // dump($reform);
        $reform->before_file_path = str_replace('public', '/storage', $reform->before_file_path);
        $reform->after_file_path = str_replace('public', '/storage', $reform->after_file_path);

        $photos = RelationReformPhoto::getDataByCode($reform->code, $user->company_id);
        foreach($photos as $photo) {
            $photo->file_path = str_replace('public', '/storage', $photo->file_path);
        }
        
        $data['active'] = "regist";
        $data['reform'] = $reform;
        $data['photos'] = $photos;
        $data['category'] = $category;
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData($reform['address1']);
        $data['town'] = MstTown::getData($reform['address1'], $reform['address2']);

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

    /**
     * リフォーム事例新規登録処理
     */
    public function editReform(ReformPost $request)
    {
        $user = Auth::user();

        // 並び順の設定
        $keys = array_keys($request->all());
        $matched = preg_grep('/.*reform_photo_id_[0-9]/', $keys);
        $rank = [];
        $no = 1;
        foreach($matched as $row) {
            preg_match('/.*reform_photo_id_(.*)/', $row, $match);
            $rank[$match[1]] = $no; 
            $no++;
        }

        // リフォーム事例登録
        $save = [];
        $save['company_id'] = $user->company_id;
        $save['regist_date'] = $request->regist_date;
        $save['category'] = $request->category;
        $save['title'] = $request->title;
        $save['area'] = $request->area;
        $save['from_year'] = $request->from_year;
        $save['from_month'] = $request->from_month;
        $save['cost'] = $request->cost;
        $save['target'] = $request->target;
        $save['plan'] = $request->plan;
        $save['point'] = $request->point;
        $save['disp'] = 1;

        $result = Reform::where('code', '=', $request->id)->update($save);

         // すでに登録されている画像のアップデート
         $matched = preg_grep('/reform_photo_id_[0-9]/', $keys);
         foreach($matched as $key) {
             preg_match('/reform_photo_id_(.*)/', $key, $match);
             $num = $match[1];
             $photo_id = $request->{'reform_photo_id_'.$num};
             $photo_data = [
                 'property' => $request->{'photo_property_'.$num},
                 'memo' => $request->{'photo_comment_'.$num},
                 'order' => $rank[$num],
             ];
             if($photo_id == $request->photo_list) {
                 $photo_data['list'] = 1;
             } else {
                 $photo_data['list'] = null;
             }
             RelationReformPhoto::where('id', '=', $photo_id)->update($photo_data);
         }
         
         // 一時保存されてる画像を本登録
         $matched_tmp = preg_grep('/tmp_reform_photo_id_[0-9]/', $keys);
         foreach($matched_tmp as $key) {
             preg_match('/tmp_reform_photo_id_(.*)/', $key, $match);
             $num = $match[1];
             $tmp_img_id = $request->{$key};
             $photo_data = [
                 'company_id' => $user->company_id,
                 'reform_id' => $request->id,
                 'property' => $request->{'tmp_photo_property_'.$num},
                 'memo' => $request->{'tmp_photo_comment_'.$num},
                 'order' => $rank[$num],
             ];
             if('tmp_'.$tmp_img_id == $request->photo_list) {
                 $photo_data['list'] = 1;
             } else {
                 $photo_data['list'] = null;
             }
 
             $res = RelationReformPhoto::create($photo_data);
 
             
             $tmp_img = TempImageReform::where('id', $tmp_img_id)->first();
             $old_path = $tmp_img->file_path;
             $new_path = str_replace('xxx', $request->id, preg_replace('/[0-9]/', $res->id, str_replace('photo', 'reform', str_replace('tmp', 'reform', $old_path))));
             Storage::delete($new_path);
             Storage::move($old_path, $new_path);
             //public/tmp/photo_image_xxx_2.jpg
             $photo_data = [
                 'file_path' => $new_path,
                 'file_type' => $tmp_img->file_type,
             ];
             RelationReformPhoto::where('id', '=', $res->id)->update($photo_data);
 
            // 一時ファイルの削除
            TempImageReform::where('id', $tmp_img_id)->delete();
        }

        if($request->del_before_flag == 1) {
            $tmp_reform = Reform::getReformDataByCode($user->company_id, $request->id);
            Storage::delete($tmp_reform->before_file_path);
            Reform::where('code', $request->id)->where('company_id', $user->company_id)->update(['before_file_path' => null]);
        }

        if($request->del_after_flag == 1) {
            $tmp_reform = Reform::getReformDataByCode($user->company_id, $request->id);
            Storage::delete($tmp_reform->after_file_path);
            Reform::where('code', $request->id)->where('company_id', $user->company_id)->update(['after_file_path' => null]);
        }

        // 間取り画像
        if(isset($request->file_single_input2)) {
            $extension = $request->file_single_input2->getClientOriginalExtension();
            $image_url = $request->file_single_input2->storeAs('public/sheet', 'reform_image_'.$request->id.'_before.'. $extension);
            Reform::where('code', $request->id)->where('company_id', $user->company_id)->update(['before_file_path' => $image_url]);
        }

        // 間取り画像
        if(isset($request->file_single_input3)) {
            $extension = $request->file_single_input3->getClientOriginalExtension();
            $image_url = $request->file_single_input3->storeAs('public/sheet', 'reform_image_'.$request->id.'_after.'. $extension);
            Reform::where('code', $request->id)->where('company_id', $user->company_id)->update(['after_file_path' => $image_url]);
        }

        return redirect("/admin/editReform/{$request->id}")->with('message', 'リフォームを登録しました。');
    }
}
