<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\UserPost;
use App\Http\Requests\UserPasswordPost;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\MstStore;
use App\Models\MstCompany;
use App\Models\CustomItem;
use App\Models\CustomContent;
use App\Models\RelationCustomItem;

class UserController extends Controller
{
    private $userInfo;

    public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

    /**
     * イベント画面の表示
     * @return string
     */
    public function show()
    {
        $user = Auth::user();
        $data['user'] = $user;
        return view('admin.pages.user', $data);
    }

    public function listUser(Request $request)
    {
        $user = $this->checkRole($request);

        $data['user'] = $user;
        $data['type'] = $request->type;
        $data['staff'] = [];

        $store_list = MstStore::getDataAll($user->company_id);
        // スタッフを取得
        foreach($store_list as $row) {
            $tmp_list = User::getDataStaff($user->company_id, $row['code']);
            foreach($tmp_list as &$item) {
                $info = UserInfo::getDataById($item['id']);
                $item['store_name'] = isset($row['name'])? $row['name']: "-";
                $item['employee_number'] = isset($info['employee_number'])? $info['employee_number']: "";
                $item['department'] = isset($info->department)? $info->department: "-";
                $item['position'] = isset($info->position)? $info->position: "-";
                $item['disp'] = isset($info->disp)? $info->disp: "-";
                $item['file_path'] = str_replace('public', '/storage', $info['file_path']);
            }

            $data['staff'][] = $tmp_list;
        }

        return view('admin.pages.user-list', $data);
    }

    public function createUser(Request $request) {
        $user = $this->checkRole($request);
        
        if($request->type != 2 && $request->type != 3) {
            print("不正なアクセスです。");
            exit;
        }
        $data['user'] = $user;
        $data['type'] = $request->type;

        // カスタム項目を取得
        $customs = CustomItem::getData($user->company_id);
        $data['customs'] = $customs;

        // 店舗を取得
        $data['store'] = MstStore::getDataAll($user->company_id);
        return view('admin.pages.user-regist', $data);
    }

    public function create(UserPost $request) {
        $user = $this->checkRole($request);

        $all = $request->all();

        // 同一会社の最大社員番号を取得
        $max_id = UserInfo::where('company_id', '=', $user->company_id)->max('employee_number');
        $max_order = UserInfo::where('company_id', '=', $user->company_id)->max('order');

        $obj_user = new User;
        $user_data = [];
        $user_data['role'] = $request->role;
        $user_data['company_id'] = $user->company_id;
        $user_data['store_id'] = $request->store;
        $user_data['name'] = $request->last_name . $request->first_name;
        $user_data['email'] = $request->email;
        $user_data['password'] = Hash::make($request->password);

        // ユーザー情報の登録
        $res = $obj_user->fill($user_data)->save();

        $obj_detail = new UserInfo;
        $detail_data = [];
        $detail_data['id'] = $obj_user->id;
        $detail_data['company_id'] = $user->company_id;
        $detail_data['employee_number'] = $max_id+1;
        $detail_data['last_name'] = $request->last_name;
        $detail_data['first_name'] = $request->first_name;
        $detail_data['last_name_kana'] = $request->last_name_kana;
        $detail_data['first_name_kana'] = $request->first_name_kana;
        $detail_data['store'] = $request->store;
        $detail_data['department'] = $request->department;
        $detail_data['position'] = $request->position;
        $detail_data['birth_month'] = $request->birth_month;
        $detail_data['birth_day'] = $request->birth_day;
        $detail_data['blood_type'] = $request->blood;
        $detail_data['disp'] = 0;
        $detail_data['order'] = $max_order+1;

        $result = $obj_detail->fill($detail_data)->save();

        if(isset($request->file_single_input)) {
            $extension = $request->file_single_input->getClientOriginalExtension();
            $image_url = $request->file_single_input->storeAs('public/staff', 'staff_image_'.$obj_user->id.'.'. $extension);
            UserInfo::where('company_id', $user->company_id)->where('employee_number', $obj_detail->employee_number)->update(['file_path' => $image_url]);

        }

        // カスタム項目の登録
        for($no = 1; $no <= config('const.ITEM_NUM'); $no++) {
            if($request->{'custom'.$no}) {
                $obj_custom = new RelationCustomItem;
                $custom = [];
                $custom['company_id'] = $user->company_id;
                $custom['user_id'] = $obj_user->id;
                $custom['code'] = $no;
                $custom['memo'] = $request->{'custom'.$no};
                $custom['file_name'] = '';
                $res = $obj_custom->fill($custom)->save();
            }
        }

        if($result) {
            $URL = url('');
            header('Location: '.$URL.'/admin/staffEdit/'.$obj_detail->employee_number);
            die();
        }
    }


