<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\MachineAndEquipment;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class MachineAndEquipmentsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:machine-and-equipment-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = MachineAndEquipment::select([
                    'machine_and_equipments.id',
                    'machine_and_equipments.device_model_name',
                    'machine_and_equipments.manufacturer_name',
                    'machine_and_equipments.mac_address',
                    'machine_and_equipments.location',
                    'machine_and_equipments.code',
                    'machine_and_equipments.port_number',
                    'machine_and_equipments.status',
                    'machine_and_equipments.ipv4_address',
                    'machine_and_equipments.ipv6_address',
                    'machine_and_equipments.part_no',
                    'machine_and_equipments.installation_date',
                ])
                ->orderBy('machine_and_equipments.device_model_name', 'ASC');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('machine_and_equipments.device_model_name', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.manufacturer_name', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.mac_address', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.location', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.code', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.port_number', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.part_no', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.ipv4_address', 'like', '%'.$search_query.'%')
                    ->orWhere('machine_and_equipments.ipv6_address', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('machine-and-equipments.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('machine-and-equipments.index', compact('data'));
        }
    }

    public function create()
    {
        return view('machine-and-equipments.create');
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'device_model_name' => 'required|unique:machine_and_equipments,device_model_name,NULL,id,deleted_at,NULL',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $data['installation_date'] = $request->installation_date != '' ? date('Y-m-d', strtotime($request->installation_date)) : '';

        $MachineAndEquipment = MachineAndEquipment::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Equipment created successfully.',
                'data'    => $MachineAndEquipment
            ]);
        }
    }

    public function show($id)
    {
        $machine = MachineAndEquipment::find($id);

        return view('machine-and-equipments.show',compact('machine'));
    }

    public function edit($id)
    {
        $data = MachineAndEquipment::find($id);

        return view('machine-and-equipments.edit', compact('data'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'device_model_name' => 'required|unique:machine_and_equipments,device_model_name,'.$id.',id,deleted_at,NULL',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $data['installation_date'] = $request->installation_date != '' ? date('Y-m-d', strtotime($request->installation_date)) : '';

        $MachineAndEquipment = MachineAndEquipment::find($id);

        if (!$MachineAndEquipment) {
            return redirect()->back()
                ->with('error','Equipment not found!');
        }

        $MachineAndEquipment->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Equipment Updated successfully.',
                'data'    => $MachineAndEquipment
            ]);
        }
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = MachineAndEquipment::where('id', '=', $request->id)->update($data);

            $Redirect = 'machine-and-equipments';

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Equipment status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function destroy(Request $request)
    {
        MachineAndEquipment::find($request->id)->delete();

        $Redirect = 'machine-and-equipments';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }
}
