<?php

namespace App\Http\Controllers\Labs;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\HcpEducation;
use App\Models\HcpLicense;
use App\Models\Hcp;
use App\Models\Device;
use App\Models\Lab;
use App\Models\Patient;
use App\Models\Labtest;
use App\Models\Lablogin;
use App\Models\NearLab;
use App\Models\LabReport;
use App\Models\Labnotification; 

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Crypt;
 use Barryvdh\DomPDF\Facade\Pdf;
class labsController extends Controller
{

   public function login(){
    return view('labs.login');
   } 
   
   
     public function register(){
    return view('labs.register');
   } 
        public function dashboard(){
    return view('labs.index');
   } 
   
     public function addReport($id = null){
     
     
        $existingRecord = $id ? Lab::find($id) : null;
   $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_id) : null;
    $patient = $existingRecord ? Patient::find($existingRecord->patient_id) : null;
   
   
      $data = [
    'reason_for_blood_work' => $existingRecord ? $existingRecord->reason_for_blood_work : null,
   

    'other_reason' => $existingRecord ? $existingRecord->other_reason : null,
    'basic_panel' => $existingRecord ? $existingRecord->basic_panel : null,
    'thyroid_tests' => $existingRecord ? $existingRecord->thyroid_tests : null,
    'basic_panel_options' => $existingRecord ? $existingRecord->basic_panel_options  : null,
    'specialty_tests' => $existingRecord ? $existingRecord->specialty_tests : null,
    'cardiac_tests' => $existingRecord ? $existingRecord->cardiac_tests : null,
    'inflammatory_tests' => $existingRecord ? $existingRecord->inflammatory_tests : null,  
    'hormone_tests' => $existingRecord ? $existingRecord->hormone_tests  : null,
    'hcp' => $hcpData ?? [],
    'labsdata' => $existingRecord ?? null,
    'existingRecord' => $existingRecord ?? null, 
    'patient' => $patient,
    'lab_id' => $id,


];
       return view('labs.addreport', $data);
        
   } 
   
        public function viewReport($id = null) {
    $LabReport = LabReport::with('labLogin')->firstOrNew(['lab_id' => $id]);

    
    $existingRecord = $id ? Lab::find($LabReport->lab_id ?? null) : null;
    $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_id) : null;
    $patient = $existingRecord ? Patient::find($existingRecord->patient_id) : null;

    // Get the full image URL dynamically
    $reportUrl = $LabReport && $LabReport->report ? asset('storage/uploads/labsreport/' . basename($LabReport->report)) : null;

    $data = [
        'reason_for_blood_work' => $existingRecord ? json_decode($existingRecord->reason_for_blood_work, true) : null,
        'other_reason' => $existingRecord ? $existingRecord->other_reason : null,
        'basic_panel' => $existingRecord ? json_decode($existingRecord->basic_panel, true) : null,
        'thyroid_tests' => $existingRecord ? json_decode($existingRecord->thyroid_tests, true) : null,
        'basic_panel_options' => $existingRecord ? json_decode($existingRecord->basic_panel_options, true) : null,
        'specialty_tests' => $existingRecord ? json_decode($existingRecord->specialty_tests, true) : null,
        'cardiac_tests' => $existingRecord ? json_decode($existingRecord->cardiac_tests, true) : null,
        'inflammatory_tests' => $existingRecord ? json_decode($existingRecord->inflammatory_tests, true) : null,
        'hormone_tests' => $existingRecord ? json_decode($existingRecord->hormone_tests, true) : null,
        'hcp' => $hcpData ?? [],
        'labsdata' => $existingRecord ?? null,
        'existingRecord' => $existingRecord ?? null,
        'patient' => $patient,
        'lab_id' => $id,
        'reportUrl' => $reportUrl, // Add the full image URL
        'test_results' =>  $LabReport, 
        'labDetails' => $LabReport->labLogin,
    ];
    $data['test_results']['complete_blood_count'] = isset($data['test_results']['complete_blood_count'])
    ? json_decode($data['test_results']['complete_blood_count'], true)
    : [];

    $data['test_results']['lipid_profile'] = isset($data['test_results']['lipid_profile'])
    ? json_decode($data['test_results']['lipid_profile'], true)
    : [];

    $data['test_results']['preoperative'] = isset($data['test_results']['preoperative'])
    ? json_decode($data['test_results']['preoperative'], true)
    : [];

    $data['test_results']['acute_illness'] = isset($data['test_results']['acute_illness'])
    ? json_decode($data['test_results']['acute_illness'], true)
    : [];

