<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Device;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DeviceController extends Controller
{
    /**
     * 一覧: /device
     */
   
    public function list(Request $request)
    {
        $perPage = \App\Utils::item_per_page ?? 20;

        $list = Device::with('park')
            ->orderBy('device_id', 'desc')
            ->paginate($perPage);

        return view('admin.devices.list', [
            'list'      => $list,
            'sort'      => 'device_id',
            'sort_type' => 'desc',
        ]);
    }


    /**
     * 新規追加: /device/add
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $v = Validator::make($request->all(), $this->rules());
            if ($v->fails()) return back()->withErrors($v)->withInput();

            DB::transaction(function () use ($request) {
                Device::create($request->only([
                    'park_id','device_type','device_subject','device_identifier',
                    'device_work','device_workstart','device_replace','device_remarks','operator_id',
                ]));
            });

            return redirect()->route('devices')->with('success', 'デバイスを登録しました。');
        }

        return view('admin.devices.add', [
            'device' => new Device(),
            'isInfo' => false,
            'isEdit' => false,
        ]);
    }


    /**
     * 編集: /device/edit/{id}
     */
    public function edit(Request $request, int $id)
    {
        $device = Device::findOrFail($id);

        if ($request->isMethod('post')) {
            $v = Validator::make($request->all(), $this->rules($id));
            if ($v->fails()) return back()->withErrors($v)->withInput();

            DB::transaction(function () use ($request, $device) {
                $device->update($request->only([
                    'park_id','device_type','device_subject','device_identifier',
                    'device_work','device_workstart','device_replace','device_remarks','operator_id',
                ]));
            });

            return redirect()->route('devices')->with('success', 'デバイスを更新しました。');
        }

        return view('admin.devices.edit', [
            'device' => $device,
            'isInfo' => false,
            'isEdit' => true,
        ]);
    }

    /**
     * 詳細: /device/info/{id}
     */
    public function info(int $id)
    {
        $device = Device::with('park')->findOrFail($id);

        return view('admin.devices.info', [
            'device' => $device,
            'isInfo' => true,
            'isEdit' => false,
        ]);
    }

    /**
     * 削除: /device/delete
     */
    public function delete(Request $request)
    {
        $ids = $request->input('ids');
        $id  = $request->input('id');

        if ($id) $ids = [$id];
        if (!is_array($ids) || empty($ids)) {
            return back()->with('error', '削除対象が指定されていません。');
        }

        DB::transaction(function () use ($ids) {
            Device::whereIn('device_id', $ids)->delete();
        });

        return redirect()->route('devices')->with('success', 'デバイスを削除しました。');
    }



    /** バリデーションルール */
    private function rules(?int $id = null): array
    {
        return [
            'park_id'           => ['nullable','integer'],
            'device_type'       => ['required','string','max:255'],
            'device_subject'    => ['required','string','max:255'],
            'device_identifier' => ['nullable','string','max:255'],
            'device_work'       => ['nullable','string','max:255'],
            'device_workstart'  => ['nullable','date'],
            'device_replace'    => ['nullable','date'],
            'device_remarks'    => ['nullable','string','max:255'],
            'operator_id'       => ['nullable','integer'],
        ];
    }


}
