<?php

namespace App\Http\Controllers\Admin;

use App\Services\CompanyApiService;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\User;
use App\Models\MstStore;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\RelationStorePhoto;
use App\Models\TempImageStore;

use GuzzleHttp\Psr7;

class StoreController extends Controller
{
    /**
     * 店舗一覧画面の表示
     */
    public function showStore()
    {
        $data = [];
        $user = Auth::user();
        $info = MstStore::getDataByCompany($user->company_id);
        if ($user->isWebmaster() && $user->company_id !== 3) {
            return redirect()->route("store-regist");
        }

        foreach($info as &$row) {
            $photo = RelationStorePhoto::getListPhoto($user->company_id, $row->code);
            if(isset($photo->file_path)) {
                $row->file_path = str_replace('public', '/storage', $photo->file_path);
            }
        }

        $del_flag = false;
        if($user->role < 2) {
            $del_flag = true;
        }

        $data['del'] = $del_flag;
        $data['active'] = "list";
        $data['store'] = $info;
        return view('admin.pages.hp-store', $data);
    }

    /**
     * 店舗新規登録画面の表示
     */
    public function registStoreForm()
    {
        $data = [];
        $user = Auth::user();

        $data['active'] = "regist";
        // 都道府県マスターを取得
        $data['pref'] = MstPrefecture::getData();
        $defaultPrefCode = array_get(array_first($data['pref']), 'code');
        $data['city'] = MstCity::getData($defaultPrefCode, null, $user->company_id);
        $data['town'] = [];


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

    /**
     * 店舗新規登録処理
     */
    public function registStore(Request $request)
    {
        $user = Auth::user();
        $max = MstStore::getMaxNo($user->company_id);
        if(empty($max)) {
            $max = 0;
        }

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

        // 店舗登録
        $store = new MstStore;
        $code = $max+1;
        $save = [];
        $save['code'] = $code;
        $save['company_id'] = $user->company_id;
        $save['name'] = $request->name;
        $save['name_kana'] = $request->name_kana;
        $save['zip'] = $request->zip;
        $save['address1'] = $request->address1;
        $save['address2'] = $request->address2;
        $save['address3'] = $request->address3;
        $save['address4'] = $request->address4;
        $save['freedial'] = $request->freedial;
        $save['tel'] = $request->tel;
        $save['fax'] = $request->fax;
        $save['email'] = $request->email;
        $save['business_hours'] = $request->business_hours;
        $save['holiday'] = $request->holiday;
        $save['parking'] = $request->parking;
        $save['comment'] = $request->comment;
        $save['obi'] = $request->obi;
        $save['disp'] = 1;
        $result = $store->fill($save)->save();

        // 写真
        $keys = array_keys($request->all());
        // 一時保存されてる画像を本登録
        $matched_tmp = preg_grep('/tmp_store_photo_id_[0-9]/', $keys);
        $list_photo = [];
        foreach($matched_tmp as $key) {
            preg_match('/tmp_store_photo_id_(.*)/', $key, $match);
            $num = $match[1];
            $tmp_img_id = $request->{$key};
            $photo_data = [
                'company_id' => $user->company_id,
                'store_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;
            }
            $photo_data1 = $photo_data;
            $res = RelationStorePhoto::create($photo_data);


            $tmp_img = TempImageStore::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', 'store', str_replace('tmp', 'store', $old_path))));
            $new_path = str_replace('/store/', '/company_'.$user->company_id.'/store/', $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,
            ];
            $photo_data2 = $photo_data;
            $list_photo[] = array_merge($photo_data1, $photo_data2);
            RelationStorePhoto::where('id', '=', $res->id)->update($photo_data);
            if($user->company_id == 1){
                $this->uploadRemoteMic($new_path);
            }
            // 一時ファイルの削除
            TempImageStore::where('id', $tmp_img_id)->delete();
        }

        $request->session()->flash('message_modal', '登録・保存しました');
        return redirect("/admin/editStore/{$code}")->with('message', '店舗を登録しました。');
    }

    /**
     * 店舗新規登録画面の表示
     */
    public function editStoreForm(Request $request)
    {
        $data = [];
        $user = Auth::user();

        // 店舗情報の取得
        $store = MstStore::getDataByCode($user->company_id, $request->id);
        if($store->last_user_edit){
            $user_edit = User::getDataStaffById($store->last_user_edit);
            if(!empty($user_edit)){
                $store->last_user_name = $user_edit[0]['name'];
            }
        }
        $photos = RelationStorePhoto::getData($request->id);

        foreach($photos as $photo) {
            $photo->file_path = str_replace('public', '/storage', $photo->file_path);
        }
        // $store->file_path = str_replace('public', '/storage', $store->file_path);

        $data['active'] = "regist";
        $data['store'] = $store;
        $data['photos'] = $photos;
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData($store['address1'], null, $user->company_id);
        $data['town'] = MstTown::getData($store['address1'], $store['address2']);

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

    /**
     * 店舗新規登録処理
     */
    public function editStore(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

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

        // 店舗登録
        $save = [];
        $save['name'] = $request->name;
        $save['name_kana'] = $request->name_kana;
        $save['zip'] = $request->zip;
        $save['address1'] = $request->address1;
        $save['address2'] = $request->address2;
        $save['address3'] = $request->address3;
        $save['address4'] = $request->address4;
        $save['freedial'] = $request->freedial;
        $save['tel'] = $request->tel;
        $save['fax'] = $request->fax;
        if($user->role == 1){
            $save['email'] = $request->email;
        }else{
            unset($save['email']);
        }
        $save['business_hours'] = $request->business_hours;
        $save['holiday'] = $request->holiday;
        $save['parking'] = $request->parking;
        $save['comment'] = $request->comment;
        $save['obi'] = $request->obi;
        $save['homes_org_name'] = $request->homes_org_name;
        $save['homes_org_checked'] = $request->homes_org_checked;

        if(!empty($request->suumo_linked)){
            $save['suumo_id'] = $request->suumo_id;
            $save['suumo_pw'] = $request->suumo_pw;
            $save['suumo_linked'] = $request->suumo_linked;
        }
        if(!empty($request->homes_linked)){
            $save['homes_id'] = $request->homes_id;
            $save['homes_pw'] = $request->homes_pw;
            $save['homes_linked'] = $request->homes_linked;
        }
        if(!empty($request->athome_linked)){
            $save['athome_id'] = $request->athome_id;
            $save['athome_pw'] = $request->athome_pw;
            $save['athome_linked'] = $request->athome_linked;
        }
        $save['last_user_edit'] =   $user->id;

        $result = MstStore::where('code', '=', $request->id)
            ->where("company_id", $user->company_id)
            ->update($save);

        $keys = array_keys($request->all());

        // すでに登録されている画像のアップデート
        $matched = preg_grep('/store_photo_id_[0-9]/', $keys);
        foreach($matched as $key) {
            preg_match('/store_photo_id_(.*)/', $key, $match);
            $num = $match[1];
            $photo_id = $request->{'store_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;
            }
            RelationStorePhoto::where('id', '=', $photo_id)->update($photo_data);
        }

        // 一時保存されてる画像を本登録
        $matched_tmp = preg_grep('/tmp_store_photo_id_[0-9]/', $keys);
        foreach($matched_tmp as $key) {
            preg_match('/tmp_store_photo_id_(.*)/', $key, $match);
            $num = $match[1];
            $tmp_img_id = $request->{$key};
            $photo_data = [
                'company_id' => $user->company_id,
                'store_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 = RelationStorePhoto::create($photo_data);


            $tmp_img = TempImageStore::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', 'store', str_replace('tmp', 'store', $old_path))));
            $new_path = str_replace('/store/', '/company_'.$user->company_id.'/store/', $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,
            ];
            RelationStorePhoto::where('id', '=', $res->id)->update($photo_data);
            if($user->company_id == 1){
                $this->uploadRemoteMic($new_path);
            }
            // 一時ファイルの削除
            TempImageStore::where('id', $tmp_img_id)->delete();
        }
        $request->session()->flash('message_modal', '登録・保存しました');

        $save['photo_data'] = RelationStorePhoto::where('store_id', '=', $request->id)->get();
        $apiService->editStore($request->id, $save);

        return redirect("/admin/editStore/{$request->id}")->with('message', '店舗を登録しました。');
    }
    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);
        }
    }
}