dd($data['test_results']['complete_blood_count']); // Debugging
    return view('labs.viewreport', $data);
}

   
   
   
public function create(Request $request)
{ 
    try {
        // Validate input data
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'nullable|string|max:255', 
            'lab_name' => 'nullable|string|max:255',
            'date_of_birth' => 'required|date',
            'sex' => 'required|in:Male,Female,Other',
            'address' => 'required|string|max:500',
            'patient_phone_num_country_code' => 'required|string|max:5',
            'patient_phone_number' => 'required|string|max:15|unique:labslogin,phone',
            'aadhar_card_num' => 'required|string|min:4|max:4',
            'email' => 'required|email|unique:labslogin,email',
            'password' => 'required|min:6',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg',
            'cin' => 'required|string|max:21|unique:labslogin,cin', // CIN validation
            'gstin' => 'required|string|max:15|unique:labslogin,gstin', // GSTIN validation
            'pan_card' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg', // PAN Card upload validation
            'signature' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg', // PAN Card upload validation
            
        ]);

        // Handle profile photo upload
        if ($request->hasFile('photo')) {
            $file = $request->file('photo');
            $fileName = time() . '_' . $file->getClientOriginalName(); 
            $file->storeAs('uploads/labs', $fileName, 'public');
            $validated['photo'] = $fileName;
        }

        // Handle PAN Card upload
        if ($request->hasFile('pan_card')) {
            $panFile = $request->file('pan_card');
            $panFileName = time() . '_PAN_' . $panFile->getClientOriginalName();
            $panFile->storeAs('uploads/labs', $panFileName, 'public');
            $validated['pan_card'] = $panFileName;
        }
        if ($request->hasFile('signature')) {
            $panFile = $request->file('signature');
            $panFileName = time() . '_signature_' . $panFile->getClientOriginalName();
            $panFile->storeAs('uploads/labs', $panFileName, 'public');
            $validated['signature'] = $panFileName;
        } 
 

        
        // Encrypt password before storing
        $validated['password'] = bcrypt($validated['password']);

        // Concatenate country code and phone number
        $validated['phone'] = $validated['patient_phone_num_country_code'] . $validated['patient_phone_number'];
        unset($validated['patient_phone_num_country_code'], $validated['patient_phone_number']);

        // Create the lab record in the database
        $lab = Lablogin::create($validated);  

        Log::info('Lab created successfully!', ['data' => $lab]);

        return response()->json([
            'message' => 'Lab created successfully!',  
            'data' => $lab
        ], 201);

    } catch (\Throwable $e) {
        Log::error('Error while creating Lab.', [
            'error' => $e->getMessage(),
            'request_data' => $request->all()
        ]);

        return response()->json([
            'message' => 'Something went wrong while creating the lab.',
            'error' => $e->getMessage()
        ], 500);
    }
}
 
   
   
public function signin(Request $request)
{
    try {
        // Validate input
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);

        // Attempt login with 'lab' guard
        if (Auth::guard('lab')->attempt($credentials)) {
            $user = Auth::guard('lab')->user();

            return response()->json([
                'message' => 'Login successful!',
                'user' => $user, // Return user data (without token)
            ], 200);
        }

        return response()->json(['error' => 'Invalid email or password.'], 401);

    } catch (\Throwable $e) {
        return response()->json([
            'message' => 'Something went wrong during login.',
            'error' => $e->getMessage()
        ], 500);
    }
}   
    
  public function logout(Request $request)

    { 
        Auth::guard('lab')->logout(); 
        session()->invalidate();
        session()->regenerateToken();
        return redirect('/labs/login');    

    }
 
       public function labTest(Request $request)
{

     return view('labs.lab_test');
} 
   
