<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Support\ImageOptimizer;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    public function create() { return redirect()->route('admin.banners.index'); }
    public function show(Banner $banner) { return redirect()->route('admin.banners.index'); }
    public function edit(Banner $banner) { return redirect()->route('admin.banners.index'); }

    public function index()
    {
        $banners = Banner::orderBy('sort_order')->get();
        return view('admin.banners.index', compact('banners'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'      => 'required|string|max:255',
            'link'       => 'nullable|url',
            'sort_order' => 'integer',
            'is_active'  => 'boolean',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = ImageOptimizer::store($request->file('image'), 'banners', 'site_banner');
        } else {
            return back()->withErrors(['image' => 'Görsel zorunludur.']);
        }

        $data['is_active'] = $request->boolean('is_active');
        Banner::create($data);
        return back()->with('success', 'Banner eklendi.');
    }

    public function update(Request $request, Banner $banner)
    {
        $data = $request->validate([
            'title'      => 'required|string|max:255',
            'link'       => 'nullable|url',
            'sort_order' => 'integer',
            'is_active'  => 'boolean',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = ImageOptimizer::store($request->file('image'), 'banners', 'site_banner');
        }

        $data['is_active'] = $request->boolean('is_active');
        $banner->update($data);
        return back()->with('success', 'Banner güncellendi.');
    }

    public function destroy(Banner $banner)
    {
        $banner->delete();
        return back()->with('success', 'Banner silindi.');
    }
}
