<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\MikrotikSecretDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreMikrotikSecretRequest;
use App\Http\Requests\UpdateMikrotikSecretRequest;
use App\Jobs\SyncMikrotikRouterDataJob;
use App\Models\Mikrotik;
use App\Models\MikrotikSecret;
use App\Services\MikrotikSecretService;
use Illuminate\Http\Request;

class MikrotikSecretController extends Controller
{
    public function __construct(protected MikrotikSecretService $service)
    {
        $this->authorizeResource(MikrotikSecret::class, 'mikrotik_secret');
    }

    public function index()
    {
        $routers = Mikrotik::orderBy('name')->get();
        $secretStats = MikrotikSecret::query()
            ->selectRaw('mikrotik_id, SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as enabled, SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as disabled')
            ->whereNotNull('customer_id')
            ->groupBy('mikrotik_id')
            ->get()
            ->keyBy('mikrotik_id');
        $routerStats = $routers->mapWithKeys(function (Mikrotik $router) use ($secretStats): array {
            $stats = $secretStats->get($router->id);

            return [$router->id => [
                'name' => $router->name,
                'ip' => $router->ip_address,
                'enabled' => (int) ($stats->enabled ?? 0),
                'disabled' => (int) ($stats->disabled ?? 0),
            ]];
        })->all();

        return view('admin.mikrotik-secrets.index', compact('routers', 'routerStats'));
    }

    public function data(Request $request, MikrotikSecretDataTable $dataTable)
    {
        return $dataTable->render($request);
    }

    public function store(StoreMikrotikSecretRequest $request)
    {
        $secret = $this->service->create($request->validated());

        return response()->json(['success' => true, 'data' => $secret], 201);
    }

    public function edit(MikrotikSecret $mikrotik_secret)
    {
        return response()->json([
            'data' => $mikrotik_secret,
            'update_url' => route('admin.mikrotik-secrets.update', $mikrotik_secret),
        ]);
    }

    public function update(UpdateMikrotikSecretRequest $request, MikrotikSecret $mikrotik_secret)
    {
        $data = $request->validated();
        if (empty($data['password'])) {
            unset($data['password']);
        }

        $this->service->update($mikrotik_secret, $data);

        return response()->json(['success' => true, 'data' => $mikrotik_secret->fresh()]);
    }

    public function destroy(MikrotikSecret $mikrotik_secret)
    {
        $this->service->delete($mikrotik_secret);

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

    public function toggleStatus(Request $request, MikrotikSecret $mikrotik_secret)
    {
        $this->authorize('update', $mikrotik_secret);
        $validated = $request->validate(['enabled' => ['required', 'boolean']]);

        try {
            $secret = $this->service->setEnabled($mikrotik_secret, (bool) $validated['enabled']);

            return response()->json(['success' => true, 'message' => 'PPP secret '.($secret->status ? 'enabled' : 'disabled').' successfully.', 'data' => $secret]);
        } catch (\Throwable $exception) {
            return response()->json(['success' => false, 'message' => $exception->getMessage()], 502);
        }
    }

    public function syncNow(Request $request)
    {
        $this->authorize('viewAny', MikrotikSecret::class);
        $validated = $request->validate(['mikrotik_id' => ['nullable', 'integer', 'exists:mikrotiks,id']]);
        SyncMikrotikRouterDataJob::dispatch($validated['mikrotik_id'] ?? null);

        return response()->json(['success' => true, 'message' => 'MikroTik secret sync queued.']);
    }
}