public function labTestShow(Request $request)
{
    if ($request->ajax()) {
    
        $lab_data = Auth::guard('lab')->user();
  
        $labTests = Labtest::where('lablogin_id', $lab_data->id)
        ->with(['patient', 'lablogin', 'lab', 'labReport']) 
          ->get();

     
        return DataTables::of($labTests)
            ->addColumn('first_name', function ($labTest) {
       
                return $labTest->patient ? $labTest->patient->first_name : 'N/A';
            })
            ->addColumn('address', function ($labTest) {
                // Access the related patient model and display address
                return $labTest->patient ? $labTest->patient->address : 'N/A';
            })
            ->addColumn('date_of_birth', function ($labTest) {
                // Access the related patient model and display date_of_birth
                return $labTest->patient ? $labTest->patient->date_of_birth : 'N/A';
            })
            ->addColumn('sex', function ($labTest) {
                // Access the related patient model and display sex
                return $labTest->patient ? $labTest->patient->sex : 'N/A';
            })
            ->addColumn('patient_phone_number', function ($labTest) {
                // Access the related patient model and display phone number
                return $labTest->patient ? $labTest->patient->patient_phone_number : 'N/A';
            })
            ->addColumn('lablogin_name', function ($labTest) {
                // Access the related lablogin model and display lablogin name (or any relevant field)
                return $labTest->lablogin ? $labTest->lablogin->name : 'N/A'; // Assuming 'name' field in Lablogin model
            })
            ->addColumn('lab_name', function ($labTest) {
                // Access the related lab model and display lab name
                return $labTest->tab ? $labTest->tab->name : 'N/A'; // Assuming 'name' field in Lab model
            })
            ->addColumn('lablogin_id', function ($labTest) {
                // Return the lablogin_id
                return $labTest->lablogin_id;
            })
            ->addColumn('lab_id', function ($labTest) {
                // Return the lab_id
                return $labTest->lab_id;
            })
            ->addColumn('actions', function ($labTest) {
                // Add action buttons for each labTest record
                $buttons = '<button data-id="' . $labTest->lab_id . '" class="btn btn-sm btn-info viewLabTest">View</button>';
                $buttons .= '<a href="javascript:void(0)" onclick="printLabPage(' . $labTest->lab_id . ')" class="btn btn-sm btn-danger">Print</a>';
                $checkReport = LabReport::where("lab_id", $labTest->lab_id)->exists();

                // Check if LabReport exists and display appropriate button
                if ($checkReport) {
                    $buttons .= '<a href="' . url('labs/viewreport/' . $labTest->lab_id) . '" class="btn btn-sm btn-success">View Report</a>';
                } else {
                    $buttons .= '<a href="' . url('labs/addreport/' . $labTest->lab_id) . '" class="btn btn-sm btn-primary">Add Report</a>';
                }
 
                return $buttons;
            })
            ->rawColumns(['actions'])
            ->make(true);
    }
}



public function getNotifications()
{
    try {
    
        $lab = Auth::guard('lab')->user();
        if (!$lab) {

            Log::error('Labs not found while retrieving notifications.');
            return response()->json(['success' => false, 'message' => 'Labs not found!'], 404);
        }

        $notifications = Labnotification::where('lablogin_id', $lab->id)
            ->orderBy('created_at', 'desc')
            ->limit(10)  
            ->get();
        Log::info('Notifications retrieved successfully for patient.', [
            'lab_id' => $lab->id,
            'notifications_count' => $notifications->count(),
        ]);
        return response()->json(['notifications' => $notifications]);

    } catch (\Exception $e) {

        Log::error('Error retrieving notifications for patient.', [
            'error' => $e->getMessage(),
            'lab_id' => isset($lab) ? $lab->id : 'N/A'
        ]); 
        return response()->json([
            'success' => false,
            'message' => 'Error retrieving notifications.',
            'error' => $e->getMessage()
        ], 500);
    }
}


