<?php

namespace App\Http\Controllers;

use App\Models\Bestseller;
use App\Models\CarouselImage;
use App\Models\GalleryCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class LandingPageController extends Controller
{
    public function index()
    {
        $bestsellers = Bestseller::all();
        $carouselImages = CarouselImage::where('is_active', true)
            ->latest()
            ->get();

        $galleryCategories = GalleryCategory::with('images')->get();

        return view('landingpage', compact('bestsellers', 'carouselImages', 'galleryCategories'));
    }

    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');
    }

    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');
    }

    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');
    }
} 