<?php

namespace App\Livewire\Admin;

use App\Models\Album;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Livewire\Component;
use Livewire\WithPagination;

class Albums extends Component
{
    use WithPagination;

    public $perPage = 5;
    public $search = null;
    public $department = null; // Just in case albums are department-specific too

    protected $queryString = [
        'search' => ['except' => ''],
        'department' => ['except' => ''],
    ];

    protected $listeners = [
        'deleteAlbumAction',
    ];

    public function mount() {}

    public function updateSearch()
    {
        $this->resetPage();
    }

    public function deleteAlbum($id)
    {
        $this->dispatch('deleteAlbum', ['id' => $id]);
    }

    public function deleteAlbumAction($id)
    {
        $album = Album::findOrFail($id);

        $coverImagePath = public_path('images/albums/' . $album->cover_photo);

        // Delete cover photo if it exists
        if (!empty($album->cover_photo) && File::exists($coverImagePath)) {
            File::delete($coverImagePath);
        }

        // Handle associated photos and their folder
        $photos = $album->photos; // assuming hasMany relationship
        $folder = null;

        foreach ($photos as $photo) {
            $photoFullPath = public_path('images/albums/' . $photo->photo_path);

            // Determine the folder path
            if (!$folder && strpos($photo->photo_path, '/') !== false) {
                $folder = explode('/', $photo->photo_path)[0];
            }

            if (File::exists($photoFullPath)) {
                File::delete($photoFullPath);
            }

            $photo->delete(); // Delete the photo DB record
        }

        // Delete the folder if it exists
        if ($folder && File::exists(public_path("images/albums/$folder"))) {
            File::deleteDirectory(public_path("images/albums/$folder"));
        }

        // Delete the album
        $deleted = $album->delete();

        if ($deleted) {
            $this->dispatch('showToastr', type: 'success', message: 'Album and all associated images and folders deleted.');
        } else {
            $this->dispatch('showToastr', type: 'error', message: 'Failed to delete album.');
        }
    }

    public function render()
    {
        $albums = Album::latest()
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . trim($this->search) . '%')
                    ->orWhere('description', 'like', '%' . trim($this->search) . '%');
            })
            ->when($this->department, function ($query) {
                $query->where('department', $this->department);
            })
            ->paginate($this->perPage);

        return view('livewire.admin.albums', compact('albums'));
    }
}