public function clearNotifications(Request $request)
{
    try {

        $lab = Auth::guard('lab')->user();
        if (!$lab) {

 
            Log::error('Lab not found while attempting to clear notifications.');
            return response()->json(['success' => false, 'message' => 'Lab not found!'], 404);
        }

        $deletedCount = Labnotification::where('lablogin_id', $lab->id)->delete();

        Log::info('Notifications cleared successfully for lab.', [
            'patient_id' => $lab->id,
            'deleted_count' => $deletedCount
        ]);

        return response()->json(['success' => true, 'message' => 'Notifications cleared successfully!']);

    } catch (\Exception $e) {
     
        Log::error('Error clearing notifications for patient.', [
            'error' => $e->getMessage(),
            'lab_id' => isset($lab) ? $lab->id : 'N/A',
            'request_data' => $request->all()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'Error clearing notifications.',
            'error' => $e->getMessage()
        ], 500);
    }
}

 
public function getLabTest($id)
{
    $labTest = Lab::with(['patient', 'hcp'])->find($id);

    if (!$labTest) {
        return response()->json(['error' => 'Lab Test not found'], 404);
    }

    return response()->json([
        'reason_for_blood_work' => $labTest->reason_for_blood_work ? json_decode($labTest->reason_for_blood_work, true) : null,
        'other_reason' => $labTest->other_reason,
        'basic_panel' => $labTest->basic_panel ? json_decode($labTest->basic_panel, true) : null,
        'thyroid_tests' => $labTest->thyroid_tests ? json_decode($labTest->thyroid_tests, true) : null,
        'basic_panel_options' => $labTest->basic_panel_options ? json_decode($labTest->basic_panel_options, true) : null,
        'specialty_tests' => $labTest->specialty_tests ? json_decode($labTest->specialty_tests, true) : null,
        'cardiac_tests' => $labTest->cardiac_tests ? json_decode($labTest->cardiac_tests, true) : null,
        'inflammatory_tests' => $labTest->inflammatory_tests ? json_decode($labTest->inflammatory_tests, true) : null,  
        'hormone_tests' => $labTest->hormone_tests ? json_decode($labTest->hormone_tests , true) : null,
        'hcp' => $labTest->hcp ?? [],
        'labsdata' => $labTest,
        'existingRecord' => $labTest, 
        'labid' => $labTest->id,
    ]);
}

public function reportPrint($id = null)
{

    $LabReport = LabReport::with('labLogin')->firstOrNew(['lab_id' => $id]);

    $existingRecord = $id ? Lab::find($LabReport->lab_id ?? null) : null;
    $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_id) : null;
    $patient = $existingRecord ? Patient::find($existingRecord->patient_id) : null;
    
    $data = [
 
        'test_results' =>  $LabReport, 
        'hcp' => $hcpData ?? [],
        'patient' => $patient,
        'labDetails' => $LabReport->labLogin,
    ]; 
    $data['test_results']['complete_blood_count'] = isset($data['test_results']['complete_blood_count'])
    ? json_decode($data['test_results']['complete_blood_count'], true)
    : [];

    $data['test_results']['lipid_profile'] = isset($data['test_results']['lipid_profile'])
    ? json_decode($data['test_results']['lipid_profile'], true)
    : [];

    $data['test_results']['preoperative'] = isset($data['test_results']['preoperative'])
    ? json_decode($data['test_results']['preoperative'], true)
    : [];

    $data['test_results']['acute_illness'] = isset($data['test_results']['acute_illness'])
    ? json_decode($data['test_results']['acute_illness'], true)
    : [];

     
    $pdf = Pdf::loadView('labs.lab_report_print', $data);
 
    return response($pdf->stream('labreportprint.pdf'), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="labprint.pdf"',
    ]);  

}

