<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\RegularContractRequest;
use App\Models\Park;
use App\Models\RegularContract;
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 RegularContractController extends Controller
{
    public function list(Request $request)
    {
       

        $inputs = [
            'isExport' => 0,
            'sort' => $request->input('sort', ''),
            'sort_type' => $request->input('sort_type', ''),
            'page' => $request->get('page', 1),
        ];
        $inputs['list'] = RegularContract::search($inputs);
      //dd($inputs['list']->items());
        
//        dd($inputs);
        if ($inputs['list']->total() > 0 && $inputs['page'] > $inputs['list']->lastPage()) {
            return redirect()->route('regular_contracts');
        }
        return view('admin.regular_contracts.list', $inputs);
    }

    public function add(Request $request)
    {
        $inputs = [
            'contract_qr_id' => $request->input('contract_qr_id'), // 定期契約QRID
            'user_id' => $request->input('user_id'), // 利用者ID
            'user_categoryid' => $request->input('user_categoryid'), // 利用者分類ID
            'reserve_id' => $request->input('reserve_id'), // 定期予約ID
            'park_id' => $request->input('park_id'), // 駐輪場ID
            'price_parkplaceid' => $request->input('price_parkplaceid'), // 駐輪場所ID
            'user_securitynum' => $request->input('user_securitynum'), // 防犯登録番号
            'reserve_date' => $request->input('reserve_date'), // 予約日時
            'contract_reserve' => $request->input('contract_reserve'), // 予約移行フラグ
            'contract_created_at' => $request->input('contract_created_at'), // 契約日時
            'contract_updated_at' => $request->input('contract_updated_at'), // 更新可能日
            'contract_cancelday' => $request->input('contract_cancelday'), // 解約日時
            'contract_reduction' => $request->input('contract_reduction'), // 減免措置
            'contract_periods' => $request->input('contract_periods'), // 有効期間S
            'contract_periode' => $request->input('contract_periode'), // 有効期間E
            'contract_taxid' => $request->input('contract_taxid'), // 消費税ID
            'billing_amount' => $request->input('billing_amount'), // 請求金額
            'contract_payment_day' => $request->input('contract_payment_day'), // 授受日時
            'contract_money' => $request->input('contract_money'), // 授受金額
            'refunds' => $request->input('refunds'), // 解約時返戻金
            'refunds_comment' => $request->input('refunds_comment'), // 返戻金付随情報
            'repayment_at' => $request->input('repayment_at'), // 返金日
            'contact_guid' => $request->input('contact_guid'), // 決済コード
            'contact_shop_code' => $request->input('contact_shop_code'), // 店舗コード
            'contract_cvs_class' => $request->input('contract_cvs_class'), // 授受種別
            'contract_flag' => $request->input('contract_flag'), // 授受フラグ
            'settlement_transaction_id' => $request->input('settlement_transaction_id'), // 決済トランザクションID
            'contract_seal_issue' => $request->input('contract_seal_issue'), // シール発行数
            'seal_reissue_request' => $request->input('seal_reissue_request'), // シール再発行リクエスト
            'contract_permission' => $request->input('contract_permission'), // シール発行許可
            'contract_cancel_flag' => $request->input('contract_cancel_flag'), // 解約フラグ
            'tag_qr_flag' => $request->input('tag_qr_flag'), // タグ／ＱＲフラグ
            'tag_change_flag' => $request->input('tag_change_flag'), // オペレータータグ変更フラグ
            'park_position' => $request->input('park_position'), // 駐輪位置番号
            'ope_id' => $request->input('ope_id'), // オペレータID
            'contract_manual' => $request->input('contract_manual'), // 手動通知
            'contract_notice' => $request->input('contract_notice'), // 通知方法
            'contract_payment_number' => $request->input('contract_payment_number'), // 受付番号
            'created_at' => $request->input('created_at'),
            'updated_at' => $request->input('updated_at'),
        ];
        $dataList = $this->getDataDropList();
        $inputs = array_merge($inputs, $dataList);
        if ($request->isMethod('POST')) {
            $type = false;
            $validation = new RegularContractRequest();
            $rules = $validation->rules();
            if(!empty($inputs['billing_amount']) ){
                $rules['billing_amount'] = 'numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['contract_money']) ){
                $rules['contract_money'] = 'numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['user_aid']) ){
                $rules['refunds'] ='numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['settlement_transaction_id']) ){
                $rules['settlement_transaction_id'] = 'integer';
            }
            if(!empty($inputs['contract_seal_issue']) ){
                $rules['contract_seal_issue'] = 'integer';
            }
            if(!empty($inputs['ope_id']) ){
                $rules['ope_id'] = 'integer';
            }
            $validator = Validator::make($request->all(), $rules, $validation->messages());
            if (!$validator->fails()) {
                \DB::transaction(function () use ($inputs, &$type) {
                    $new = new RegularContract();
                    $new->fill($inputs);
                    if ($new->save()) {
                        $type = true;
                    }

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

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

    public function edit(Request $request, $contract_id, $view = '')
    {
        $regular_contract = RegularContract::getByPk($contract_id);
        if (empty($contract_id) || empty($regular_contract)) {
            abort('404');
        }
        $data = $regular_contract->getAttributes();
        $dataList = $this->getDataDropList();
        $data = array_merge($data, $dataList);
        if ($request->isMethod('POST')) {
            $type = false;
            $inputs = $request->all();
            $validation = new RegularContractRequest();
            $rules = $validation->rules();
            if(!empty($inputs['billing_amount']) ){
                $rules['billing_amount'] = 'numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['contract_money']) ){
                $rules['contract_money'] = 'numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['user_aid']) ){
                $rules['refunds'] ='numeric|between:0,999999999999.99';
            }
            if(!empty($inputs['settlement_transaction_id']) ){
                $rules['settlement_transaction_id'] = 'integer';
            }
            if(!empty($inputs['contract_seal_issue']) ){
                $rules['contract_seal_issue'] = 'integer';
            }
            if(!empty($inputs['ope_id']) ){
                $rules['ope_id'] = 'integer';
            }
            $validator = Validator::make($inputs, $rules, $validation->messages());
            $data = array_merge($data, $inputs);
            if (!$validator->fails()) {
                \DB::transaction(function () use ($data, &$type, $regular_contract) {
                    $regular_contract->fill($data);
                    $regular_contract->save();
                    $type = true;
                });
                if ($type) {
                    $request->session()->flash('success', __('更新に成功しました'));
                    return redirect()->route('regular_contracts');
                } else {
                    $request->session()->flash('error', __('更新に失敗しました'));
                }
            } else {
                $data['errorMsg'] = $this->__buildErrorMessasges($validator);
            }
        }
        if ($view != '') {
            return view($view, $data);
        }
        return view('admin.regular_contracts.edit', $data);
    }

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

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

    public function getDataDropList()
    {
        $data['users'] = User::getList();
        $data['listUserType'] = Usertype::getList();
        $data['park'] = Park::getList();
        return $data;
    }


    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 = RegularContract::search($inputs);
        $columns = array(
            __('定期契約ID'),
            __('定期契約QRID'),// 1
            __('利用者ID'),// 2
            __('利用者分類ID'),// 3
            __('定期予約ID'),// 4
            __('駐輪場ID'),// 5
            __('駐輪場所ID'),// 6
            __('防犯登録番号'),// 7
            __('予約日時'),// 8
            __('予約移行フラグ'),// 9
            __('契約日時'),// 10
            __('更新可能日'),// 11
            __('解約日時'),// 12
            __('減免措置'),// 13
            __('有効期間S'),// 14
            __('有効期間E'),// 15
            __('消費税ID'),// 16
            __('請求金額'),// 17
            __('授受日時'),// 18
            __('授受金額'),// 19
            __('解約時返戻金'),// 20
            __('返戻金付随情報'),// 21
            __('返金日'),// 22
            __('決済コード'),// 23
            __('店舗コード'),// 24
            __('授受種別'),// 25
            __('授受フラグ'),// 26
            __('決済トランザクションID'),// 27
            __('シール発行数'),// 28
            __('シール再発行リクエスト'),// 29
            __('シール発行許可'),// 30
            __('解約フラグ'),// 31
            __('タグ／ＱＲフラグ'),// 32
            __('オペレータータグ変更フラグ'),// 33
            __('駐輪位置番号'),// 34
            __('オペレータID'),// 35
            __('手動通知'),// 36
            __('通知方法'),// 37
            __('受付番号'),// 38
        );
        $filename = "定期契約マスタ.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $items) {
            fputcsv($file, array(
                    $items->contract_id, // 0
                    $items->contract_qr_id, // 1
                    $items->user_id, // 2
                    $items->user_categoryid, // 3
                    $items->reserve_id, // 4
                    $items->park_id, // 5
                    $items->price_parkplaceid, // 6
                    $items->user_securitynum, // 7
                    $items->reserve_date, // 8
                    $items->contract_reserve, // 9
                    $items->contract_created_at, // 10
                    $items->contract_updated_at, // 11
                    $items->contract_cancelday, // 12
                    $items->contract_reduction, // 13
                    $items->contract_periods, // 14
                    $items->contract_periode, // 15
                    $items->contract_taxid, // 16
                    $items->billing_amount, // 17
                    $items->contract_payment_day, // 18
                    $items->contract_money, // 19
                    $items->refunds, // 20
                    $items->refunds_comment, // 21
                    $items->repayment_at, // 22
                    $items->contact_guid, // 23
                    $items->contact_shop_code, // 24
                    $items->contract_cvs_class, // 25
                    $items->contract_flag, // 26
                    $items->settlement_transaction_id, // 27
                    $items->contract_seal_issue, // 28
                    $items->seal_reissue_request, // 29
                    $items->contract_permission, // 30
                    $items->contract_cancel_flag, // 31
                    $items->tag_qr_flag, // 32
                    $items->tag_change_flag, // 33
                    $items->park_position, // 34
                    $items->ope_id, // 35
                    $items->contract_manual, // 36
                    $items->contract_notice, // 37
                    $items->contract_payment_number, // 38
                )
            );
        }
        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 {
                RegularContract::query()->delete();
                $col = 39;
                foreach ($data as $key => $items) {
                    $record = $key + 2;
                    if (count($items) == $col) {
                        $row = new RegularContract();
                        $row->contract_id = $items[0];
                        $row->contract_qr_id = $items[1];
                        $row->user_id = $items[2];
                        $row->user_categoryid = $items[3];
                        $row->reserve_id = $items[4];
                        $row->park_id = $items[5];
                        $row->price_parkplaceid = $items[6];
                        $row->user_securitynum = $items[7];
                        $row->reserve_date = $items[8];
                        $row->contract_reserve = $items[9];
                        $row->contract_created_at = $items[10];
                        $row->contract_updated_at = $items[11];
                        $row->contract_cancelday = $items[12];
                        $row->contract_reduction = $items[13];
                        $row->contract_periods = $items[14];
                        $row->contract_periode = $items[15];
                        $row->contract_taxid = $items[16];
                        $row->billing_amount = $items[17];
                        $row->contract_payment_day = $items[18];
                        $row->contract_money = $items[19];
                        $row->refunds = $items[20];
                        $row->refunds_comment = $items[21];
                        $row->repayment_at = $items[22];
                        $row->contact_guid = $items[23];
                        $row->contact_shop_code = $items[24];
                        $row->contract_cvs_class = $items[25];
                        $row->contract_flag = $items[26];
                        $row->settlement_transaction_id = $items[27];
                        $row->contract_seal_issue = $items[28];
                        $row->seal_reissue_request = $items[29];
                        $row->contract_permission = $items[30];
                        $row->contract_cancel_flag = $items[31];
                        $row->tag_qr_flag = $items[32];
                        $row->tag_change_flag = $items[33];
                        $row->park_position = $items[34];
                        $row->ope_id = $items[35];
                        $row->contract_manual = $items[36];
                        $row->contract_notice = $items[37];
                        $row->contract_payment_number = $items[38];
                        if (!$row->save()) {
                            $type = 0;
                            $msg = '行:record型が一致しません。';
                            break;
                        }
                    } else {
                        $type = 0;
                        $msg = '行:record列数が一致しません。';
                        break;
                    }
                }
            } catch (\Exception $e) {
                dd($e);
                $msg = '行:record型が一致しません。';
                $type = 0;
            }
            if ($type) {
                DB::commit();
                return redirect()->route('regular_contracts')->with('success', __('輸入成功'));
            } else {
                DB::rollBack();
                return redirect()->route('regular_contracts')->with('error', __($msg, ['record' => $record]));
            }
        } else {
            return redirect()->route('regular_contracts')->with('error', __('あなたはcsvファイルを選択していません。'));
        }
    }
}