<?php

namespace App\Http\Controllers;

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

class ProjectController extends Controller
{
    /**
     * Display a listing of the active projects.
     */
    public function index(): JsonResponse
    {
        $projects = Project::orderBy('created_at', 'desc')->get();
        return response()->json($projects);
    }

    /**
     * Display a specific project.
     */
    public function show($id): JsonResponse
    {
        $project = Project::findOrFail($id);
        return response()->json($project);
    }

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

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

    /**
     * Store a newly created project in storage.
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'location' => 'nullable|string|max:255',
            'directed_by' => 'nullable|string|max:255',
            'total_fund_raised' => 'nullable|numeric|min:0',
            'media_type' => 'required|in:youtube,upload',
            'media_url' => 'nullable|string',
            'media_file' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'thumbnail_file' => 'nullable|file|mimes:jpeg,png,jpg,webp|max:10240',
            'pdf_file' => 'nullable|file|mimes:pdf|max:20480',
            'gallery_files.*' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'gallery_urls' => 'nullable|array',
            'impact_reports' => 'nullable|array',
        ]);

        $data = $request->except(['media_file', 'thumbnail_file', 'pdf_file', 'gallery_files', 'gallery_urls']);

        // Handle main media
        if ($request->media_type === 'upload' && $request->hasFile('media_file')) {
            $data['media_url'] = $this->handleFileUpload($request->file('media_file'), 'project');
        }

        // Handle thumbnail
        if ($request->hasFile('thumbnail_file')) {
            $data['thumbnail_url'] = $this->handleFileUpload($request->file('thumbnail_file'), 'thumb');
        }

        // Handle PDF
        if ($request->hasFile('pdf_file')) {
            $data['pdf_url'] = $this->handleFileUpload($request->file('pdf_file'), 'doc');
        }

        // 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');
                // Determine if it's an image or video based on extension
                $ext = strtolower($gFile->getClientOriginalExtension());
                $type = in_array($ext, ['mp4', 'mov', 'avi']) ? 'video' : 'image';
                $gallery[] = ['type' => $type, 'url' => $path];
            }
        }
        $data['gallery'] = $gallery;

        $project = Project::create($data);

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

    /**
     * Update the specified project in storage.
     */
    public function update(Request $request, Project $project): JsonResponse
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'location' => 'nullable|string|max:255',
            'directed_by' => 'nullable|string|max:255',
            'total_fund_raised' => 'nullable|numeric|min:0',
            'media_type' => 'required|in:youtube,upload',
            'media_url' => 'nullable|string',
            'media_file' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'thumbnail_file' => 'nullable|file|mimes:jpeg,png,jpg,webp|max:10240',
            'pdf_file' => 'nullable|file|mimes:pdf|max:20480',
            'gallery_files.*' => 'nullable|file|mimes:jpeg,png,jpg,webp,mp4,mov,avi|max:51200',
            'gallery_urls' => 'nullable|array',
            'impact_reports' => 'nullable|array',
            'existing_gallery' => 'nullable|string', // JSON string of retained gallery items
        ]);

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

        if ($request->media_type === 'upload' && $request->hasFile('media_file')) {
            $data['media_url'] = $this->handleFileUpload($request->file('media_file'), 'project');
        }

        if ($request->hasFile('thumbnail_file')) {
            $data['thumbnail_url'] = $this->handleFileUpload($request->file('thumbnail_file'), 'thumb');
        }

        if ($request->hasFile('pdf_file')) {
            $data['pdf_url'] = $this->handleFileUpload($request->file('pdf_file'), 'doc');
        }

        // 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;

        $project->update($data);

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

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