public function labsPrint($id = null)
{

 
   $existingRecord = $id ? Lab::find($id) : null;
   $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_id) : null;
    $patient = $existingRecord ? Patient::find($existingRecord->patient_id) : null;
   
   
      $data = [
    'reason_for_blood_work' => $existingRecord ? json_decode($existingRecord->reason_for_blood_work, true) : null,
   

    'other_reason' => $existingRecord ? $existingRecord->other_reason : null,
    'basic_panel' => $existingRecord ? json_decode($existingRecord->basic_panel, true) : null,
    'thyroid_tests' => $existingRecord ? json_decode($existingRecord->thyroid_tests, true) : null,
    'basic_panel_options' => $existingRecord ? json_decode($existingRecord->basic_panel_options, true)  : null,
    'specialty_tests' => $existingRecord ? json_decode($existingRecord->specialty_tests, true) : null,
    'cardiac_tests' => $existingRecord ? json_decode($existingRecord->cardiac_tests, true) : null,
    'inflammatory_tests' => $existingRecord ? json_decode($existingRecord->inflammatory_tests, true) : null,  
    'hormone_tests' => $existingRecord ? json_decode($existingRecord->hormone_tests , true) : null,
    'hcp' => $hcpData ?? [],
    'labsdata' => $existingRecord ?? null,
    'existingRecord' => $existingRecord ?? null, 
    'patient' => $patient,


];

    
    $pdf = Pdf::loadView('labs.labprint', $data);
 
    return response($pdf->stream('labprint.pdf'), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="labprint.pdf"',
    ]);  
 
}




