<?php

namespace App\Http\Controllers\Admin;

use App\Services\CompanyApiService;
use GuzzleHttp\Client;
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;

use GuzzleHttp\Psr7;

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

        $data['active'] = "list";

        $reform_list = Reform::getDataAll();
        $count = 0;

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

            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, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $max = Reform::getMaxNo();
        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};
           //dd($tmp_img_id);
           $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))));
            $new_path = str_replace('/reform/', '/company_'.$user->company_id.'/reform/', $new_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,
                'list'      => $photo_data['list']
            ];
            RelationReformPhoto::where('id', '=', $res->id)->update($photo_data);
            if($user->company_id == 1){
                $this->uploadRemoteMic($new_path);
            }
            // 一時ファイルの削除
           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/company_'.$user->company_id.'/sheet', 'reform_image_'.$reform->id.'_before.'. $extension);
            Reform::where('id', $reform->id)->update(['before_file_path' => $image_url]);
            if($user->company_id == 1){
                $this->uploadRemoteMic($image_url);
            }
        }

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

        $data_send = Reform::where('code', '=', $reform->code)->first();
        $data_send['photo_data'] = RelationReformPhoto::where('reform_id', '=', $reform->code)->get();
        $apiService->registerReform($data_send);

        $request->session()->flash('message', '登録・保存しました');

        return redirect("/admin/editReform/{$code}");
    }

    /**
     * リフォーム事例新規登録画面の表示
     */
    public function editReformForm(Request $request)
    {
        $data = [];
        $user = Auth::user();

        $category = [
            ['code' => 1, 'name' => 'マンション'],
            ['code' => 2, 'name' => '戸建'],
            ['code' => 0, 'name' => '未選択'],
        ];

        // リフォーム事例情報の取得
        $reform = Reform::getReformDataByCode($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);
        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, CompanyApiService $apiService)
    {
        $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))));
            $new_path = str_replace('/reform/', '/company_'.$user->company_id.'/reform/', $new_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);
            if($user->company_id == 1){
                $this->uploadRemoteMic($new_path);
            }
            // 一時ファイルの削除
            TempImageReform::where('id', $tmp_img_id)->delete();
        }

        if($request->del_before_flag == 1) {
            $tmp_reform = Reform::getReformDataByCode($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($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/company_'.$user->company_id.'/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($user->company_id == 1){
                $this->uploadRemoteMic($image_url);
            }
        }

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

        $request->session()->flash('message_modal', '登録・保存しました');

        $data_send = Reform::where('code', '=', $request->id)->first();
        $data_send['photo_data'] = RelationReformPhoto::where('reform_id', '=', $request->id)->get();
        $apiService->editReform($request->id, $data_send);
        return redirect("/admin/editReform/{$request->id}");
    }

    public function deleteReform($id, CompanyApiService $apiService)
    {
        $user = Auth::user();
        Reform::where('code', $id)->where('company_id', $user->company_id)->delete();
        RelationReformPhoto::where('reform_id', '=', $id)->delete();
        $apiService->delReform($id);
        return back();
    }
    public static function uploadRemoteMic($file_path)
    {
        $ar_folder = explode('/', $file_path);
        unset($ar_folder[count($ar_folder) - 1]);
        $folder = implode('/', $ar_folder);
        $folder = str_replace('public', 'storage', $folder);


        $url = env("URL_MIC_EXPORT", "");
        $path = storage_path("app".DIRECTORY_SEPARATOR.$file_path);

        try {
            $client = new Client(['verify' => false]);
            $r = $client->request('POST', $url, [
                'multipart' => [
                    [
                        'name'     => 'file_name',
                        'contents' => Psr7\Utils::tryFopen($path, 'r'),
                    ],
                    [
                        'name'     => 'folder',
                        'contents' => "/".$folder."/",
                    ],
                ]
            ]);

            $code = $r->getStatusCode();
            $body = $r->getBody();
            $remainingBytes = $body->getContents();
            //dd($remainingBytes);
        } catch (\Error $error) {
            var_dump($error);
        }
    }
}
