<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Slider;
use App\Models\SliderItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;

class SliderController extends Controller
{
    /**
     * Display a listing of sliders
     */
    public function index()
    {
        $sliders = Slider::with('items.product')
            ->orderBy('order')
            ->get();
        
        return view('admin.sliders.index', compact('sliders'));
    }

    /**
     * Show the form for creating a new slider
     */
    public function create()
    {
        return view('admin.sliders.create');
    }

    /**
     * Store a newly created slider
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:banner,product',
            'is_active' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $validated['slug'] = Str::slug($validated['name']);
        
        // Ensure unique slug
        $originalSlug = $validated['slug'];
        $counter = 1;
        while (Slider::where('slug', $validated['slug'])->exists()) {
            $validated['slug'] = $originalSlug . '-' . $counter;
            $counter++;
        }

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

        Slider::create($validated);

        return redirect()->route('admin.sliders.index')
            ->with('success', 'Slider başarıyla oluşturuldu.');
    }

    /**
     * Display the specified slider
     */
    public function show(Slider $slider)
    {
        $slider->load('items.product');
        return view('admin.sliders.show', compact('slider'));
    }

    /**
     * Show the form for editing the specified slider
     */
    public function edit(Slider $slider)
    {
        $slider->load('items.product');
        $products = Product::active()->orderBy('name')->get();
        return view('admin.sliders.edit', compact('slider', 'products'));
    }

    /**
     * Update the specified slider
     */
    public function update(Request $request, Slider $slider)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:banner,product',
            'is_active' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        // Update slug if name changed
        if ($slider->name !== $validated['name']) {
            $validated['slug'] = Str::slug($validated['name']);
            // Ensure unique slug
            $originalSlug = $validated['slug'];
            $counter = 1;
            while (Slider::where('slug', $validated['slug'])->where('id', '!=', $slider->id)->exists()) {
                $validated['slug'] = $originalSlug . '-' . $counter;
                $counter++;
            }
        }

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

        $slider->update($validated);

        return redirect()->route('admin.sliders.index')
            ->with('success', 'Slider başarıyla güncellendi.');
    }

    /**
     * Remove the specified slider
     */
    public function destroy(Slider $slider)
    {
        $slider->delete();

        return redirect()->route('admin.sliders.index')
            ->with('success', 'Slider başarıyla silindi.');
    }

    /**
     * Add item to slider
     */
    public function addItem(Request $request, Slider $slider)
    {
        if ($slider->type === 'product') {
            $validated = $request->validate([
                'product_id' => 'required|exists:products,id',
                'order' => 'nullable|integer|min:0',
            ]);

            // Check if product already exists in slider
            $exists = SliderItem::where('slider_id', $slider->id)
                ->where('product_id', $validated['product_id'])
                ->exists();

            if ($exists) {
                return back()->withErrors(['error' => 'Bu ürün zaten slider\'da mevcut.']);
            }

            SliderItem::create([
                'slider_id' => $slider->id,
                'product_id' => $validated['product_id'],
                'order' => $validated['order'] ?? 0,
                'is_active' => true,
            ]);
        } else {
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
                'link' => 'nullable|string|max:255',
                'order' => 'nullable|integer|min:0',
            ]);

            // Handle image upload
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                $filename = 'slider-' . time() . '-' . Str::random(10) . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('uploads/sliders'), $filename);
                $validated['image'] = '/uploads/sliders/' . $filename;
            }

            SliderItem::create([
                'slider_id' => $slider->id,
                'title' => $validated['title'],
                'description' => $validated['description'] ?? null,
                'image' => $validated['image'],
                'link' => $validated['link'] ?? null,
                'order' => $validated['order'] ?? 0,
                'is_active' => true,
            ]);
        }

        return back()->with('success', 'Öğe başarıyla eklendi.');
    }

    /**
     * Remove item from slider
     */
    public function removeItem($item)
    {
        $sliderItem = SliderItem::findOrFail($item);
        
        // Delete image if exists
        if ($sliderItem->image && file_exists(public_path($sliderItem->image))) {
            unlink(public_path($sliderItem->image));
        }

        $sliderItem->delete();

        return back()->with('success', 'Öğe başarıyla silindi.');
    }

    /**
     * Update item order
     */
    public function updateItemOrder(Request $request)
    {
        $items = $request->input('items', []);
        
        foreach ($items as $index => $itemId) {
            SliderItem::where('id', $itemId)->update(['order' => $index]);
        }

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