<?php

namespace App\Http\Controllers\Admin;

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;

class StoreController extends Controller
{
    /**
     * 店舗一覧画面の表示
     */
    public function showStore()
    {   
        $data = [];
        $user = Auth::user();
        $info = MstStore::getDataByCompany($user->company_id);

        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();
        $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $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['disp'] = 1;
        $result = $store->fill($save)->save();

        // 写真
        $keys = array_keys($request->all());
        // 一時保存されてる画像を本登録
        $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' => $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 = 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))));
            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);

            // 一時ファイルの削除
            TempImageStore::where('id', $tmp_img_id)->delete();
        }

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

    /**
     * 店舗新規登録画面の表示
     */
    public function editStoreForm(Request $request)
    {
        $data = [];
        $user = Auth::user();
        
        // 店舗情報の取得
        $store = MstStore::getDataByCode($user->company_id, $request->id);
        $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']);
        $data['town'] = MstTown::getData($store['address1'], $store['address2']);

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

    /**
     * 店舗新規登録処理
     */
    public function editStore(Request $request)
    {
        $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;
        $save['email'] = $request->email;
        $save['business_hours'] = $request->business_hours;
        $save['holiday'] = $request->holiday;
        $save['parking'] = $request->parking;
        $save['comment'] = $request->comment;

        $result = MstStore::where('code', '=', $request->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))));
            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);

            // 一時ファイルの削除
            TempImageStore::where('id', $tmp_img_id)->delete();
        }

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