public function reportStore(Request $request)
{

   // dd($request);
    try {
        $lab = Auth::guard('lab')->user();
        $data = $request->validate([
            'report' => 'nullable|mimes:jpeg,png,jpg,gif,pdf,svg|max:10240', // 10MB
            'lab_id' => 'required|exists:lab,id',
        ]);
           

        // Initialize result structure 
        $complete_blood_countData = [];
        $lipidData = [];
        $preoperativeData = [];
        $acute_illnessData = [];
        $screeningData = [];
        $medicationmonitoringData = [];
        $cardiacmarkersData = [];
        $inflammatorymarkersData = [];
        $hormonalstudiesData = [];
        $infectiousdiseasescreeningData = [];
        $genetictestingData = [];
        $drugscreeningData = [];
        $cbcData = [];
        $bmpData = [];
        $cmpData = [];
        $lipidpanelData = [];
        $thyroidfunctiontestsData = [];
        $glucoseData = [];
        $urinalysisData = []; 


        // Fetching Dynamic Complete Blood Count (CBC) Data
        if ($request->has('complete_blood_count')) {
            foreach ($request->complete_blood_count as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $complete_blood_countData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->complete_blood_count["result_{$key}"] ?? '',
                        'normal_range' => $request->complete_blood_count["normal_range_{$key}"] ?? '',
                        'units' => $request->complete_blood_count["units_{$key}"] ?? '',
                        'remarks' => $request->complete_blood_count["remarks_{$key}"] ?? ''
                    ];
                }
            }
        }

        if ($request->has('lipid_profile')) {
            foreach ($request->lipid_profile as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $lipidData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->lipid_profile["result_{$key}"] ?? '',
                        'normal_range' => $request->lipid_profile["normal_range_{$key}"] ?? '',
                        'units' => $request->lipid_profile["units_{$key}"] ?? '',
                        'remarks' => $request->lipid_profile["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('preoperative')) {
            foreach ($request->preoperative as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $preoperativeData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->preoperative["result_{$key}"] ?? '',
                        'normal_range' => $request->preoperative["normal_range_{$key}"] ?? '',
                        'units' => $request->preoperative["units_{$key}"] ?? '',
                        'remarks' => $request->preoperative["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('acute_illness')) {
            foreach ($request->acute_illness as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $acute_illnessData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->acute_illness["result_{$key}"] ?? '',
                        'normal_range' => $request->acute_illness["normal_range_{$key}"] ?? '',
                        'units' => $request->acute_illness["units_{$key}"] ?? '',
                        'remarks' => $request->acute_illness["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('screening')) {
            foreach ($request->screening as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $screeningData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->screening["result_{$key}"] ?? '',
                        'normal_range' => $request->screening["normal_range_{$key}"] ?? '',
                        'units' => $request->screening["units_{$key}"] ?? '',
                        'remarks' => $request->screening["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        
        if ($request->has('medicationmonitoring')) {
            foreach ($request->medicationmonitoring as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $medicationmonitoringData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->medicationmonitoring["result_{$key}"] ?? '',
                        'normal_range' => $request->medicationmonitoring["normal_range_{$key}"] ?? '',
                        'units' => $request->medicationmonitoring["units_{$key}"] ?? '',
                        'remarks' => $request->medicationmonitoring["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('cardiacmarkers')) {
            foreach ($request->cardiacmarkers as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $cardiacmarkersData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->cardiacmarkers["result_{$key}"] ?? '',
                        'normal_range' => $request->cardiacmarkers["normal_range_{$key}"] ?? '',
                        'units' => $request->cardiacmarkers["units_{$key}"] ?? '',
                        'remarks' => $request->cardiacmarkers["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('inflammatorymarkers')) {
            foreach ($request->inflammatorymarkers as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $inflammatorymarkersData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->inflammatorymarkers["result_{$key}"] ?? '',
                        'normal_range' => $request->inflammatorymarkers["normal_range_{$key}"] ?? '',
                        'units' => $request->inflammatorymarkers["units_{$key}"] ?? '',
                        'remarks' => $request->inflammatorymarkers["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('hormonalstudies')) {
            foreach ($request->hormonalstudies as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $hormonalstudiesData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->hormonalstudies["result_{$key}"] ?? '',
                        'normal_range' => $request->hormonalstudies["normal_range_{$key}"] ?? '',
                        'units' => $request->hormonalstudies["units_{$key}"] ?? '',
                        'remarks' => $request->hormonalstudies["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('infectiousdiseasescreening')) {
            foreach ($request->infectiousdiseasescreening as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $infectiousdiseasescreeningData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->infectiousdiseasescreening["result_{$key}"] ?? '',
                        'normal_range' => $request->infectiousdiseasescreening["normal_range_{$key}"] ?? '',
                        'units' => $request->infectiousdiseasescreening["units_{$key}"] ?? '',
                        'remarks' => $request->infectiousdiseasescreening["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('genetictesting')) {
            foreach ($request->genetictesting as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $genetictestingData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->genetictesting["result_{$key}"] ?? '',
                        'normal_range' => $request->genetictesting["normal_range_{$key}"] ?? '',
                        'units' => $request->genetictesting["units_{$key}"] ?? '',
                        'remarks' => $request->genetictesting["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('drugscreening')) {
            foreach ($request->drugscreening as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $drugscreeningData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->drugscreening["result_{$key}"] ?? '',
                        'normal_range' => $request->drugscreening["normal_range_{$key}"] ?? '',
                        'units' => $request->drugscreening["units_{$key}"] ?? '',
                        'remarks' => $request->drugscreening["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('cbc')) {
            foreach ($request->cbc as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $cbcData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->cbc["result_{$key}"] ?? '',
                        'normal_range' => $request->cbc["normal_range_{$key}"] ?? '',
                        'units' => $request->cbc["units_{$key}"] ?? '',
                        'remarks' => $request->cbc["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('bmp')) {
            foreach ($request->bmp as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $bmpData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->bmp["result_{$key}"] ?? '',
                        'normal_range' => $request->bmp["normal_range_{$key}"] ?? '',
                        'units' => $request->bmp["units_{$key}"] ?? '',
                        'remarks' => $request->bmp["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
        
        if ($request->has('cmp')) {
            foreach ($request->cmp as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $cmpData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->cmp["result_{$key}"] ?? '',
                        'normal_range' => $request->cmp["normal_range_{$key}"] ?? '',
                        'units' => $request->cmp["units_{$key}"] ?? '',
                        'remarks' => $request->cmp["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('lipidpanel')) {
            foreach ($request->lipidpanel as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $lipidpanelData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->lipidpanel["result_{$key}"] ?? '',
                        'normal_range' => $request->lipidpanel["normal_range_{$key}"] ?? '',
                        'units' => $request->lipidpanel["units_{$key}"] ?? '',
                        'remarks' => $request->lipidpanel["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('thyroidfunctiontests')) {
            foreach ($request->thyroidfunctiontests as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $thyroidfunctiontestsData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->thyroidfunctiontests["result_{$key}"] ?? '',
                        'normal_range' => $request->thyroidfunctiontests["normal_range_{$key}"] ?? '',
                        'units' => $request->thyroidfunctiontests["units_{$key}"] ?? '',
                        'remarks' => $request->thyroidfunctiontests["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        
        if ($request->has('glucose')) {
            foreach ($request->glucose as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $glucoseData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->glucose["result_{$key}"] ?? '',
                        'normal_range' => $request->glucose["normal_range_{$key}"] ?? '',
                        'units' => $request->glucose["units_{$key}"] ?? '',
                        'remarks' => $request->glucose["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 

        if ($request->has('urinalysis')) {
            foreach ($request->urinalysis as $key => $value) {
                if (!str_starts_with($key, 'result_') && !str_starts_with($key, 'normal_range_') 
                    && !str_starts_with($key, 'units_') && !str_starts_with($key, 'remarks_')) {

                    $urinalysisData[$key] = [
                        'test_name' => $key, // Test name added
                        'result' => $request->urinalysis["result_{$key}"] ?? '',
                        'normal_range' => $request->urinalysis["normal_range_{$key}"] ?? '',
                        'units' => $request->urinalysis["units_{$key}"] ?? '',
                        'remarks' => $request->urinalysis["remarks_{$key}"] ?? ''
                    ];
                }
            }
        } 
          
        
        // Convert CBC Data to JSON and store it
     
        $data['complete_blood_count'] = json_encode($complete_blood_countData);
        $data['lipid_profile'] = json_encode($lipidData);
        $data['preoperative'] = json_encode($preoperativeData);
        $data['acute_illness'] = json_encode($acute_illnessData);
        $data['screening'] = json_encode($screeningData);
        $data['medicationmonitoring'] = json_encode($medicationmonitoringData);
        $data['cardiacmarkers'] = json_encode($cardiacmarkersData); 
        $data['inflammatorymarkers'] = json_encode($inflammatorymarkersData);
        $data['hormonalstudies'] = json_encode($hormonalstudiesData);
        $data['infectiousdiseasescreening'] = json_encode($infectiousdiseasescreeningData);
        $data['genetictesting'] = json_encode($genetictestingData);
        $data['drugscreening'] = json_encode($drugscreeningData);
        $data['cbc'] = json_encode($cbcData);
        $data['bmp'] = json_encode($bmpData);
        $data['cmp'] = json_encode($cmpData);
        $data['lipidpanel'] = json_encode($lipidpanelData);
        $data['thyroidfunctiontests'] = json_encode($thyroidfunctiontestsData);
        $data['glucose'] = json_encode($glucoseData);
        $data['urinalysis'] = json_encode($urinalysisData);
        $data['lab_login_id'] = $lab->id;
        // Handle File Upload
        if ($request->hasFile('report')) {
            $reportFile = $request->file('report');
            $reportFileName = time() . '_L_REPORT_' . $reportFile->getClientOriginalName();
            $reportFile->storeAs('uploads/labsreport', $reportFileName, 'public');
            $data['report'] = $reportFileName;
        }
        
        //dd($data); 
        // Save Lab Report
        $labReport = LabReport::create($data);

        if ($labReport) {
            return response()->json([ 
                'message' => 'Lab Report uploaded successfully!',
                'report' => $labReport,
            ], 200);
        }

        return response()->json(['error' => 'Lab report not added.'], 422);

    } catch (\Throwable $e) {
        return response()->json([
            'message' => 'Something went wrong while uploading the report.',
            'error' => $e->getMessage()
        ], 500);
    }
}
  
 
    

 

}