<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Media;
use Illuminate\Support\Facades\DB;

class MediaController extends Controller
{
    private function uploadFile($file)
    {
        if (!$file || !$file->isValid()) {
            return null;
        }

        $fileName = time() . '_' . $file->getClientOriginalName();

        $file->move(
            public_path("storage/media"),
            $fileName
        );

        return url("storage/media/$fileName");
    }

    private function deleteFile($fileUrl)
    {
        if (!$fileUrl) return;

        $path = public_path(parse_url($fileUrl, PHP_URL_PATH));

        if (file_exists($path)) {
            unlink($path);
        }
    }

    public function store(Request $request)
    {
        DB::beginTransaction();

        try {
            $request->validate([
                'media_title' => 'nullable|string|max:255',
                'media_description' => 'nullable|string',
                'media_type' => 'required|in:image,video',
                'file' => 'required|file|mimes:jpg,jpeg,png,mp4,mov,avi|max:20480'
            ]);

            $fileUrl = $this->uploadFile($request->file('file'));

            $media = Media::create([
                'media_title' => $request->media_title,
                'media_description' => $request->media_description,
                'media_type' => $request->media_type,
                'file_url' => $fileUrl,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Media uploaded successfully',
                'data' => $media
            ]);

        } catch (\Exception $e) {

            DB::rollback();

            if (isset($fileUrl)) {
                $this->deleteFile($fileUrl);
            }

            return response()->json([
                'success' => false,
                'message' => 'Media upload failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function index()
    {
        DB::beginTransaction();

        try {
            $media = Media::latest()->get();

            DB::commit();

            return response()->json([
                'success' => true,
                'data' => $media
            ]);

        } catch (\Exception $e) {

            DB::rollback();

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch media',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        DB::beginTransaction();

        try {
            $media = Media::find($id);

            if (!$media) {
                return response()->json([
                    'success' => false,
                    'message' => 'Media not found'
                ], 404);
            }

            $fileUrl = $media->file_url;

            $media->delete();

            $this->deleteFile($fileUrl);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Media deleted successfully'
            ]);

        } catch (\Exception $e) {

            DB::rollback();

            return response()->json([
                'success' => false,
                'message' => 'Media deletion failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}