<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Asset;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;

class AssetController extends Controller
{
    // 1. Dashboard View
    public function index(Request $request)
    {
        $categories = Category::where('status', 1)->get();
        
        if (Auth::user()->role === 'super_admin') {
            $query = Asset::with(['category', 'user'])->latest();
        } else {
            $query = Asset::with('category')->where('user_id', Auth::id())->latest();
        }

        if ($request->filled('search')) $query->where('title', 'like', '%' . $request->search . '%');
        if ($request->filled('category_id')) $query->where('category_id', $request->category_id);
        if ($request->filled('file_type')) $query->where('file_type', $request->file_type);

        $assets = $query->paginate(10)->withQueryString();
        return view('admin.assets', compact('assets', 'categories'));
    }

    // 2. GENERATE VIP LINK (Pre-signed URL for Direct Cloudflare Upload)
   public function getPresignedUrl(Request $request)
    {
        $request->validate([
            'filename' => 'required|string',
            'contentType' => 'required|string',
        ]);

        $fileName = time() . '_' . preg_replace('/[^A-Za-z0-9.\-]/', '', $request->filename);
        $path = 'media/' . $fileName;

        try {
            // 👇 Humne VS Code ko bataya ki ye S3 adapter hai
            /** @var \Illuminate\Filesystem\FilesystemAdapter $disk */
            $disk = Storage::disk('r2');
            
            // S3 driver ke liye getClient() seedha disk par available hota hai
            $client = $disk->getClient();
            
            $command = $client->getCommand('PutObject', [
                'Bucket' => env('CLOUDFLARE_R2_BUCKET'),
                'Key' => $path,
                'ContentType' => $request->contentType,
            ]);

            // VIP Link generate kiya (Pre-signed URL)
            $presignedRequest = $client->createPresignedRequest($command, '+60 minutes');

            return response()->json([
                'upload_url' => (string) $presignedRequest->getUri(),
                'path' => $path,
                'public_url' => rtrim(env('CLOUDFLARE_R2_URL'), '/') . '/' . $path
            ]);
        } catch (\Exception $e) {
            // Agar koi error aaye toh console mein dikhega
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    // 3. SAVE DATA TO DB (After Direct Upload is Complete)
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'file_path' => 'required|string',
            'file_url' => 'required|url',
            'file_type' => 'required|string',
            'file_size' => 'required|string',
        ]);

        try {
            Asset::create([
                'title' => $request->title,
                'category_id' => $request->category_id,
                'user_id' => Auth::id(),
                'file_type' => $request->file_type,
                'file_url' => $request->file_url,
                'file_size' => $request->file_size,
                'file_path' => $request->file_path,
            ]);

            return response()->json(['success' => true, 'message' => 'Asset details saved successfully!']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Database save failed: ' . $e->getMessage()], 500);
        }
    }

    // 4. Edit Asset Details
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
        ]);

        try {
            $asset = Asset::findOrFail($id);

            if (Auth::user()->role !== 'super_admin' && $asset->user_id !== Auth::id()) {
                return back()->with('error', 'Security Alert: You can only edit your own uploads!');
            }

            $asset->update([
                'title' => $request->title,
                'category_id' => $request->category_id,
            ]);

            return back()->with('success', 'Asset details updated successfully.');
        } catch (\Exception $e) {
            return back()->with('error', 'Update failed: ' . $e->getMessage());
        }
    }

    // 5. Delete from Cloudflare R2
    public function destroy($id)
    {
        try {
            $asset = Asset::findOrFail($id);

            if (Auth::user()->role !== 'super_admin' && $asset->user_id !== Auth::id()) {
                return back()->with('error', 'Security Alert: You can only delete your own uploads!');
            }
            
            if ($asset->file_path) {
                Storage::disk('r2')->delete($asset->file_path);
            }
            
            $asset->delete();
            return back()->with('success', 'Asset permanently deleted.');
        } catch (\Exception $e) {
            return back()->with('error', 'Deletion failed: ' . $e->getMessage());
        }
    }
}