<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\User;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $devices = Device::with('user')->get();
        return view('configuration.device.index',compact('devices'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $users = User::where('role_id',5)->get();
        return view('configuration.device.create',compact('users'));
    }




    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'mac_address'=>'required|unique:devices,mac_address',
            'user_id'=>'required'
        ]);
        Device::create([
            'mac_address'=>$request->mac_address,
            'user_id'=>$request->user_id
        ]);
        return redirect()->route('Device.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function show(Device $device)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $device = Device::whereId($id)->first();
        $users = User::where('role_id',5)->where('id','!=',$device->user_id)->get();
        return view('configuration.device.edit',compact('device','users'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request , $id)
    {
        $device = Device::whereId($id)->first();
        $request->validate([
            'mac_address'=>'required|unique:devices,mac_address,'.$id,
        ]);

        $device->mac_address = $request->mac_address;
        $device->user_id = $request->user_id;
        $device->update();
        
        return redirect()->route('Device.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $device = Device::whereId($id)->first();
        $device->delete();
        return redirect()->route('Device.index');


    }
}
