<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ServerGroupCreateRequest;
use App\Http\Requests\Admin\ServerGroupDestroyRequest;
use App\Http\Requests\Admin\ServerGroupEditRequest;
use App\Http\Requests\Admin\ServerGroupIndexRequest;
use App\Http\Requests\Admin\ServerGroupRecordsRequest;
use App\Http\Requests\Admin\ServerGroupStoreRequest;
use App\Http\Requests\Admin\ServerGroupUpdateRequest;
use App\Models\Server;
use App\Models\ServerGroup;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class ServerGroupController extends Controller
{
    use LogsAdminActivity;
    /**
     * Display a listing of the resource.
     */
    public function index(ServerGroupIndexRequest $request): View
    {
        return view('admin.server-groups.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(ServerGroupCreateRequest $request): View
    {
        // PRC-817 dual-purpose guard: provisioning grubuna yalnız provisioning|both host eklenebilir.
        $servers = Server::provisionable()->where('status', 'active')->get();

        return view('admin.server-groups.create', compact('servers'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ServerGroupStoreRequest $request): JsonResponse
    {

        $validated = $request->validated();

        $serverGroup = ServerGroup::create([
            'name' => $validated['name'],
            'fill_strategy' => $validated['fill_strategy'],
        ]);

        // Sunucuları gruba ata
        if (! empty($validated['servers'])) {
            $serverGroup->servers()->attach($validated['servers']);
        }

        $this->logCreated($serverGroup, "Created server group #{$serverGroup->id} - {$serverGroup->name}");

        return response()->json([
            'success' => true,
            'message' => __('admin/server-groups.messages_created_successfully'),
            'data' => $serverGroup,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ServerGroupEditRequest $request, ServerGroup $serverGroup): View
    {
        // PRC-817 dual-purpose guard: provisioning grubuna yalnız provisioning|both host eklenebilir.
        $servers = Server::provisionable()->where('status', 'active')->get();
        $selectedServers = $serverGroup->servers->pluck('id')->toArray();

        return view('admin.server-groups.edit', compact('serverGroup', 'servers', 'selectedServers'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ServerGroupUpdateRequest $request, ServerGroup $serverGroup): JsonResponse
    {

        $validated = $request->validated();

        $serverGroup->update([
            'name' => $validated['name'],
            'fill_strategy' => $validated['fill_strategy'],
        ]);

        // Sunucu ilişkilerini güncelle
        $serverGroup->servers()->sync($validated['servers'] ?? []);

        $this->logUpdated($serverGroup, "Updated server group #{$serverGroup->id} - {$serverGroup->name}");

        return response()->json([
            'success' => true,
            'message' => __('admin/server-groups.messages_updated_successfully'),
            'data' => $serverGroup,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ServerGroupDestroyRequest $request, ServerGroup $serverGroup): JsonResponse
    {

        // İlişkileri temizle
        $serverGroup->servers()->detach();

        $this->logDeleted($serverGroup, "Deleted server group #{$serverGroup->id} - {$serverGroup->name}");

        $serverGroup->delete();

        return response()->json([
            'success' => true,
            'message' => __('admin/server-groups.messages_deleted_successfully'),
        ]);
    }

    /**
     * Get server groups data for DataTables.
     */
    public function records(ServerGroupRecordsRequest $request): JsonResponse
    {

        $query = ServerGroup::with(['servers']);

        // DataTables parametreleri
        $start = $request->get('start', 0);
        $length = $request->get('length', 10);
        $searchValue = $request->get('search.value', '');

        // Arama
        if (! empty($searchValue)) {
            $query->where('name', 'like', "%{$searchValue}%");
        }

        // Toplam kayıt sayısı
        $totalRecords = ServerGroup::count();
        $filteredRecords = $query->count();

        // Sıralama
        $orderColumn = $request->get('order.0.column', 0);
        $orderDirection = $request->get('order.0.dir', 'asc');

        $columns = ['id', 'name', 'fill_strategy', 'created_at'];
        if (isset($columns[$orderColumn])) {
            $query->orderBy($columns[$orderColumn], $orderDirection);
        }

        // Sayfalama
        $serverGroups = $query->skip($start)->take($length)->get();

        // Veriyi formatla
        $data = $serverGroups->map(function ($serverGroup) {
            return [
                'id' => $serverGroup->id,
                'name' => $serverGroup->name,
                'fill_strategy' => $serverGroup->fill_strategy,
                'servers_count' => $serverGroup->servers->count(),
                'created_at' => $serverGroup->created_at?->format('d.m.Y H:i'),
            ];
        });

        return response()->json([
            'draw' => intval($request->get('draw')),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'data' => $data,
        ]);
    }
}