    public function editUser(Request $request) {
        $user = $this->checkRole($request);
        $data['user'] = $user;
        $data['type'] = $request->type;

        // 店舗を取得
        $data['store'] = MstStore::getDataAll($user->company_id);

        $user_info = UserInfo::getDataByNumber($request->id);
        $data['user_info'] = User::getDataStaffById($user_info->id);
        
        $user_info['file_path'] = str_replace('public', '/storage', $user_info ['file_path']);
        $data['user_detail'] = $user_info;

        // カスタム項目を取得
        $customs = CustomItem::getData($user->company_id);
        foreach($customs as &$row) {
            $custom_anser = RelationCustomItem::getItem($request->id, $row->code);
            $row->ans = $custom_anser['memo'];
        }
        $data['customs'] = $customs;

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

    public function edit(UserPost $request) {

        $URL = url('');
        $user = $this->checkRole($request);
        $data['user'] = $user;
        $data['type'] = $request->type;

        // 店舗を取得
        $data['store'] = MstStore::getDataAll($user->company_id);

        $detail_data = [];
        $detail_data['last_name'] = $request->last_name;
        $detail_data['first_name'] = $request->first_name;
        $detail_data['last_name_kana'] = $request->last_name_kana;
        $detail_data['first_name_kana'] = $request->first_name_kana;
        $detail_data['store'] = $request->store;
        $detail_data['department'] = $request->department;
        $detail_data['position'] = $request->position;
        $detail_data['birth_month'] = $request->birth_month;
        $detail_data['birth_day'] = $request->birth_day;
        $detail_data['blood_type'] = $request->blood;
        if(isset($request->del_photo)) {
            $user_info = UserInfo::getDataByNumber($request->id);
            Storage::delete($user_info->file_path);
            $detail_data['file_path'] = null;
        }
        $result = UserInfo::where('company_id', $user->company_id)->where('employee_number', $request->id)->update($detail_data);

        $user_info = UserInfo::getDataByNumber($request->id);

        // ユーザー詳細情報の更新
        $detail_data = [];
        $detail_data['store_id'] = $request->store;
        User::where('id', $user_info->id)->update($detail_data);

        

        if(isset($request->file_single_input)) {
            $extension = $request->file_single_input->getClientOriginalExtension();
            $image_url = $request->file_single_input->storeAs('public/staff', 'staff_image_'.$request->id.'.'. $extension);
            UserInfo::where('company_id', $user->company_id)->where('employee_number', $request->id)->update(['file_path' => $image_url]);

        }


        RelationCustomItem::where('company_id', '=', $user->company_id)->where('user_id', '=', $request->id)->delete();
        for($no = 1; $no <= config('const.ITEM_NUM'); $no++) {
            if($request->{'custom'.$no}) {
                $obj_custom = new RelationCustomItem;
                $custom = [];
                $custom['company_id'] = $user->company_id;
                $custom['user_id'] = $request->id;
                $custom['code'] = $no;
                $custom['memo'] = $request->{'custom'.$no};
                $custom['file_name'] = '';
                $res = $obj_custom->fill($custom)->save();
            }
        }

        $URL = url('');
            header('Location: '.$URL.'/admin/staffEdit/'.$request->id);
            die();
    }

    public function editUserMe(Request $request) {
        $user = $this->checkRole($request);
        $data['user'] = $user;
        $data['type'] = $request->type;

        // 店舗を取得
        $data['store'] = MstStore::getDataAll($user->company_id);

        $user_info = UserInfo::getDataByNumber($user->id);
        $data['user_info'] = User::getDataStaffById($user_info->id);
        
        $user_info['file_path'] = str_replace('public', '/storage', $user_info ['file_path']);
        $data['user_detail'] = $user_info;

        // カスタム項目を取得
        $customs = CustomItem::getData($user->company_id);
        foreach($customs as &$row) {
            $custom_anser = RelationCustomItem::getItem($request->id, $row->code);
            $row->ans = $custom_anser['memo'];
        }
        $data['customs'] = $customs;

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

    public function editMe(UserPost $request) {

        $URL = url('');
        $user = $this->checkRole($request);
        $data['user'] = $user;
        $data['type'] = $request->type;

        // 店舗を取得
        $data['store'] = MstStore::getDataAll($user->company_id);

        $detail_data = [];
        $detail_data['last_name'] = $request->last_name;
        $detail_data['first_name'] = $request->first_name;
        $detail_data['last_name_kana'] = $request->last_name_kana;
        $detail_data['first_name_kana'] = $request->first_name_kana;
        $detail_data['store'] = $request->store;
        $detail_data['department'] = $request->department;
        $detail_data['position'] = $request->position;
        $detail_data['birth_month'] = $request->birth_month;
        $detail_data['birth_day'] = $request->birth_day;
        $detail_data['blood_type'] = $request->blood;
        if(isset($request->del_photo)) {
            $user_info = UserInfo::getDataByNumber($user->id);
            Storage::delete($user_info->file_path);
            $detail_data['file_path'] = null;
        }
        $result = UserInfo::where('company_id', $user->company_id)->where('employee_number', $user->id)->update($detail_data);

        $user_info = UserInfo::getDataByNumber($user->id);

        // ユーザー詳細情報の更新
        $detail_data = [];
        $detail_data['store_id'] = $request->store;
        User::where('id', $user_info->id)->update($detail_data);

        

        if(isset($request->file_single_input)) {
            $extension = $request->file_single_input->getClientOriginalExtension();
            $image_url = $request->file_single_input->storeAs('public/staff', 'staff_image_'.$user->id.'.'. $extension);
            UserInfo::where('company_id', $user->company_id)->where('employee_number', $user->id)->update(['file_path' => $image_url]);

        }


        RelationCustomItem::where('company_id', '=', $user->company_id)->where('user_id', '=', $user->id)->delete();
        for($no = 1; $no <= config('const.ITEM_NUM'); $no++) {
            if($request->{'custom'.$no}) {
                $obj_custom = new RelationCustomItem;
                $custom = [];
                $custom['company_id'] = $user->company_id;
                $custom['user_id'] = $user->id;
                $custom['code'] = $no;
                $custom['memo'] = $request->{'custom'.$no};
                $custom['file_name'] = '';
                $res = $obj_custom->fill($custom)->save();
            }
        }

        $URL = url('');
            header('Location: '.$URL.'/admin/userInfo');
            die();
    }

    public function customProf(Request $request) {
        $user = $this->checkRole($request);
        $data['user'] = $user;
        $items = CustomItem::getData($user->company_id);
        $num = 1;
        foreach($items as $item) {
            $data['item'.$num] = $item->name;
            $num++;
        }

        $contents = CustomContent::getData($user->company_id);
        $num = 1;
        foreach($contents as $item) {
            $data['custom_type'.$num] = $item->type;
            $data['custom_name'.$num] = $item->name;
            $data['custom_contents'.$num] = $item->contents;
            $num++;
        }
        
        return view('admin.pages.user-custom-prof', $data);
    }

    public function registCustom(Request $request) {
        $user = $this->checkRole($request);

        // カスタム項目の登録
        $item = new CustomItem;
        $item::where('company_id', '=', $user->company_id)->delete();
        for($i = 1; $i < 6; $i++) {
            $data = [];
            $data['company_id'] = $user->company_id;
            $data['code'] = $i;
            $data['name'] = !empty($request->{'custom'.$i})?$request->{'custom'.$i}: null;
            $item = new CustomItem;
            $res = $item->fill($data)->save();
        }

        // 独自項目の登録
        $item = new CustomContent;
        $item::where('company_id', '=', $user->company_id)->delete();
        for($i = 1; $i < 4; $i++) {
            $data = [];
            $data['company_id'] = $user->company_id;
            $data['code'] = $i;
            $data['type'] = !empty($request->{'custom_type'.$i})?$request->{'custom_type'.$i}: null;
            $data['name'] = !empty($request->{'custom_name'.$i})?$request->{'custom_name'.$i}: null;
            $data['contents'] = !empty($request->{'custom_contents'.$i})?$request->{'custom_contents'.$i}: null;
            $item = new CustomContent;
            $res = $item->fill($data)->save();
        }

        if ($res) {
            return redirect('/admin/user')->with('message', '登録しました。');
        }
    }



    public function checkRole(Request $request) {
        $user = Auth::user($request);
        if($user->role > 1 || $request->type == 1 || $request->type > 3) {
            print("不正なアクセスです。");
            exit;
        }
        return $user;
    } 

    public function registPasswordForm(Request $request) {
        $user = $this->checkRole($request);

        return view('admin.pages.user-password');
    }

    public function registPassword(UserPasswordPost $request) {
        $user = Auth::user();

        // ユーザー詳細情報の更新
        $detail_data = [];
        $detail_data['password'] = Hash::make($request->password);
        $res = User::where('id', $user->id)->update($detail_data);

        if ($res) {
            return redirect('/admin/adminRegist')->with('message', '登録しました。');
        }
    }
    
}
