<?php

namespace App\Http\Controllers\Api;

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

class VpnPayloadController extends Controller
{
    public function index()
    {
        $payloads = VpnPayload::orderBy('priority', 'desc')->get();
        return response()->json(['success' => true, 'data' => $payloads]);
    }

    public function getAvailable()
    {
        $payloads = VpnPayload::available()->get();
        return response()->json(['success' => true, 'data' => $payloads]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'config' => 'required|json',
            'type' => 'required|in:cloud,tunnel',
            'priority' => 'integer|min:0'
        ]);

        $payload = VpnPayload::create($request->all());
        return response()->json(['success' => true, 'data' => $payload]);
    }

    public function update(Request $request, VpnPayload $payload)
    {
        $request->validate([
            'name' => 'string',
            'config' => 'json',
            'status' => 'in:live,blocked,slow',
            'priority' => 'integer|min:0'
        ]);

        $payload->update($request->all());
        return response()->json(['success' => true, 'data' => $payload]);
    }

    public function destroy(VpnPayload $payload)
    {
        $payload->delete();
        return response()->json(['success' => true]);
    }

    public function updateOrder(Request $request)
    {
        $request->validate([
            'orders' => 'required|array',
            'orders.*.id' => 'required|exists:vpn_payloads,id',
            'orders.*.priority' => 'required|integer|min:0'
        ]);

        foreach ($request->orders as $order) {
            VpnPayload::where('id', $order['id'])
                ->update(['priority' => $order['priority']]);
        }

        return response()->json(['success' => true]);
    }

    public function validatePayload(Request $request)
    {
        $request->validate([
            'payload_id' => 'required|exists:vpn_payloads,id'
        ]);

        $payload = VpnPayload::find($request->payload_id);
        
        // Here you can implement the actual validation logic
        // For now, we'll just check if it's marked as live
        $isValid = $payload->isAvailable();

        return response()->json([
            'success' => true,
            'is_valid' => $isValid
        ]);
    }
}