<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Facilities;
use App\Models\FacilitiesPhoto;

class FacilitiesPhotoController extends Controller
{
    public function listFacilityPhotos(Facilities $facilities)
    {
        // Load the album with its photos
       
            $facilitiesPhoto = FacilitiesPhoto::where('facility_id', $facilities->id)->orderBy('id', 'desc')->get();
        $data=[
            'facilitiesPhotos' => $facilitiesPhoto,
            'pageTitle' => 'Manage Photo : '. $facilities->name,
            'facilities'=>$facilities
        ];

        return view('back.pages.facility.facilityPhoto.photo_list', $data);
    }
    public function uploadFacilityPhotos(Request $request, Facilities $facilities)
    {
        $request->validate([
            'photos.*' => 'required|image|mimes:jpeg,png,jpg|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/facilities/';
            $folderName = str_replace(' ', '_', strtolower($facilities->name)) . '_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);
    
                    FacilitiesPhoto::create([
                        'facility_id' => $facilities->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()
            ]);
        }
    }
}
