<?php
// 3. Controller: GambarCarouselController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GambarCarousel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Auth;

class GambarCarouselController extends Controller
{
    public function index()
    {
        $carousels = GambarCarousel::latest()->get();
        return view('admin.carousel.index', compact('carousels'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'tajuk' => 'required|string|max:255',
            'keterangan' => 'nullable|string|max:180',
            'fail' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048',
            'tarikh_mula' => 'required|date',
            'tarikh_tamat' => 'required|date|after_or_equal:tarikh_mula',
        ]);

        $fail = $request->file('fail');
        $namaFail = Str::slug(pathinfo($fail->getClientOriginalName(), PATHINFO_FILENAME)) . '-' . time() . '.' . $fail->getClientOriginalExtension();
        $path = $fail->storeAs('caro', $namaFail, 'public');

        GambarCarousel::create([
            'tajuk' => $request->tajuk,
            'keterangan' => $request->keterangan,
            'fail_nama' => $namaFail,
            'fail_path' => $path,
            'tarikh_upload' => now(),
            'tarikh_mula' => $request->tarikh_mula,
            'tarikh_tamat' => $request->tarikh_tamat,
            'admin_id' => Auth::id(),
        ]);

        return redirect()->route('carousel.index')->with('success', 'Imej carousel berjaya dimuat naik.');
    }

    public function destroy($id)
    {
        $carousel = GambarCarousel::findOrFail($id);
        Storage::disk('public')->delete($carousel->fail_path);
        $carousel->delete();
        return back()->with('success', 'Imej dipadam.');
    }
}