<?php
use App\Models\Carousel;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Layout;
use Illuminate\Support\Facades\Storage;

return new class extends Component {
    use WithFileUploads;

    public $carousels;
    public $title, $subtitle, $link, $image, $sort_order = 0, $is_active = true;
    public $editingId, $deletingId = null;
    public $showModal, $showDeleteModal = false;

    public function mount() {
        $this->loadCarousels();
    }

    public function loadCarousels() {
        $this->carousels = Carousel::orderBy('sort_order')->get();
    }

    public function openCreate() {
        $this->reset(['title', 'subtitle', 'link', 'image', 'editingId']);
        $this->showModal = true;
    }

    public function edit($id) {
        $carousel = Carousel::find($id);
        $this->editingId = $id;
        $this->title = $carousel->title;
        $this->subtitle = $carousel->subtitle;
        $this->link = $carousel->link;
        $this->sort_order = $carousel->sort_order;
        $this->is_active = $carousel->is_active;
        $this->showModal = true;
    }

    public function save() {
        $this->validate([
            'image' => $this->editingId ? 'nullable|image|max:2048' : 'required|image|max:2048',
            'title' => 'nullable|string|max:255',
        ]);

        $data = [
            'title' => $this->title,
            'subtitle' => $this->subtitle,
            'link' => $this->link,
            'sort_order' => $this->sort_order,
            'is_active' => $this->is_active,
        ];

        if ($this->image) {
            $data['image_path'] = $this->image->store('carousels', 'public');
        }

        if ($this->editingId) {
            Carousel::find($this->editingId)->update($data);
        } else {
            Carousel::create($data);
        }

        $this->showModal = false;
        $this->loadCarousels();
    }

    public function confirmDelete($id) {
        $this->deletingId = $id;
        $this->showDeleteModal = true;
    }

    public function delete() {
        if ($this->deletingId) {
            $carousel = Carousel::find($this->deletingId);
            Storage::disk('public')->delete($carousel->image_path);
            $carousel->delete();
            $this->reset('deletingId', 'showDeleteModal');
            $this->dispatch('toast', 
                type: 'error', 
                text: 'Carousel Deleted Successfully!'
            );
            $this->loadCarousels();
        }
    }

    protected function view($data = [])
    {
        return app('view')->file('C:\laragon\www\ecommerce\storage\framework/views/livewire/views/2184c461.blade.php', $data);
    }
};
