<?php

namespace App\Http\Controllers\APIManagement;

use App\Http\Controllers\Controller;
use App\Models\MetaMintAPI;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class MetaMintAPIController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = MetaMintAPI::select([
            'id',
            'api_key',
            'api_salt',
            'api_target_url',
            'status'
        ]);

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

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

            return view('meta-mint-apis.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('meta-mint-apis.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_target_url' => 'required'
        ]);

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

        $data['api_target_url'] = $request->api_target_url;

        $key = '';

        do {
            $key = Str::random(32);
            $exists = MetaMintAPI::where('api_key', $key)->get();
        }
        while (count($exists) > 0);

        $data['api_key'] = $key;
        $data['api_salt'] = \Hash::make($key);

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

        return redirect()->route('meta-mint-apis.index')
            ->with('success', 'API 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 = MetaMintAPI::find($id);

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

        return view('meta-mint-apis.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)
    {
        $api = MetaMintAPI::find($id);

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

        $validator = \Validator::make($request->all(), [
            'api_target_url' => 'required'
        ]);

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

        $data['api_target_url'] = $request->api_target_url;

        $data = $api->update($data);

        return redirect()->route('meta-mint-apis.index')
            ->with('success', 'API updated successfully.');
    }

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

        if (!$api) {
            return response()->json([
                'success' => false,
                'message' => 'API not found!',
                'data'    => [
                    'reload' => true,
                    'redirect' => false,
                ]
            ]);
        }
        $api->delete();

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

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

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