<?php

namespace App\Http\Controllers\Admin;

use App\Models\City;
use App\Http\Requests\UserRequest;
use App\Models\Ope;
use App\Models\User;
use App\Models\Usertype;
use App\Utils;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Response;

class UserController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function list(Request $request)
    {
        $inputs = [
            'isMethodPost' => 0,
            'isExport' => $request->input('isExport', 0) * 1,
            'sort' => $request->input('sort', ''),
            'sort_type' => $request->input('sort_type', ''),
            'page' => $request->get('page', 1),
            'user_id' => $request->input('user_id', ''),
            'member_id' => $request->input('member_id', ''),
            'user_tag_serial' => $request->input('user_tag_serial', ''),
            'user_phonetic' => $request->input('user_phonetic', ''),
            'phone' => $request->input('phone', ''),
            'crime' => $request->input('crime', ''),
            'black_list' => $request->input('black_list', ''),
            'ward_residents' => $request->input('ward_residents', ''),
            'user_tag_serial_64' => $request->input('user_tag_serial_64', ''),
            'photo_filename1' => $request->file('photo_filename1'),
            'photo_filename2' => $request->file('photo_filename2'),
        ];
        $inputs['isMethodPost'] = $request->isMethod('post');
        $inputs['list'] = User::search($inputs);
        if ($inputs['list']->total() > 0 && $inputs['page'] > $inputs['list']->lastPage()) {
            return redirect()->route('users');
        }
        return view('admin.users.list', $inputs);
    }

    public function add(Request $request)
    {
        $inputs = [
            'user_id' => $request->input('user_id', ''),
            'member_id' => $request->input('member_id', ''),
            'user_pass' => $request->input('password', ''),
            'user_manual_regist_flag' => $request->input('user_manual_regist_flag', 0),
            'user_mailing_flag' => $request->input('user_mailing_flag', 0),
            'contract_number' => $request->input('contract_number', ''),
            'user_tag_serial' => $request->input('user_tag_serial', ''),
            'user_tag_serial_64' => $request->input('user_tag_serial_64', ''),
            'qr_code' => $request->input('qr_code', ''),
            'tag_qr_flag' => $request->input('tag_qr_flag', ''),
            'user_aid' => $request->input('user_aid', ''),
            'user_park_number' => $request->input('user_park_number', ''),
            'user_place_qrid' => $request->input('user_place_qrid', ''),
            'user_categoryid' => $request->input('user_categoryid', ''),
            'user_name' => $request->input('user_name', ''),
            'user_phonetic' => $request->input('user_phonetic', ''),
            'user_gender' => $request->input('user_gender', ''),
            'user_birthdate' => $request->input('user_birthdate', ''),
            'user_age' => $request->input('user_age', ''),
            'ward_residents' => $request->input('ward_residents', ''),
            'user_mobile' => $request->input('user_mobile', ''),
            'user_homephone' => $request->input('user_homephone', ''),
            'user_primemail' => $request->input('user_primemail', ''),
            'user_submail' => $request->input('user_submail', ''),
            'user_regident_zip' => $request->input('user_regident_zip', ''),
            'user_regident_pre' => $request->input('user_regident_pre', ''),
            'user_regident_city' => $request->input('user_regident_city', ''),
            'user_regident_add' => $request->input('user_regident_add', ''),
            'user_relate_zip' => $request->input('user_relate_zip', ''),
            'user_relate_pre' => $request->input('user_relate_pre', ''),
            'user_relate_city' => $request->input('user_relate_city', ''),
            'user_relate_add' => $request->input('user_relate_add', ''),
            'user_workplace' => $request->input('user_workplace', ''),
            'user_school' => $request->input('user_school', ''),
            'user_graduate' => $request->input('user_graduate', ''),
            'user_reduction' => $request->input('user_reduction', ''),
            'user_idcard' => $request->input('user_idcard', ''),
            'user_idcard_chk_flag' => $request->input('user_idcard_chk_flag', 0),
            'user_chk_day' => $request->input('user_chk_day', ''),
            'user_chk_opeid' => $request->input('user_chk_opeid', ''),
            'user_tag_issue' => $request->input('user_tag_issue', ''),
            'issue_permission' => $request->input('issue_permission', 0),
            'user_quit_flag' => $request->input('user_quit_flag', 0),
            'user_quitday' => $request->input('user_quitday', ''),
            'user_remarks' => $request->input('user_remarks', ''),
            'photo_filename1' => $request->file('photo_filename1'),
            'photo_filename2' => $request->file('photo_filename2'),
        ];
        $dataList = $this->getDataDropList();
        $inputs = array_merge($inputs, $dataList);

        if ($request->isMethod('POST')) {
            $type = false;
            $validation = new UserRequest();
            $rules = $validation->rules();
            $rules['user_id'] = $rules['user_id'] . '|unique:user';
            $rules['password'] = 'required|min:6|confirmed';
            if(!empty($inputs['user_age']) ){
                $rules['user_age'] = 'integer';
            }
            if(!empty($inputs['user_aid']) ){
                $rules['user_aid'] = 'integer';
            }
            $validator = Validator::make($request->all(), $rules, $validation->messages());
            if (!$validator->fails()) {
                if ($request->hasFile('photo_filename1') && $inputs['photo_filename1']->isValid()) {
                    $inputs['image1'] = Utils::uploadFile($inputs['photo_filename1']);
                } else {
                    $inputs['image1'] = '';
                }
                if ($request->hasFile('photo_filename2') && $inputs['photo_filename2']->isValid()) {
                    $inputs['image2'] = Utils::uploadFile($inputs['photo_filename2']);
                } else {
                    $inputs['image2'] = '';
                }
                \DB::transaction(function () use ($inputs, &$type) {
                    $new = new User();
                    $new->fill($inputs);
                    if ($inputs['image1'] && $inputs['image1'] != '') {
                        $new->photo_filename2 = $inputs['image1'];
                    }
                    if ($inputs['image2'] && $inputs['image2'] != '') {
                        $new->photo_filename2 = $inputs['image2'];
                    }
                    if ($new->save()) {
                        $new->user_pass = Utils::getHashPassword($inputs['user_pass'], $new->user_seq);
                        $new->save();
                    }

                    $type = true;
                });
                if ($type) {
                    $request->session()->flash('success', __('新しい成功を創造する。'));
                    return redirect()->route('users');
                } else {
                    $request->session()->flash('error', __('新しい作成に失敗しました'));
                }
            } else {
                $inputs['errorMsg'] = $this->__buildErrorMessasges($validator);
                $data['photo_filename1'] = '';
                $data['photo_filename2'] = '';
            }
        }

        return view('admin.users.add', $inputs);
    }

    public function edit(Request $request, $seq, $view = '')
    {
        $user = User::getUserBySeq($seq);
        if (empty($seq) || empty($user)) {
            abort('404');
        }
        $data = $user->getAttributes();
        $filename1 = $data['photo_filename1'];
        $filename2 = $data['photo_filename2'];
        $dataList = $this->getDataDropList();
        $data = array_merge($data, $dataList);

        if ($request->isMethod('POST')) {
            $type = false;
            $validation = new UserRequest();
            $inputs = $request->all();
            $rules = $validation->rules();
            if (!empty($inputs['password'])) {
                $rules['password'] = 'required|min:6|confirmed';
            }
            if(!empty($inputs['user_age']) ){
                $rules['user_age'] = 'integer';
            }
            if(!empty($inputs['user_aid']) ){
                $rules['user_aid'] = 'integer';
            }
            $validator = Validator::make($inputs, $rules, $validation->messages());
            $data = array_merge($data, $inputs);

            if (!$validator->fails()) {

                if ($request->hasFile('photo_filename1') && $data['photo_filename1']->isValid()) {
                    $data['image1'] = Utils::uploadFile($data['photo_filename1']);
                } else {
                    $data['image1'] = '';
                }
                if ($request->hasFile('photo_filename2') && $data['photo_filename2']->isValid()) {
                    $data['image2'] = Utils::uploadFile($data['photo_filename2']);
                } else {
                    $data['image2'] = '';
                }
                \DB::transaction(function () use ($data, &$type, $user, $inputs) {
                    $user->fill($data);
                    if (!empty($inputs['password'])) {
                        $user->user_pass = Utils::getHashPassword($data['password'], $user->user_seq);
                    }
                    if ($data['image1'] && $data['image1'] != '') {
                        $user->photo_filename1 = $data['image1'];
                    }
                    if ($data['image2'] && $data['image2'] != '') {
                        $user->photo_filename2 = $data['image2'];
                    }
                    $user->save();
                    $type = true;
                });
                if ($type) {
                    $request->session()->flash('success', __('更新に成功しました'));
                    return redirect()->route('users');
                } else {
                    $request->session()->flash('error', __('更新に失敗しました'));
                }
            } else {
                $data['errorMsg'] = $this->__buildErrorMessasges($validator);
                $data['photo_filename1'] = $filename1;
                $data['photo_filename2'] = $filename2;

            }
        }
        if ($view != '') {
            return view($view, $data);
        }
        return view('admin.users.edit', $data);
    }

    public function delete(Request $request)
    {
        $arr_seq = $request->get('seq');
        if ($arr_seq) {
            if (User::deleteUsersBySeq($arr_seq)) {
                return redirect()->route('users')->with('success', __("削除が完了しました。"));
            } else {
                return redirect()->route('users')->with('error', __('削除に失敗しました。'));
            }
        }
        return redirect()->route('users')->with('error', __('削除するユーザーを選択してください。'));
    }

    public function export(Request $request)
    {

        $headers = array(
            "Content-type" => "text/csv;charset=UTF-8",
            'Content-Encoding: UTF-8',
            "Content-Disposition" => "attachment; filename=file.csv",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        );
        $inputs = [
            'isMethodPost' => 0,
            'isExport' => 1,
            'sort' => $request->input('sort', ''),
            'sort_type' => $request->input('sort_type', ''),

        ];

        $dataExport = User::search($inputs);
        $columns = array(
            __('利用者連番'),// 0
            __('利用者ID'),// 1
            __('会員ID'),// 2
            __('パスワード'),// 3
            __('手動登録フラグ'),// 4
            __('手動登録フラグ'),
            __('郵送必要フラグ'),// 5
            __('郵送必要フラグ'),
            __('旧定期契約番号'),// 6
            __('タグシリアル'),// 7
            __('タグシリアル64進'),// 8
            __('QRコード'),// 9
            __('タグ／ＱＲフラグ'),// 10
            __('タグ／ＱＲフラグ'),
            __('AID'),// 11
            __('居場所通知用QRID'),// 12
            __('利用者分類ID'),// 13
            __('利用者分類'),
            __('利用者名'),// 14
            __('フリガナ'),// 15
            __('性別'),// 16
            __('生年月日'),// 17
            __('年齢'),// 18
            __('携帯電話番号'),// 19
            __('自宅電話番号'),// 20
            __('メールアドレス'),// 21
            __('予備メールアドレス'),// 22
            __('居住所:郵便番号'),// 23
            __('居住所:都道府県'),// 24
            __('居住所:市区群'),// 25
            __('居住所:住所'),// 26
            __('関連住所:郵便番号'),// 27
            __('関連住所:都道府県'),// 28
            __('関連住所:市区群'),// 29
            __('関連住所:住所'),// 30
            __('区民'),// 31
            __('勤務先名'),// 32
            __('学校'),// 33
            __('卒業予定'),// 34
            __('本人確認書類'),// 35
            __('本人確認チェック済'),// 36
            __('本人確認チェック済'),
            __('本人確認日時'),// 37
            __('本人確認オペレータID'),// 38
            __('タグ発行数'),// 39
            __('タグ発行許可'),// 40
            __('退会フラグ'),// 41
            __('退会フラグ'),
            __('退会日'),// 42
            __('備考'),// 43
        );
        $filename = "利用者マスタ.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $items) {
            fputcsv($file, array(
                $items->user_seq, // 0
                $items->user_id, // 1
                $items->member_id, // 2
                '',//TODO パスワード not found in database specs
                $items->user_manual_regist_flag, // 4
                $items->user_manual_regist_flag ? __("はい") : __("いいえ"),
                $items->user_mailing_flag, // 6
                $items->user_mailing_flag ? __("はい") : __("いいえ"),
                $items->contract_number, // 8
                $items->user_tag_serial, // 9
                $items->user_tag_serial_64, // 10
                $items->qr_code, // 11
                $items->tag_qr_flag, // 12
                $items->tag_qr_flag ? __('ＱＲコード') : __('タグ'),
                $items->user_aid, // 14
                $items->user_place_qrid, // 15
                $items->user_categoryid, // 16
                $items->getUserType()->print_name,
                $items->user_name, // 18
                $items->user_phonetic, // 19
                $items->user_gender, // 20
                $items->user_birthdate, // 21
                $items->user_age, // 22
                $items->user_mobile, // 23
                $items->user_homephone, // 24
                $items->user_primemail, // 25
                $items->user_submail, // 26
                $items->user_regident_zip, // 27
                $items->user_regident_pre, // 28
                $items->user_regident_city, // 29
                $items->user_regident_add, // 30
                $items->user_relate_zip, // 31
                $items->user_relate_pre, // 32
                $items->user_relate_city, // 33
                $items->user_relate_add, // 34
                $items->ward_residents, // 35
                $items->user_workplace, // 36
                $items->user_school, // 37
                $items->user_graduate, // 38
                $items->user_idcard, // 39
                $items->user_idcard_chk_flag, // 40
                \App\Models\User::USER_ID_CARD_CHK_FLG[$items->user_idcard_chk_flag],
                $items->user_chk_day, // 42
                $items->user_chk_opeid, // 43
                $items->user_tag_issue, // 44
                $items->issue_permission, // 45
                $items->user_quit_flag, // 46
                $items->user_quit_flag ? __("はい") : __("いいえ"),
                $items->user_quitday, // 48
                $items->user_remarks, // 49
            ));
        }
        fclose($file);
        return Response::download($filename, $filename, $headers);
    }

    public function import(Request $request)
    {
        $file = $request->file('file');
        if (!empty($file)) {
            $data = Utils::csvToArray($file);
            $type = 1;
            $msg = '';
            $record = 0;
            DB::beginTransaction();
            try {
                User::query()->delete();
                $col = 50;
                foreach ($data as $key => $items) {
                    $record = $key + 2;
                    if (count($items) == $col) {
                        $row = new User();
                        $row->user_seq = $items[0];
                        $row->user_id = $items[1];
                        $row->member_id = $items[2];
                        //TODO パスワード not found in database specs_$items[3]
                        $row->user_manual_regist_flag = $items[4];
                        $row->user_mailing_flag = $items[6];
                        $row->contract_number = $items[8];
                        $row->user_tag_serial = $items[9];
                        $row->user_tag_serial_64 = $items[10];
                        $row->qr_code = $items[11];
                        $row->tag_qr_flag = $items[12];
                        $row->user_aid = $items[14];
                        $row->user_place_qrid = $items[15];
                        $row->user_categoryid = $items[16];
                        $row->user_name = $items[18];
                        $row->user_phonetic = $items[19];
                        $row->user_gender = $items[20];
                        $row->user_birthdate = $items[21];
                        $row->user_age = !empty($items[22]) ? $items[22] : null;
                        $row->user_mobile = $items[23];
                        $row->user_homephone = $items[24];
                        $row->user_primemail = $items[25];
                        $row->user_submail = $items[26];
                        $row->user_regident_zip = $items[27];
                        $row->user_regident_pre = $items[28];
                        $row->user_regident_city = $items[29];
                        $row->user_regident_add = $items[30];
                        $row->user_relate_zip = $items[31];
                        $row->user_relate_pre = $items[32];
                        $row->user_relate_city = $items[33];
                        $row->user_relate_add = $items[34];
                        $row->ward_residents = $items[35];
                        $row->user_workplace = $items[36];
                        $row->user_school = $items[37];
                        $row->user_graduate = $items[38];
                        $row->user_idcard = $items[39];
                        $row->user_idcard_chk_flag = $items[40];
                        $row->user_chk_day = $items[42];
                        $row->user_chk_opeid = $items[43];
                        $row->user_tag_issue = $items[44];
                        $row->issue_permission = $items[45];
                        $row->user_quit_flag = $items[46];
                        $row->user_quitday = $items[48];
                        $row->user_remarks = $items[49];
                        if (!$row->save()) {
                            $type = 0;
                            $msg = '行:record型が一致しません。';
                            break;
                        }
                    } else {
                        $type = 0;
                        $msg = '行:record列数が一致しません。';
                        break;
                    }
                }
            } catch (\Exception $e) {
                $msg = '行:record型が一致しません。';
                $type = 0;
            }
            if ($type) {
                DB::commit();
                return redirect()->route('users')->with('success', __('輸入成功'));
            } else {
                DB::rollBack();
                return redirect()->route('users')->with('error', __($msg, ['record' => $record]));
            }
        } else {
            return redirect()->route('users')->with('error', __('あなたはcsvファイルを選択していません。'));
        }
    }


    public function info(Request $request, $seq)
    {
        return $this->edit($request, $seq, 'admin.users.info');
    }

    public function getDataDropList()
    {
        $data['cities'] = City::getList();
        $data['listUserType'] = Usertype::getList();
        $data['listOpe'] = Ope::getList();
        return $data;
    }

    /**
     * バリデーションエラーメッセージを構築
     */
    private function __buildErrorMessasges($validator)
    {
        $messages = [];
        foreach ($validator->errors()->all() as $message) {
            $messages[] = $message;
        }
        return implode('<br>', $messages);
    }

}
