<?php

namespace App\Http\Controllers;

use App\Models\Album;
use App\Http\Requests\StoreAlbumRequest;
use App\Http\Requests\UpdateAlbumRequest;
use Illuminate\Support\Facades\Log;

class AlbumController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $albums = Album::orderBy('created_at', 'desc')->get();
        return view('admin.album.index', compact('albums'));
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreAlbumRequest $request)
    {
        $data = $request->validated();
        $data['main_image'] = $this->uploadImage($request, 'main_image');

        Album::create($data);
        return redirect()->route('albums.index')->with('success', 'Album created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(Album $album)
    {
        return view('admin.album.show', compact('album'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Album $album)
    {
        return view('admin.album.edit', compact('album'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateAlbumRequest $request, Album $album)
    {
        $data = $request->validated();

        $data['main_image'] = $this->uploadImage($request, 'main_image', $album->main_image);

        $album->update(array_filter($data));

        return redirect()->route('albums.index')->with('success', 'Album updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Album $album)
    {
        $this->deleteImage($album->main_image);

        $album->delete();
        return redirect()->route('albums.index')->with('success', 'Album deleted successfully.');
    }

    /**
     * Handle image upload.
     */
    private function uploadImage($request, $fieldName, $oldImage = null)
    {
        if ($request->hasFile($fieldName)) {
            $this->deleteImage($oldImage);

            $file = $request->file($fieldName);
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/albums'), $filename);

            return $filename;
        }
        return $oldImage;
    }

    /**
     * Delete image if exists.
     */
    private function deleteImage($image)
    {
        if ($image) {
            $imagePath = public_path('uploads/albums/' . $image);
            if (file_exists($imagePath)) {
                unlink($imagePath);
                Log::info('Image deleted successfully', ['imagePath' => $imagePath]);
            } else {
                Log::warning('File does not exist', ['imagePath' => $imagePath]);
            }
        }
    }
}