<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ModelNumberRequest;
use App\Models\DeviceModelNumber;
use Illuminate\Support\Facades\DB;

class ModelNumberController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $deviceModelNumbers = DB::table('device_model_numbers AS m')->select('m.*', 't.tname')
            ->leftJoin('device_type AS t', 't.tid', '=', 'm.device_type_id')
            ->orderBy('m.device_type_id')->get()->toArray();
        return $this->jsonSuccessData($deviceModelNumbers);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ModelNumberRequest $request)
    {
        $data = $request->all();

        $model = new DeviceModelNumber();
        $model->model_number = $data['model_number'];
        $model->device_type_id = $data['device_type_id'];
        if($model->save()) {
            return $this->jsonSuccessData();
        }else{
            return $this->jsonErrorData(201, 'error:2002');
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ModelNumberRequest $request, $id)
    {
        $data = $request->all();
//        dd($data,$id);
        $model = DeviceModelNumber::where('id', $id)->update([
            'model_number' => $data['model_number'],
        ]);

        if($model) {
            return $this->jsonSuccessData();
        }else{
            return $this->jsonErrorData(201, 'error:2002');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(DeviceModelNumber::destroy($id)) {
            return $this->jsonSuccessData();
        }else{
            return $this->jsonErrorData(201, 'error:2002');
        }
    }
}
