<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Models\VpsDetail;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class VpsDetailController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = VpsDetail::join('vps', 'vps.id', '=', 'vps_details.vps_id')
                ->join('vps_proxies', 'vps_proxies.id', '=', 'vps_details.vps_proxies_id')
                ->join('vps_countries', 'vps_countries.id', '=', 'vps.vps_country_id')
                ->join('vps_categories', 'vps_categories.id', '=', 'vps_details.vps_category_id')
                ->select('vps_details.*', 'vps.name as vps_name', 'vps_proxies.name as vps_proxies_name', 'vps_countries.name as vps_country_name', 'vps_categories.name as vps_category_name')
                ->orderBy('vps.name', 'asc')
                ->orderBy('vps_proxies.seq', 'asc');
            return Datatables::of($data)
                ->addIndexColumn()
                ->editColumn('expires_at', function ($row) {
                    return $row->created_at->format('d-m-Y H:i:s');
                })
                ->addColumn('action', function ($row) {
                    $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;
                })
                ->addColumn('limit', function ($row) {
                    return $row->data_limit_reset_strategy . '<br/>' . $row->data_limit . ' GB';
                })
                ->rawColumns(['action', 'limit'])
                ->make(true);
        }

        return view('admin.vps_detail');
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'vps_id' => [
                'required',
                Rule::unique('vps_details')->where(function ($query) use ($request) {
                    return $query->where('vps_proxies_id', $request->vps_proxies_id);
                })->ignore($request->id),
            ],
            'vps_category_id' => 'required',
            'vps_proxies_id' => 'required',
            'price' => 'required',
            'price_hour' => 'required',
            'quota' => 'required',
            'max_session' => 'required',
            'data_limit' => 'required',
            'data_limit_reset_strategy' => 'required',
            'is_pay' => 'required|numeric',
        ], [
            'vps_id.unique' => 'vps and proxies already exists.',
        ]);

        VpsDetail::updateOrCreate(
            [
                'id' => $request->id
            ],
            [
                'vps_id' => $request->vps_id,
                'vps_category_id' => $request->vps_category_id,
                'vps_proxies_id' => $request->vps_proxies_id,
                'price' => str_replace(',', '', $request->price),
                'price_hour' => str_replace(',', '', $request->price_hour),
                'quota' => str_replace(',', '', $request->quota),
                'max_session' => str_replace(',', '', $request->max_session),
                'data_limit' => str_replace(',', '', $request->data_limit),
                'data_limit_reset_strategy' => $request->data_limit_reset_strategy,
                'is_pay' => $request->is_pay,
            ]
        );

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

    public function show($id): JsonResponse
    {
        $data = VpsDetail::where('vps_details.id', $id)
            ->join('vps', 'vps.id', '=', 'vps_details.vps_id')
            ->join('vps_categories', 'vps_categories.id', '=', 'vps_details.vps_category_id')
            ->join('vps_proxies', 'vps_proxies.id', '=', 'vps_details.vps_proxies_id')
            ->select('vps_details.*', 'vps.name as vps_name', 'vps_proxies.name as vps_proxies_name', 'vps_categories.name as vps_category_name')->first();

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

    public function destroy(Request $request): JsonResponse
    {
        $request->validate([
            'id' => 'required|integer|exists:vps_details,id',
        ]);
        $updated = VpsDetail::find($request->id)?->delete();
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $updated ? 200 : 404,
                'message' => $updated ? 'OK' : 'Record not found or already inactive',
            ]
        ], $updated ? 200 : 404);
    }

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

        $data = VpsDetail::join('vps', 'vps.id', '=', 'vps_details.vps_id')
            ->join('vps_categories', 'vps_categories.id', '=', 'vps_details.vps_category_id')
            ->join('vps_proxies', 'vps_proxies.id', '=', 'vps_details.vps_proxies_id')
            ->where('vps.name', 'LIKE', "%$query%")
            ->whereNull('vps_details.deleted_at')
            ->select('vps_details.id', DB::raw('CONCAT(vps_categories.name, " - ", vps.name, " - ", vps_proxies.name, " - ", vps_details.price) as name'))
            ->paginate($limit);

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

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