<?php

namespace App\Http\Controllers\APIManagement;

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

class ApisManagementController extends Controller
{
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->checkPermission('api-management-list')) {
            return redirect()->back()->with('info', 'You don\'t have enough permission to access this page.');
        }

        $data = ApiManagement::select(['id','api_name','api_slug', 'api_type','is_default'])->paginate(10);

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

            $data = ApiManagement::select(['id','api_name','api_slug','api_type','is_default'])->when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('api_name', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

            return view('api-management.table', compact('data'));
        }
        else
        {
            return view('api-management.index',compact('data'));
        }
        // api-management
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('api-management.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(), [
            'api_name' => 'required',
            'api_slug' => 'required',
            'api_key'  => 'required',
        ]);

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

        $data['api_slug'] = \Str::slug(strtolower($request->api_slug), '-');


        ApiManagement::create($data);

        return response()->json([
            'success' => true,
            'message' => 'API been stored successfully',
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $api = ApiManagement::find($id);

        return view('api-management.show', compact('api'));
    }

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

        return view('api-management.edit', compact('api'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'api_name' => 'required',
            'api_slug' => 'required',
            'api_key'  => 'required',
        ]);

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

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

        $data['api_slug'] = \Str::slug(strtolower($request->api_slug), '-');

        $api = ApiManagement::find($id);

        if (!$api) {
            return redirect()->back()
                ->with('error','API data not found!');
        }

        $api->update($data);

        return response()->json([
            'success' => true,
            'message' => 'API data been updated successfully',
        ]);
    }

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

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'reload' => true,
                'redirect' => false,
            ]
        ]);
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = ApiManagement::where(['is_default' => $request->status])->count();

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

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

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