<?php

namespace App\Http\Controllers\LicenseManagement;

use App\Http\Controllers\Controller;
use App\Models\Server;
use Illuminate\Http\Request;
class ServersController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:server-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Server::select(
            'id',
            'server_name',
            'server_code',
            'login_link',
            'private_link',
            'server_ip',
            'user_name',
            'password',
            'status',
            'default',
        );

        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('server_name', 'like', '%'.$search_query.'%')
                ->orWhere('user_name', 'like', '%'.$search_query.'%');
            })
            ->orderBy('id','ASC')
            ->groupBy('id')
            ->paginate($sort_by);

            return view('server.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('server.index',compact('data'));
        }
    }

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('server.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'server_name'   => 'required',
            'login_link'    => 'required|unique:servers,login_link,NULL,id,deleted_at,NULL|different:server_ip',
            'server_ip'     => 'required|unique:servers,server_ip,NULL,id,deleted_at,NULL|different:login_link',
        ]);

        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']);

        $data['server_code'] = strtoupper(str_replace(' ', '_', $request->server_name));

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

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

        return redirect()->route('server.index')
            ->with('success', 'Server created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Server::find($id);

        return view('server.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'server_name'   => 'required',
            'login_link'    => 'required|unique:servers,login_link,' . $id . ',id,deleted_at,NULL|different:server_ip',
            'server_ip'     => 'required|unique:servers,server_ip,' . $id . ',id,deleted_at,NULL|different:login_link',
        ]);

        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 = Server::whereId($id)->update($data);
        $data = Server::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Server updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('server.index')
            ->with('success', 'Server updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = Server::find($request->id);

        if ($data->default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'enquiry-sources';

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


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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Server status successfully change'],
                    'data' => [
                        'redirect' => '/tags/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = Server::where(['default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Server!'],
                    'data'    => []
                ]);
            }

            $Update = Server::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Server default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
}
