<?php

namespace App\Http\Controllers\LicenseManagement;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\LicenseAuthentication;

class LicenseAuthenticationsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = LicenseAuthentication::select(
            'id',
            'license_key',
            'license_type',
            'is_default',
        )
        ->latest();

        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('license_secret', 'like', '%'.$search_query.'%')
                    ->orWhere('license_key', 'like', '%'.$search_query.'%')
                    ->orWhere('license_type', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

            return view('license-authentications.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('license-authentications.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(), [
            'license_key'    => 'required|max:16',
            'license_secret' => 'required|max:64',
            'license_type'   => 'required|max:32',
            'api_endpoint'   => 'required',
        ]);

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

        $default_check = LicenseAuthentication::where(['is_default' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = '1';
        }

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

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

    /**
     * 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 = LicenseAuthentication::find($id);

        return view('license-authentications.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)
    {
        $license = LicenseAuthentication::find($id);

        if (!$license) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found!',
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', 'Record not found!');
        }

        $validator = \Validator::make($request->all(), [
            'license_key'    => 'required|max:16',
            'license_secret' => 'required|max:64',
            'license_type'   => 'required|max:32',
            'api_endpoint'   => 'required',
        ]);

        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 = $license->update($data);

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

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

        return response()->json([
            'success' => true,
            'message' => ['License Deleted Successfully'],
        ]);
    }

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

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