<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Club;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ClubController extends Controller
{
    public function index()
    {
        $clubs = Club::orderBy('name')->paginate(30);
        return view('admin.clubs.index', compact('clubs'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'        => ['required', 'string', 'max:100'],
            'type'        => ['nullable', 'in:club,national'],
            'short_name'  => ['nullable', 'string', 'max:10'],
            'nationality' => ['nullable', 'string', 'max:80'],
            'overall'     => ['nullable', 'integer', 'min:1', 'max:99'],
            'logo'        => ['nullable', 'image', 'mimes:png,jpg,jpeg,webp', 'max:512'],
        ]);

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('clubs', 'public');
        }

        Club::create($data);

        return back()->with('success', 'Klub "' . $data['name'] . '" berhasil ditambahkan.');
    }

    public function update(Request $request, int $id)
    {
        $club = Club::findOrFail($id);
        $data = $request->validate([
            'name'        => ['required', 'string', 'max:100'],
            'type'        => ['nullable', 'in:club,national'],
            'short_name'  => ['nullable', 'string', 'max:10'],
            'nationality' => ['nullable', 'string', 'max:80'],
            'overall'     => ['nullable', 'integer', 'min:1', 'max:99'],
            'is_active'   => ['nullable', 'boolean'],
            'logo'        => ['nullable', 'image', 'mimes:png,jpg,jpeg,webp', 'max:512'],
        ]);

        if ($request->hasFile('logo')) {
            if ($club->logo) Storage::disk('public')->delete($club->logo);
            $data['logo'] = $request->file('logo')->store('clubs', 'public');
        }

        $data['is_active'] = $request->boolean('is_active', true);
        $club->update($data);

        return back()->with('success', 'Klub berhasil diperbarui.');
    }

    public function destroy(int $id)
    {
        $club = Club::findOrFail($id);
        if ($club->logo) Storage::disk('public')->delete($club->logo);
        $club->delete();
        return back()->with('success', 'Klub berhasil dihapus.');
    }

    /** JSON search endpoint for select2/autocomplete. */
    public function search(Request $request)
    {
        $q    = $request->get('q', '');
        $type = $request->get('type'); // 'club', 'national', or null for all

        $query = Club::where('is_active', true)
            ->where(function ($query) use ($q) {
                $query->where('name', 'like', "%{$q}%")
                      ->orWhere('short_name', 'like', "%{$q}%")
                      ->orWhere('nationality', 'like', "%{$q}%");
            });

        if ($type) {
            $query->where('type', $type);
        }

        $clubs = $query->orderBy('type') // clubs first, then nationals
                       ->orderBy('overall', 'desc')
                       ->limit(50)
                       ->get(['id', 'name', 'short_name', 'type', 'logo', 'overall', 'nationality']);

        return response()->json($clubs->map(fn($c) => [
            'id'          => $c->id,
            'name'        => $c->name,
            'short_name'  => $c->short_name,
            'nationality' => $c->nationality,
            'overall'     => $c->overall,
            'type'        => $c->type,
            'type_label'  => $c->type_label,
            'logo_url'    => $c->logo_url,
        ]));
    }

    /** Import clubs from JSON. */
    public function import(Request $request)
    {
        $request->validate([
            'json_data' => ['required', 'string'],
        ]);

        $items = json_decode($request->json_data, true);
        if (!is_array($items)) {
            return back()->with('error', 'Format JSON tidak valid.');
        }

        $count = 0;
        foreach ($items as $item) {
            if (empty($item['name'])) continue;
            Club::firstOrCreate(
                ['name' => $item['name']],
                [
                    'type'        => $item['type']        ?? 'club',
                    'short_name'  => $item['short_name']  ?? null,
                    'nationality' => $item['nationality']  ?? null,
                    'overall'     => $item['overall']      ?? 80,
                    'is_active'   => true,
                ]
            );
            $count++;
        }

        return back()->with('success', $count . ' klub berhasil diimport.');
    }
}
