<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Facility;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstFacilityType;

class FacilityController extends Controller
{
    /**
     * 施設検索条件設定画面の表示
     * @return string
     */
    public function show()
    {
        $data['active'] = 'search';
        // 都道府県マスターを取得
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $data['town'] = [];

        $data['facility_property'] = MstFacilityType::getData();

        return view('admin.pages.facility', $data);
    }

     /**
     * 施設検索条件設定画面の表示
     * @return string
     */
    public function listShow(Request $request)
    {
        $data['active'] = 'search';
        // 都道府県マスターを取得
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $data['town'] = [];

        $data['facility_property'] = MstFacilityType::getData();

        // 検索条件
        $data['search_name'] = $request->search_name;
        $data['search_property'] = $request->search_property;
        $data['search_address1'] = $request->search_address1;
        $data['search_address2'] = $request->search_address2;
        $data['search_address3'] = $request->search_address3;

        // 施設を取得
        $facility = Facility::getDataByCondition($request->all(), 20, 1);
        foreach($facility as &$row) {
            $property = MstFacilityType::getDataByCode($row->kind);
            if(!empty($property)) {
                $row['property'] = $property->name;
            } else {
                $row['property'] = '-';
            }

            $row->file_path = str_replace('public', '/storage', $row->file_path);
            
        }

        // 表示中のページの最初のアイテムのインデックス番号
        $first = $facility->firstItem();

        // 表示中のページの最後のアイテムのインデックス番号
        $last = $facility->lastItem();

        $data['facility_list'] = $facility;
        $data['first'] = $first;
        $data['last'] = $last;

        $data['search'] = $request->all();


        return view('admin.pages.facility', $data);
    }

    /**
     * 施設検索結果画面の表示
     * @return string
     */
    public function list(Request $request)
    {
        $data['active'] = 'list';

        $q = Facility::query();

        if(isset($request->id)) {
            $q->where('id', '=', $request->id);
        }
        if(isset($request->name)) {
            $q->where('name', 'LIKE', '%'.$request->name.'%');
            $q->orWhere('name_kana', 'LIKE', '%'.$request->name.'%');
        }
        if(isset($request->facility_charge)) {
            $q->where('facility_charge', 'LIKE', '%'.$request->name.'%');
            $q->orWhere('facility_charge_kana', 'LIKE', '%'.$request->name.'%');
        }
        if(isset($request->facility_tel)) {
            $q->where('facility_tel', '=', $request->facility_tel);
        }
        if(isset($request->facility_fax)) {
            $q->where('facility_fax', '=', $request->facility_fax);
        }
        $result = $q->get();

        $data['list'] = $result;
        return view('admin.pages.facility-list', $data);
    }

        /**
     * 施設登録画面の表示
     * @return string
     */
    public function registFacility(Request $request)
    {
        $data['active'] = 'regist';
        $data['kind'] = MstFacilityType::getData();
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData($data['pref'][0]['code']);
        $data['town'] = MstTown::getData($data['pref'][0]['code'], $data['city'][0]['code']);

        $all = $request->all();
        return view('admin.pages.facility-regist', $data);
    }

    /**
     * 施設検索結果画面の表示
     * @return string
     */
    public function regist(Request $request)
    {
        $user = Auth::user();
        $cols = ['name', 'kind', 'zip', 'address1', 'address2', 'address3', 'address4', 'lat', 'lng', 'memo'];
        // print_r($_FILES);
        // print_r($request->all());
        // exit;
        $images = $request->photo_images;

        $not_save = explode(',', $request->not_save_img_id);
        if(count($not_save) == 1 && $not_save[0] == "") {
            $not_save = [];
        }

        foreach($images as $key => $obj) {
            $save_data = [];
            foreach($cols as $col) {
                $col_name = $col.'_'.$key;
                $save_data[$col] = $request->{$col_name};
            }
            $save_data['company_id'] = $user->company_id;
            
            $facility = new Facility;
            $facility->fill($save_data)->save();

            if(!in_array($key, $not_save)) {
                $extension = $obj->getClientOriginalExtension();
                $image_url = $obj->storeAs('public/facility', 'facility_image_'.$facility->id.'.'. $extension);
                Facility::where('id', $facility->id)->update(['file_path' => $image_url]);
            }
        }
        
        $URL = url('');
        // $facility = new Facility;
        // $all = $request->all();
        // unset($all['_token']);
        // $result = $facility->fill($all)->save();

        return redirect("/admin/facility")->with('message', '施設を登録しました。');
    }

    /**
     * 施設検索結果画面の表示
     * @return string
     */
    public function editFacility(Request $request)
    {
        $data['active'] = 'regist';
        $id = $request->id;

        $facility = Facility::getDataById($id);

        $facility->file_path = str_replace('public', '/storage', $facility->file_path);
        $data['facility_info'] = $facility;

        $data['kind'] = MstFacilityType::getData();
        $data['pref'] = MstPrefecture::getData();
        $data['city'] = MstCity::getData($data['pref'][0]['code']);
        $data['town'] = MstTown::getData($data['pref'][0]['code'], $data['city'][0]['code']);

        $all = $request->all();
        return view('admin.pages.facility-edit', $data);
    }

    /**
     * 施設検索結果画面の表示
     * @return string
     */
    public function edit(Request $request)
    {
        $URL = url('');
        
        $all = $request->all();

        unset($all['_token']);
        unset($all['file_path']);
        unset($all['file_single_input']);
        unset($all['del_img']);
        
        $result = Facility::where('id', $request->id)->update($all);

        if(isset($request->file_single_input)) {
            $extension = $request->file_single_input->getClientOriginalExtension();
            $image_url = $request->file_single_input->storeAs('public/facility', 'facility_image_'.$request->id.'.'. $extension);
            Facility::where('id', $request->id)->update(['file_path' => $image_url]);
        } else if($request->del_img == 1) {
            Facility::where('id', $request->id)->update(['file_path' => null]);
        }

        if($result) {
            header('Location: '.$URL.'/admin/editFacility/'.$request->id);
            die();
        }
    }
}
