<?php

namespace App\Http\Controllers\Api;

use App\Models\GalleryAlbum;
use App\Models\GalleryMedia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class GalleryController extends BaseApiController
{
    /**
     * List published gallery albums
     */
    public function albums(Request $request)
    {
        $user = Auth::user();
        $association = $user->associations()->first();

        if (!$association) {
            return $this->error('No association found', null, 404);
        }

        $query = GalleryAlbum::where('association_id', $association->id)
            ->published()
            ->ordered()
            ->with('creator:id,firstname,surname')
            ->withCount('media');

        // Filter by source type
        if ($request->filled('source_type')) {
            $query->bySource($request->input('source_type'));
        }

        // Search
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        $perPage = $request->input('per_page', 12);
        return $this->paginated($query, $perPage);
    }

    /**
     * Get album detail with paginated media
     */
    public function albumDetail(Request $request, $id)
    {
        $user = Auth::user();
        $association = $user->associations()->first();

        if (!$association) {
            return $this->error('No association found', null, 404);
        }

        $album = GalleryAlbum::where('association_id', $association->id)
            ->published()
            ->with('creator:id,firstname,surname')
            ->find($id);

        if (!$album) {
            return $this->error('Album not found', null, 404);
        }

        // Paginated media
        $perPage = $request->input('per_page', 24);
        $media = $album->media()
            ->approved()
            ->with('uploader:id,firstname,surname')
            ->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => [
                'album' => $album,
                'media' => $media->items(),
            ],
            'pagination' => [
                'current_page' => $media->currentPage(),
                'last_page' => $media->lastPage(),
                'per_page' => $media->perPage(),
                'total' => $media->total(),
            ],
        ]);
    }

    /**
     * Upload media to an album (if member uploads allowed)
     */
    public function uploadMedia(Request $request, $albumId)
    {
        $user = Auth::user();
        $association = $user->associations()->first();

        if (!$association) {
            return $this->error('No association found', null, 404);
        }

        $album = GalleryAlbum::where('association_id', $association->id)
            ->published()
            ->find($albumId);

        if (!$album) {
            return $this->error('Album not found', null, 404);
        }

        if (!$album->allow_member_uploads) {
            return $this->error('Member uploads are not allowed for this album', null, 403);
        }

        $request->validate([
            'files' => 'required|array|max:10',
            'files.*' => 'file|mimes:jpg,jpeg,png,webp,gif,mp4,mov,avi|max:51200', // 50MB
            'captions' => 'nullable|array',
            'captions.*' => 'nullable|string|max:500',
        ]);

        $uploadedMedia = [];

        foreach ($request->file('files') as $index => $file) {
            $isVideo = in_array($file->getClientOriginalExtension(), ['mp4', 'mov', 'avi']);
            $mediaType = $isVideo ? 'video' : 'image';
            $path = $file->store("gallery/{$album->id}", 'public');

            $media = GalleryMedia::create([
                'gallery_album_id' => $album->id,
                'uploaded_by' => $user->id,
                'media_type' => $mediaType,
                'file_path' => $path,
                'caption' => $request->input("captions.{$index}"),
                'file_size' => $file->getSize(),
                'display_order' => $album->media()->count(),
            ]);

            $uploadedMedia[] = $media;
        }

        // Refresh the media count
        $album->refreshMediaCount();

        // Auto-set cover image if album doesn't have one
        if (!$album->cover_image_path && count($uploadedMedia) > 0) {
            $firstImage = collect($uploadedMedia)->firstWhere('media_type', 'image');
            if ($firstImage) {
                $album->update(['cover_image_path' => $firstImage->file_path]);
            }
        }

        return $this->success($uploadedMedia, 'Media uploaded successfully', 201);
    }

    /**
     * Add an external link/video to an album
     */
    public function addLink(Request $request, $albumId)
    {
        $user = Auth::user();
        $association = $user->associations()->first();

        if (!$association) {
            return $this->error('No association found', null, 404);
        }

        $album = GalleryAlbum::where('association_id', $association->id)
            ->published()
            ->find($albumId);

        if (!$album) {
            return $this->error('Album not found', null, 404);
        }

        if (!$album->allow_member_uploads) {
            return $this->error('Member contributions are not allowed for this album', null, 403);
        }

        $validated = $request->validate([
            'external_url' => 'required|url|max:1000',
            'caption' => 'nullable|string|max:500',
        ]);

        $media = GalleryMedia::create([
            'gallery_album_id' => $album->id,
            'uploaded_by' => $user->id,
            'media_type' => 'link',
            'external_url' => $validated['external_url'],
            'caption' => $validated['caption'] ?? null,
            'display_order' => $album->media()->count(),
        ]);

        $album->refreshMediaCount();

        return $this->success($media, 'Link added successfully', 201);
    }
}
