<?php

namespace App\Http\Controllers\Admin;

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

class HeroController extends Controller
{
    public function index()
    {
        $heroes = Hero::orderBy('sort_order')->get();
        return view('admin.heroes.index', compact('heroes'));
    }

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

    public function store(Request $request)
    {
        $data = $this->validateData($request);
        $images = [];
        if ($request->hasFile('side_images')) {
            foreach ($request->file('side_images') as $file) {
                $images[] = $file->store('heroes', 'public');
            }
        }
        $data['side_images'] = $images;
        Hero::create($data);
        return redirect()->route('admin.heroes.index')->with('success', 'Hero нэмэгдлээ.');
    }

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

    public function update(Request $request, Hero $hero)
    {
        $data = $this->validateData($request);
        $images = $hero->side_images ?? [];

        if ($request->filled('existing_images')) {
            $images = $request->existing_images;
        }
        if ($request->hasFile('side_images')) {
            foreach ($request->file('side_images') as $file) {
                $images[] = $file->store('heroes', 'public');
            }
        }
        $data['side_images'] = array_values($images);

        $hero->update($data);
        return redirect()->route('admin.heroes.index')->with('success', 'Шинэчлэгдлээ.');
    }

    public function destroy(Hero $hero)
    {
        foreach ($hero->side_images ?? [] as $img) Storage::disk('public')->delete($img);
        $hero->delete();
        return back()->with('success', 'Устгагдлаа.');
    }

    private function validateData(Request $request): array
    {
        return $request->validate([
            'title_line_1'  => 'required|string|max:255',
            'title_line_2'  => 'required|string|max:255',
            'title_line_3'  => 'required|string|max:255',
            'description'   => 'nullable|string',
            'button_text'   => 'nullable|string|max:120',
            'button_link'   => 'nullable|string|max:255',
            'video_url'     => 'nullable|url|max:255',
            'side_images.*' => 'nullable|image|max:5120',
            'is_active'     => 'nullable|boolean',
            'sort_order'    => 'nullable|integer',
        ]);
    }
}
