<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Document;
use App\Models\LegalCase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class DocumentController extends Controller
{
    public function store(Request $request, $caseId)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'document' => 'required|file|mimes:pdf,doc,docx,jpg,png|max:10240', // 10MB limit
        ]);

        // This correctly gets the file from the 'document' input
        $file = $request->file('document');

        if (!$file) {
            return back()->with('error', 'File upload failed. Please try again.');
        }

        // 1. Store the file using the variable we just defined
        // We save it to 'documents/cases' on the 'local' (private) disk
        $path = $file->store('documents/cases', 'local');

        // 2. Save info to Database
        Document::create([
            'legal_case_id' => $caseId,
            'user_id' => auth()->id(), // Ensure this matches your migration (uploader_id vs user_id)
            'title' => $request->title,
            'file_path' => $path, // No need for str_replace if saving directly to local
            'file_type' => $file->getClientOriginalExtension(),
            'file_size' => $file->getSize() / 1024, // KB
        ]);

        return back()->with('success', 'Document uploaded successfully.');
    }
    public function preview(Document $document)
    {
        // 1. Check if the file exists on the 'local' (private) disk
        // If your DB path is "documents/cases/xyz.pdf"
        if (!Storage::disk('local')->exists($document->file_path)) {
            \Log::error("File missing for preview: " . $document->file_path);
            abort(404, 'The requested document does not exist.');
        }

        // 2. Get the full system path
        // This converts the relative path to: /home/user/project/storage/app/documents/cases/xyz.pdf
        $path = Storage::disk('local')->path($document->file_path);

        // 3. Detect the MIME type (Safe check for browser rendering)
        $mimeType = Storage::disk('local')->mimeType($document->file_path);

        // 4. Return the file for inline viewing
        return response()->file($path, [
            'Content-Type' => $mimeType,
            'Content-Disposition' => 'inline; filename="' . $document->title . '"'
        ]);
    }

    public function download(Document $document)
    {
        // $document->file_path should just be "documents/cases/xyz.pdf"
        if (!Storage::disk('local')->exists($document->file_path)) {
            abort(404);
        }
        return Storage::disk('local')->download($document->file_path);
    }

    // List all documents (Global View)

    public function index()
    {
        $cases = LegalCase::with(['documents', 'evidence', 'recordings', 'client'])
            ->whereHas('documents')
            ->orWhereHas('evidence')
            ->orWhereHas('recordings') // Add this
            ->latest()
            ->paginate(10);

        return view('admin.documents.index', compact('cases'));
    }
}
