<?php

namespace App\Http\Controllers\Admin;

use App\Models\VpsServer;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\VpsSubscription;

class VpsServerController extends Controller
{
    public function index(Request $request)
    {

        if ($request->ajax()) {
            $data = VpsServer::join('vps_countries', 'vps_countries.id', '=', 'vps.vps_country_id')
                ->select('vps.*', 'vps.name as vps_name', 'vps_countries.name as vps_country_name')
                ->orderBy('vps.name', 'asc')
                ->orderBy('vps_countries.seq', 'asc');

            return Datatables::of($data)
                ->addIndexColumn()
                ->editColumn('status', function ($row) {
                    return $row->status == 'online' ? '<span class="right badge badge-success">Online</span>' : '<span class="right badge badge-danger">Offline</span>';
                })
                ->addColumn('action', function ($row) {
                    $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Show" class="btn btn-info btn-xs showData"><i class="fa fa-eye"></i></a>';
                    $btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Edit" class="btn btn-primary btn-xs editData"><i class="fa fa-edit"></i></a>';
                    $btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Delete" class="btn btn-danger btn-xs deleteData"><i class="fa fa-trash"></i></a>';
                    return $btn;
                })
                ->rawColumns(['action', 'status'])
                ->make(true);
        }

        return view('admin.vps_server');
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'vps_country_id' => 'required',
            'name' => 'required',
            'speed' => 'required',
            'protocol' => 'required',
            'hostname' => 'required',
            'ipaddress' => 'required',
            'username' => 'required',
            'password' => 'required',
            'token_type' => 'required',
            'access_token' => 'required',
        ]);

        VpsServer::updateOrCreate(
            [
                'id' => $request->id
            ],
            [
                'vps_country_id' => $request->vps_country_id,
                'name' => $request->name,
                'speed' => $request->speed,
                'description' => $request->description,
                'protocol' => $request->protocol,
                'hostname' => $request->hostname,
                'ipaddress' => $request->ipaddress,
                'username' => $request->username,
                'password' => $request->password,
                'token_type' => $request->token_type,
                'access_token' => $request->access_token,
            ]
        );

        $code = 200;
        $message = 'OK';
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }

    public function show($id): JsonResponse
    {
        $data = VpsServer::join('vps_countries', 'vps_countries.id', '=', 'vps.vps_country_id')
            ->select('vps.*', 'vps.name as vps_name', 'vps_countries.name as vps_country_name')
            ->find($id);

        return response()->json($data);
    }

    public function edit($id): JsonResponse
    {
        $data = VpsServer::join('vps_countries', 'vps_countries.id', '=', 'vps.vps_country_id')
            ->select('vps.*', 'vps.name as vps_name', 'vps_countries.name as vps_country_name')
            ->find($id);

        return response()->json($data);
    }

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

        $code = 200;
        $message = 'OK';
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }

    public function select2(Request $request)
    {
        $query = $request->get('q');
        $limit = 10;

        $data = VpsServer::where('name', 'LIKE', "%$query%")
            ->paginate($limit);

        $results = $data->map(function ($item) {
            return [
                'id' => $item->id,
                'text' => $item->name,
            ];
        });

        return response()->json([
            'data' => $results,
            'next_page_url' => $data->nextPageUrl(),
        ]);
    }

    public function ipAddress(Request $request): JsonResponse
    {
        $id = $request->id;
        $user = auth()->user();
        if (empty($id)) {
            $code = 400;
            $message = 'Bad Request';
            return response()->json([
                'response' => null,
                'metadata' => [
                    'code' => $code,
                    'message' => $message
                ]
            ], $code);
        }
        $min_amount_ip = Setting::find('1')->min_amount_ip;
        if ($user->amount < $min_amount_ip) {
            $code = 403;
            $message = 'Minimal saldo pada akun IDR ' . number_format($min_amount_ip, 0, ',', '.') . ' atau hubungi Admin LingVPN di https://t.me/LingVPN';
            return response()->json([
                'response' => null,
                'metadata' => [
                    'code' => $code,
                    'message' => $message
                ]
            ], $code);
        }

        $code = 200;
        $message = 'OK';
        $vps_subscription = VpsSubscription::join('vps_details', 'vps_details.id', '=', 'vps_subscriptions.vps_details_id')
            ->where('vps_subscriptions.user_id', $user->id)
            ->where('vps_subscriptions.id', $id)
            ->first();
        return response()->json([
            'response' =>
            [
                'ipaddress' => VpsServer::find($vps_subscription->vps_id)->ipaddress,
            ],
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }
}
