<?php

namespace App\Http\Controllers;
use App\Models\Album;
use App\Models\Photo;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;

class AlbumPhotoController extends Controller
{
    public function uploadPhoto(Request $request, Album $album)
    {
        $request->validate([
            'photos.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
        ], [
            'photos.*.required' => 'Please upload at least one image.',
            'photos.*.image' => 'Only image files are allowed.',
            'photos.*.mimes' => 'Only jpeg, png, jpg formats are accepted.',
        ]);
    
        try {
            $basePath = 'images/albums/';
            $folderName = str_replace(' ', '_', strtolower($album->title)) . '_photos';
            $fullPath = public_path($basePath . $folderName);
    
            if (!file_exists($fullPath)) {
                mkdir($fullPath, 0777, true);
            }
    
            if ($request->hasFile('photos')) {
                foreach ($request->file('photos') as $file) {
                    $fileName = uniqid() . '.' . $file->getClientOriginalExtension();
                    $file->move($fullPath, $fileName);
    
                    Photo::create([
                        'album_id' => $album->id,
                        'photo_path' => $folderName . '/' . $fileName,
                    ]);
                }
    
                return response()->json([
                    'status' => 1,
                    'message' => 'Photos uploaded successfully!'
                ]);
            }
    
            return response()->json([
                'status' => 0,
                'message' => 'No photos uploaded.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 0,
                'message' => 'Something went wrong. ' . $e->getMessage()
            ]);
        }
    }
    
        
        public function listPhotos(Album $album)
    {
        // Load the album with its photos
       
            $photos = Photo::where('album_id', $album->id)->orderBy('id', 'desc')->get();
        $data=[
            'photos' => $photos,
            'pageTitle' => 'Manage Photo : '. $album->title,
            'album'=>$album
        ];

        return view('back.pages.album.photo.photo_list', $data);
    }

    

}
