<?php

namespace App\Http\Controllers\Backoffice;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\BlacklistEntry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BlacklistController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax() || $request->wantsJson() || $request->boolean('ajax')) {
            $items = BlacklistEntry::with(['creator', 'updater'])
                ->orderBy('id', 'desc')
                ->get();

            return response()->json([
                'data' => $items->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'player_id' => $item->player_id,
                        'player_name' => $item->player_name ?: '-',
                        'description' => $item->description ?: '-',
                        'created_by_name' => $item->creator ? $item->creator->full_name : '-',
                        'created_at' => $item->created_at ? $item->created_at->format('d.m.Y H:i') : '-',
                    ];
                }),
            ]);
        }

        return view('backoffice.blacklist.index');
    }

    public function store(Request $request)
    {
        $request->validate([
            'player_id' => 'required|string|max:255|unique:blacklist_entries,player_id',
            'player_name' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
        ], [
            'player_id.required' => 'Player ID is required.',
            'player_id.unique' => 'Player ID already exists in blacklist.',
        ]);

        DB::beginTransaction();
        try {
            $item = BlacklistEntry::create([
                'player_id' => $request->player_id,
                'player_name' => $request->player_name,
                'description' => $request->description,
                'created_by' => auth()->id(),
            ]);

            ActivityLog::log(
                'create_blacklist',
                'blacklist',
                'Blacklist entry created',
                null,
                $item->toArray()
            );

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Blacklist entry created.',
                'item' => $item,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Create failed: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function show($id)
    {
        $item = BlacklistEntry::findOrFail($id);

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

    public function update(Request $request, $id)
    {
        $item = BlacklistEntry::findOrFail($id);

        $request->validate([
            'player_id' => 'required|string|max:255|unique:blacklist_entries,player_id,' . $item->id,
            'player_name' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
        ], [
            'player_id.required' => 'Player ID is required.',
            'player_id.unique' => 'Player ID already exists in blacklist.',
        ]);

        DB::beginTransaction();
        try {
            $oldData = $item->toArray();

            $item->update([
                'player_id' => $request->player_id,
                'player_name' => $request->player_name,
                'description' => $request->description,
                'updated_by' => auth()->id(),
            ]);

            ActivityLog::log(
                'update_blacklist',
                'blacklist',
                'Blacklist entry updated',
                $oldData,
                $item->toArray()
            );

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Blacklist entry updated.',
                'item' => $item,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Update failed: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function destroy($id)
    {
        $item = BlacklistEntry::findOrFail($id);

        DB::beginTransaction();
        try {
            $oldData = $item->toArray();
            $item->delete();

            ActivityLog::log(
                'delete_blacklist',
                'blacklist',
                'Blacklist entry deleted',
                $oldData,
                null
            );

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Blacklist entry deleted.',
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Delete failed: ' . $e->getMessage(),
            ], 500);
        }
    }
}
