<?php

namespace App\Http\Controllers\Admin;

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

class AdminHeroController extends Controller
{
    public function index(Request $request)
    {
        $query = Hero::query();

        // Cek apakah ada input pencarian
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhere('subtitle', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter berdasarkan status aktif/nonaktif
        if ($request->filled('status')) {
            $query->where('is_active', $request->status);
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $heroes = $query->orderBy('order')->orderBy('created_at', 'desc')->paginate($itemsPerPage)->withQueryString();

        return view('admin.heroes.index', compact('heroes'));
    }

    public function create()
    {
        return view('admin.heroes.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'nullable|string|max:255',
            'subtitle' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp',
            'is_active' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $data = $request->only(['title', 'subtitle', 'description', 'is_active', 'order']);
        $data['is_active'] = $request->has('is_active') ? true : false;
        $data['order'] = $request->order ?? 0;

        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('heroes', 'uploads');
            $data['image'] = $imagePath;
        }

        Hero::create($data);

        return redirect()->route('admin.heroes.index')
            ->with('add_message', 'Hero berhasil ditambahkan!');
    }

    public function edit($id)
    {
        $hero = Hero::findOrFail($id);
        return view('admin.heroes.edit', compact('hero'));
    }

    public function update(Request $request, $id)
    {
        $hero = Hero::findOrFail($id);

        $validated = $request->validate([
            'title' => 'nullable|string|max:255',
            'subtitle' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp',
            'is_active' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $validated['is_active'] = $request->has('is_active') ? true : false;
        $validated['order'] = $request->order ?? 0;

        // Jika ada gambar baru, hapus gambar lama
        if ($request->hasFile('image')) {
            if ($hero->image && Storage::disk('uploads')->exists($hero->image)) {
                Storage::disk('uploads')->delete($hero->image);
            }

            $validated['image'] = $request->file('image')->store('heroes', 'uploads');
        }

        $hero->update($validated);

        return redirect()->route('admin.heroes.index')
            ->with('add_message', 'Hero berhasil diperbarui!');
    }

    public function destroy($id)
    {
        $hero = Hero::findOrFail($id);

        // Hapus gambar jika ada
        if ($hero->image && Storage::disk('uploads')->exists($hero->image)) {
            Storage::disk('uploads')->delete($hero->image);
        }

        $hero->delete();

        return redirect()->route('admin.heroes.index')
            ->with('add_message', 'Hero berhasil dihapus!');
    }

    public function bulkDestroy(Request $request)
    {
        // Handle JSON string from form
        $ids = $request->ids;
        if (is_string($ids)) {
            $ids = json_decode($ids, true);
        }

        $request->merge(['ids' => $ids]);

        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:heroes,id'
        ]);

        $deletedCount = 0;

        foreach ($ids as $id) {
            $hero = Hero::findOrFail($id);

            // Hapus gambar jika ada
            if ($hero->image && Storage::disk('uploads')->exists($hero->image)) {
                Storage::disk('uploads')->delete($hero->image);
            }

            $hero->delete();
            $deletedCount++;
        }

        $message = $deletedCount > 1 
            ? "{$deletedCount} hero berhasil dihapus!" 
            : "Hero berhasil dihapus!";

        return redirect()->route('admin.heroes.index')
            ->with('add_message', $message);
    }
}
