<?php

namespace App\Http\Controllers;

use App\Models\FundCollection;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class FundCollectionController extends Controller
{
    /**
     * Public endpoint to get all active and completed fund collections
     */
    public function index(): JsonResponse
    {
        $funds = FundCollection::orderBy('created_at', 'desc')->get();
        return response()->json($funds);
    }

    /**
     * Public endpoint to get a specific fund collection by slug
     */
    public function show($slug): JsonResponse
    {
        $fund = FundCollection::where('slug', $slug)->firstOrFail();
        return response()->json($fund);
    }

    /**
     * Admin endpoint to get a specific fund collection by id
     */
    public function showById($id): JsonResponse
    {
        $fund = FundCollection::findOrFail($id);
        return response()->json($fund);
    }

    private function handleFileUpload($file, $prefix = 'file')
    {
        $filename = $prefix . '-' . time() . '-' . rand(1000, 9999) . '.' . $file->getClientOriginalExtension();
        
        $spaPublicPath = base_path('../public/images/funds');
        if (!is_dir($spaPublicPath)) {
            mkdir($spaPublicPath, 0775, true);
        }
        $file->move($spaPublicPath, $filename);
        
        $laravelPublicPath = public_path('images/funds');
        if (!is_dir($laravelPublicPath)) {
            mkdir($laravelPublicPath, 0775, true);
        }
        if (file_exists($spaPublicPath . '/' . $filename)) {
            copy($spaPublicPath . '/' . $filename, $laravelPublicPath . '/' . $filename);
        }

        return '/images/funds/' . $filename;
    }

    /**
     * Store a newly created fund collection.
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'status' => 'required|in:active,completed,paused',
            'bank_details' => 'nullable|string',
            'benefits' => 'nullable|string',
            'how_donations_help' => 'nullable|string',
            'cover_file' => 'nullable|file|mimes:jpeg,png,jpg,webp|max:10240',
            'gallery_files.*' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'gallery_urls' => 'nullable|array',
            'existing_gallery' => 'nullable|string',
        ]);

        $data = $request->except(['cover_file', 'gallery_files', 'gallery_urls', 'existing_gallery']);

        if ($request->hasFile('cover_file')) {
            $data['cover_image'] = $this->handleFileUpload($request->file('cover_file'), 'fund');
        }

        // Handle gallery
        $gallery = [];
        
        if ($request->has('gallery_urls') && is_array($request->gallery_urls)) {
            foreach ($request->gallery_urls as $url) {
                if (!empty($url)) {
                    $gallery[] = ['type' => 'youtube', 'url' => $url];
                }
            }
        }
        
        if ($request->hasFile('gallery_files')) {
            foreach ($request->file('gallery_files') as $gFile) {
                $path = $this->handleFileUpload($gFile, 'gallery');
                $ext = strtolower($gFile->getClientOriginalExtension());
                $type = in_array($ext, ['mp4', 'mov', 'avi']) ? 'video' : 'image';
                $gallery[] = ['type' => $type, 'url' => $path];
            }
        }
        $data['gallery'] = $gallery;

        $fund = FundCollection::create($data);

        return response()->json([
            'status' => 'success',
            'message' => 'Fund collection created successfully',
            'fund' => $fund
        ]);
    }

    /**
     * Update the specified fund collection.
     */
    public function update(Request $request, FundCollection $fund): JsonResponse
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'status' => 'required|in:active,completed,paused',
            'bank_details' => 'nullable|string',
            'benefits' => 'nullable|string',
            'how_donations_help' => 'nullable|string',
            'cover_file' => 'nullable|file|mimes:jpeg,png,jpg,webp|max:10240',
            'gallery_files.*' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'gallery_urls' => 'nullable|array',
            'existing_gallery' => 'nullable|string',
        ]);

        $data = $request->except(['cover_file', 'gallery_files', 'gallery_urls', 'existing_gallery']);

        if ($request->hasFile('cover_file')) {
            $data['cover_image'] = $this->handleFileUpload($request->file('cover_file'), 'fund');
        }

        // Handle gallery updates
        $gallery = [];
        if ($request->has('existing_gallery')) {
            $existing = json_decode($request->existing_gallery, true);
            if (is_array($existing)) {
                $gallery = $existing;
            }
        }

        if ($request->has('gallery_urls') && is_array($request->gallery_urls)) {
            foreach ($request->gallery_urls as $url) {
                if (!empty($url)) {
                    $gallery[] = ['type' => 'youtube', 'url' => $url];
                }
            }
        }
        
        if ($request->hasFile('gallery_files')) {
            foreach ($request->file('gallery_files') as $gFile) {
                $path = $this->handleFileUpload($gFile, 'gallery');
                $ext = strtolower($gFile->getClientOriginalExtension());
                $type = in_array($ext, ['mp4', 'mov', 'avi']) ? 'video' : 'image';
                $gallery[] = ['type' => $type, 'url' => $path];
            }
        }
        $data['gallery'] = $gallery;

        $fund->update($data);

        return response()->json([
            'status' => 'success',
            'message' => 'Fund collection updated successfully',
            'fund' => $fund
        ]);
    }

    /**
     * Remove the specified fund collection.
     */
    public function destroy(FundCollection $fund): JsonResponse
    {
        $fund->delete();
        return response()->json(['status' => 'success', 'message' => 'Fund collection deleted successfully']);
    }
}
