<?php

namespace App\Http\Controllers\Admin;

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

class CarouselController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $images = CarouselImage::latest()->get();
        return view('admin.carousel', compact('images'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        $imagePath = $request->file('image')->store('carousel', 'public');

        CarouselImage::create([
            'image' => $imagePath,
            'is_active' => true
        ]);

        return redirect()->back()->with('success', 'Gambar carousel berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, CarouselImage $carousel)
    {
        $request->validate([
            'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'is_active' => 'nullable|boolean'
        ]);

        $data = [];

        if ($request->hasFile('image')) {
            // Delete old image
            if ($carousel->image) {
                Storage::disk('public')->delete($carousel->image);
            }
            $data['image'] = $request->file('image')->store('carousel', 'public');
        }

        if ($request->has('is_active')) {
            $data['is_active'] = $request->is_active;
        }

        $carousel->update($data);

        return redirect()->back()->with('success', 'Gambar carousel berhasil diperbarui');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(CarouselImage $carousel)
    {
        if ($carousel->image) {
            Storage::disk('public')->delete($carousel->image);
        }
        
        $carousel->delete();

        return redirect()->back()->with('success', 'Gambar carousel berhasil dihapus');
    }

    public function reorder(Request $request)
    {
        $request->validate([
            'orders' => 'required|array',
            'orders.*' => 'required|integer|exists:carousel_images,id'
        ]);

        foreach ($request->orders as $index => $id) {
            CarouselImage::where('id', $id)->update(['order' => $index]);
        }

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