<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pplace;
use App\Models\Ope;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Response;

class PplaceController 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'] = Pplace::search($inputs);

        if ($inputs['list']->total() > 0 && $inputs['page'] > $inputs['list']->lastPage()) {
            return redirect()->route('pplace');
        }

        return view('admin.Pplace.list', $inputs);
    }

    public function add(Request $request)
    {
        $inputs = [
            'pplace_number' => $request->input('pplace_number'),
            'pplace_remarks' => $request->input('pplace_remarks'),
            'operator_id' => $request->input('operator_id'),
        ];
      
        $inputs['operators'] = Ope::getList(); // 

        if ($request->isMethod('POST')) {
            $validator = Validator::make($inputs, [
                'pplace_number' => 'required|string|max:255',
                'pplace_remarks' => 'nullable|string|max:255',
                'operator_id' => 'nullable|integer',
            ]);
             
            if (!$validator->fails()) {
                DB::transaction(function () use ($inputs) {
                    $pplace = new Pplace();
                    $pplace->fill($inputs);
                    $pplace->save();
                });
                return redirect()->route('pplace')->with('success', '登録成功');
            } else {
                $inputs['errorMsg'] = $this->__buildErrorMessasges($validator);
            }
        }

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

    public function edit(Request $request, $id, $view = '')
    {
        
        $record = Pplace::find($id);
       
        if (!$record) abort(404);

        $data = $record->toArray();
        $data['operators'] = Ope::getList();
       

        if ($request->isMethod('POST')) {
            $inputs = $request->all();
            $validator = Validator::make($inputs, [
                'pplace_number' => 'required|string|max:255',
                'pplace_remarks' => 'nullable|string|max:255',
                'operator_id' => 'nullable|integer',
            ]);

            $data = array_merge($data, $inputs);

            if (!$validator->fails()) {
                DB::transaction(function () use ($record, $inputs) {
                    $record->fill($inputs);
                    $record->save();
                });
                return redirect()->route('pplace')->with('success', '更新成功');
            } else {
                $data['errorMsg'] = $this->__buildErrorMessasges($validator);
            }
        }

        return view($view ?: 'admin.Pplace.edit', $data);
    }

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

    public function delete(Request $request)
    {
        $pk = $request->get('pk');
        if ($pk && Pplace::destroy($pk)) {
            return redirect()->route('pplace')->with('success', '削除成功');
        }
        return redirect()->route('pplace')->with('error', '削除失敗');
    }

    public function export()
    {
        $headers = [
            "Content-type" => "text/csv;charset=UTF-8",
            "Content-Disposition" => "attachment; filename=Pplace.csv",
        ];

        $data = Pplace::all();
        $columns = ['ID', '番号', '備考', 'オペレータID'];

        $filename = "Pplace.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);

        foreach ($data as $item) {
            fputcsv($file, [
                $item->pplace_id,
                $item->pplace_number,
                $item->pplace_remarks,
                $item->operator_id,
            ]);
        }

        fclose($file);
        return Response::download($filename, $filename, $headers);
    }

    public function import(Request $request)
    {
        $file = $request->file('file');
        if (!$file) {
            return redirect()->route('pplace')->with('error', 'CSVファイルを選択してください');
        }

        $data = \App\Utils::csvToArray($file);
        $record = 0;

        DB::beginTransaction();
        try {
            foreach ($data as $key => $row) {
                $record = $key + 2;
                if (count($row) < 3) throw new \Exception('列数が不正です');

                Pplace::create([
                    'pplace_number' => $row[0],
                    'pplace_remarks' => $row[1],
                    'operator_id' => $row[2],
                ]);
            }
            DB::commit();
            return redirect()->route('pplace')->with('success', 'インポート成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route('pplace')->with('error', "行 {$record} : " . $e->getMessage());
        }
    }

    private function __buildErrorMessasges($validator)
    {
        return implode("\n", $validator->errors()->all());
    }
}
