<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Media;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class MediaController extends Controller
{
    public function index(Request $request)
    {
        $query = Media::latest();

        if ($request->has('type') && $request->type != 'all') {
            $query->where('file_type', 'LIKE', $request->type . '/%');
        }

        if ($request->has('search')) {
            $query->where('filename', 'LIKE', '%' . $request->search . '%');
        }

        $mediaItems = $query->paginate(24);

        if ($request->ajax()) {
            $html = view('admin.media.partials.items', compact('mediaItems'))->render();
            if ($mediaItems->hasPages()) {
                $html .= '<div class="mt-12 flex justify-center ajax-pagination">' . $mediaItems->links()->render() . '</div>';
            }
            return response($html);
        }

        return view('admin.media.index', compact('mediaItems'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'files.*' => 'required|file|max:10240', // 10MB limit
        ]);

        $uploadedMedia = [];

        try {
            if ($request->hasFile('files')) {
                foreach ($request->file('files') as $file) {
                    $originalName = $file->getClientOriginalName();
                    $mimeType = $file->getMimeType();
                    $fileSize = $file->getSize();
                    
                    $filename = time() . '_' . Str::slug(pathinfo($originalName, PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
                    
                    // Move file
                    $file->move(public_path('uploads/media'), $filename);

                    $media = Media::create([
                        'filename' => $originalName,
                        'file_path' => 'uploads/media/' . $filename,
                        'file_type' => $mimeType,
                        'file_size' => $fileSize,
                        'disk' => 'public',
                    ]);

                    $uploadedMedia[] = $media;
                }
            }

            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Files uploaded successfully!',
                    'items' => $uploadedMedia,
                ]);
            }

            return redirect()->back()->with('success', 'Files uploaded successfully!');
        } catch (\Exception $e) {
            Log::error('Media Upload Error: ' . $e->getMessage());
            
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Upload failed: ' . $e->getMessage(),
                ], 500);
            }

            return redirect()->back()->with('error', 'Upload failed: ' . $e->getMessage());
        }
    }

    public function destroy(Media $media)
    {
        if (File::exists(public_path($media->file_path))) {
            File::delete(public_path($media->file_path));
        }

        $media->delete();

        if (request()->ajax()) {
            return response()->json(['success' => true]);
        }

        return redirect()->back()->with('success', 'File deleted successfully!');
    }

    public function update(Request $request, Media $media)
    {
        $validated = $request->validate([
            'alt_text' => 'nullable|string|max:255',
        ]);

        $media->update($validated);

        return response()->json(['success' => true]);
    }

    public function crop(Request $request, Media $media)
    {
        $request->validate([
            'crop_image' => 'required|image|max:5120',
        ]);

        try {
            if ($request->hasFile('crop_image')) {
                $file = $request->file('crop_image');
                
                // Keep the same path but overwrite content or generate new one?
                // Overwriting is cleaner for "Editing".
                $destinationPath = public_path($media->file_path);
                
                // If it's a relative path in DB, move it.
                if (File::exists($destinationPath)) {
                    File::delete($destinationPath);
                }

                $file->move(public_path('uploads/media'), basename($media->file_path));

                // Update size and type in case they changed
                $media->update([
                    'file_size' => File::size($destinationPath),
                    'file_type' => $file->getMimeType(),
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Image cropped successfully!',
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Media Crop Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Crop failed: ' . $e->getMessage(),
            ], 500);
        }

        return response()->json(['success' => false, 'message' => 'No image provided.'], 400);
    }
}
