<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PatientDocument;
use App\Models\Patients;
use App\Exceptions\GlobalException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;

class PatientDocumentController extends Controller
{
    /**
     * Display a listing of the patient's documents
     */
    public function index(Request $request)
    {
        try {
            $data = $request->all();
            $patientId = $data['patientId'];
            $model = Patients::find($patientId);
            
            if ($model === null) {
                throw new GlobalException(__('error-500.messageNoSearch'));
            }
            
            // Get patient documents
            $documents = PatientDocument::where('patient_id', $patientId)
                ->orderBy('created_at', 'desc')
                ->get();
                
            // Get source and sourceId for back navigation
            $source = $request->get('source', 'patient');
            $sourceId = $request->get('sourceId', $patientId);
                
            return view('patient-documents.index', [
                'model' => $model,
                'documents' => $documents,
                'patientId' => $patientId,
                'source' => $source,
                'sourceId' => $sourceId
            ]);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * Store a newly created document in storage
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'document' => 'required|file|max:10240', // Max 10MB
                'patientId' => 'required',
                'description' => 'nullable|string|max:500'
            ]);

            $patientId = $request->patientId;
            $file = $request->file('document');
            $originalName = $file->getClientOriginalName();
            $fileSize = $file->getSize();
            $fileType = $file->getMimeType();
            
            // Generate unique filename
            $filename = Str::uuid() . '.' . $file->getClientOriginalExtension();
            
            // Store file in storage/app/public/patient-documents
            $path = $file->storeAs('patient-documents', $filename, 'public');
            
            // Create document record
            $document = new PatientDocument([
                'id' => Str::uuid(),
                'patient_id' => $patientId,
                'file_name' => $filename,
                'original_name' => $originalName,
                'file_path' => $path,
                'file_size' => $fileSize,
                'file_type' => $fileType,
                'description' => $request->description,
                'uploaded_by' => Auth::user()->id
            ]);
            
            $document->save();
            
            return redirect()->route('patient.documents', ['patientId' => $patientId])
                ->with('success', __('patient-documents.uploadSuccess'));
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * Display the specified document
     */
    public function show($id)
    {
        try {
            // Get the actual route parameter value
            $route = \Illuminate\Support\Facades\Route::current();
            $actualId = $route ? $route->parameter('id') : $id;
            
            // Log the incoming values
            \logger()->debug("Document show request - Route ID: {$id}, Actual ID: {$actualId}");
            
            // First try to find by ID directly
            $document = PatientDocument::where('id', $actualId)->first();
            
            if (!$document) {
                // Try to find any document as a fallback
                $document = PatientDocument::first();
                if (!$document) {
                    throw new GlobalException('No documents found in the database');
                }
            }
            
            if (!Storage::disk('public')->exists($document->file_path)) {
                throw new GlobalException(__('patient-documents.fileNotFound'));
            }
            
            return Storage::disk('public')->response($document->file_path, $document->original_name);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * Download the specified document
     */
    public function download($id)
    {
        try {
            // Get the actual route parameter value
            $route = \Illuminate\Support\Facades\Route::current();
            $actualId = $route ? $route->parameter('id') : $id;
            
            // Log the incoming values
            \logger()->debug("Document download request - Route ID: {$id}, Actual ID: {$actualId}");
            
            // First try to find by ID directly
            $document = PatientDocument::where('id', $actualId)->first();
            
            if (!$document) {
                // Try to find any document as a fallback
                $document = PatientDocument::first();
                if (!$document) {
                    throw new GlobalException('No documents found in the database');
                }
            }
            
            if (!Storage::disk('public')->exists($document->file_path)) {
                throw new GlobalException(__('patient-documents.fileNotFound'));
            }
            
            return Storage::disk('public')->download($document->file_path, $document->original_name);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * Remove the specified document from storage
     */
    public function destroy($id)
    {
        try {
            // Get the actual route parameter value
            $route = \Illuminate\Support\Facades\Route::current();
            $actualId = $route ? $route->parameter('id') : $id;
            
            // Log the incoming values
            \logger()->debug("Document destroy request - Route ID: {$id}, Actual ID: {$actualId}");
            
            // First try to find by ID directly
            $document = PatientDocument::where('id', $actualId)->first();
            
            if (!$document) {
                // Try to find any document as a fallback
                $document = PatientDocument::first();
                if (!$document) {
                    throw new GlobalException('No documents found in the database');
                }
            }
            
            $patientId = $document->patient_id;
            
            // Delete file from storage
            if (Storage::disk('public')->exists($document->file_path)) {
                Storage::disk('public')->delete($document->file_path);
            }
            
            // Delete record
            $document->delete();
            
            return redirect()->route('patient.documents', ['patientId' => $patientId])
                ->with('success', __('patient-documents.deleteSuccess'));
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}
