<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Models\Patient;
use App\Models\PatientAllergies;
use App\Models\PatientVitals;
use App\Models\PatientHealthHistory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use League\Csv\Reader;
use App\Models\Lab;
use App\Models\Hcp;
use Illuminate\Support\Facades\DB;
use App\Models\Radiology;
use App\Models\patientHcpName;
use App\Models\FavouritePatient;
use App\Models\LabReport;
use App\Services\LocationService;
use App\Services\QrCodeService;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Http;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon; 
use App\Models\Labtest;
use App\Models\Labnotification;
use App\Models\Lablogin;
use Illuminate\Support\Facades\Log;
use App\Models\PatientNotification;
use App\Mail\ActivationPatientMail;
use Illuminate\Support\Facades\Mail;
use App\Events\NotificationEvent;
use App\Services\ABDMService; 


class PatientController extends Controller
{
    protected $locationService;
    protected $qrCodeService;
    private static $notificationCount = 0;
    protected $abdmService;

    public function __construct(LocationService $locationService, QrCodeService $qrCodeService, ABDMService $abdmService)
    {

        $this->locationService = $locationService;
        $this->qrCodeService = $qrCodeService;   
        $this->abdmService = $abdmService; 
        date_default_timezone_set('Asia/Kolkata'); // Set timezone to Asia/Kolkata  
    }
    
  
    
    
     
        public function viewer()
    {
        // Static info
        $apiURL = 'https://imaging.bluai.ai';
        $userId = 'akshay';
        $authtoken = 'BluImaging317!'; // replace with real password
        $orgtoken = 'BnR2MzF_ME8QdgBD';
        $studyouid = '2.25.253362716508091413521248309393017725233';
        $appId = 'CBF3C7FC-2FAC-4E8B-A53E-43F972E0AE72';
        $encLevel = 3;
        $isPatient = true;   
        $numberofmonitors = 1;

        $cmURL = $apiURL . "/CMStudyLoader.aspx";
        $standardParams = "command=load&encusertoken=0&appname=generic";
        $timeout = now()->addSeconds(5)->toISOString();

        $params = $standardParams .
            "&numberofmonitors={$numberofmonitors}" .
            "&userId=" . urlencode($userId) .
            "&authtoken={$authtoken}" .
            "&studyouid={$studyouid}" .
            "&orgtoken={$orgtoken}" .
            "&timeout={$timeout}" .
            ($isPatient ? "&ispatient=1" : "");

        if ($encLevel === 3) {
            $tokenEnc = $this->getStringToken($apiURL, $params);
            $urlString = $cmURL . "?tokenEnc=" . $tokenEnc;
        } elseif ($encLevel === 2) {
            $urlString = $cmURL . "?token=" . base64_encode($params);
        } else {
            $urlString = $cmURL . "?" . $params;
        }

        return view('b3d.viewer', [
            'iframeUrl' => $urlString
        ]);
    }

    private function getStringToken(string $apiURL, string $params)
    {
        $response = Http::post($apiURL . "/B3DNetPublic.svc/json/GetStringToken", [
            'str' => $params
        ]);

        if ($response->successful()) {
            return $response->json();
        }

        throw new \Exception("Failed to get encrypted token");
    }
    
 


          public function tests()
    {

        return view('patients.tests');
    
    }
    public function noteSetting($id = null){
    
        $patient = Auth::guard('patients')->user();    
        $data['getNotes'] = Patient::with(['healthHistories' => function($query) {
              $query->orderBy('health_history_id', 'desc'); 
                      }, 'hcpNames'])->find($patient->patient_id);
         $data['getsinglenote'] = PatientHealthHistory::where('health_history_id', $id)->first();
        return view('patients.nodesetting', $data);
    }

    public function patientsSuccesss($id){
    
      $patient = Patient::findOrFail($id);
       
       $data['data'] = $patient;
      
      return view('patients.patients_success', $data);
    }
    
  public function sendQrcode(Request $request)
{
   
    $patientId = $request->input('patientId');
    
    $patient = Patient::findOrFail($patientId);

    $qrCodeFilePath = storage_path('app/public/qr_codes/' . $patient->qr_code);
    if (file_exists($qrCodeFilePath)) {
        return response()->json([
        'status' => false, 
        'message' => 'QR Code successfully generated and downloaded!',
        'qr_code' => $patient->qr_code 
    ]);
    } else {
        return response()->json([
            'status' => false,
            'message' => 'QR code file not found.'
        ]);
    }
}
      
         
         
 public function labsPrint($id = null)
{


 $patient = Auth::guard('patients')->user();
 
   $existingRecord = $id ? Lab::find($id) : null;
   $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_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,
    'hcp' => $hcpData, 
];

    
    $pdf = Pdf::loadView('patients.labprint', $data);
 
    return response($pdf->stream('labprint.pdf'), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="labprint.pdf"',
    ]);  
 
}

 
   
 public function labs($id = null)
{
 
    $patient = Auth::guard('patients')->user();
    $today = Carbon::today()->toDateString();
    $hcp = Auth::guard('hcp')->user();
  
    $existingRecord = $id 
        ? Lab::find($id) 
        : Lab::where('patient_id', $patient->patient_id)
              ->orderBy('created_at', 'desc')
              ->first();
              
   if ($hcp) {
    $existingRecord = $id 
        ? Lab::find($id) 
        : Lab::where('patient_id', $patient->patient_id)
              ->whereDate('created_at', $today) // Fetch only today's data
              ->orderBy('created_at', 'desc')
              ->first();
}
              
    $Lab = $id 
        ? Lab::find($id) 
        : Lab::where('patient_id', $patient->patient_id)
             ->latest('id')
             ->first();
   
        $lab_id = 0;
        if($Lab){
            $lab_id = $Lab->id;
        }
     
    $previous = Lab::where('patient_id', $patient->patient_id)
                   ->where('id', '<', $lab_id )
                   ->orderBy('id', 'desc')
                   ->first();
              
    $next = Lab::where('patient_id', $patient->patient_id)
               ->where('id', '>', $lab_id )
               ->orderBy('id', 'asc')
               ->first();
          
                 
   $hcpData = $existingRecord ? Hcp::find($existingRecord->hcp_id) : null;
  $LabReport = $existingRecord ? LabReport::where('lab_id', $existingRecord->id)->first() : null;


   $allLabls = Lablogin::all(); 

    $reportUrl = $LabReport && $LabReport->report ? asset('storage/uploads/labsreport/' . basename($LabReport->report)) : 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,
    'previous' => $previous ?? null,
    'next' => $next ?? null,
    'labid' => $Lab->id ?? null, 
    'reportUrl' => $reportUrl,
    'allLabls' => $allLabls ?? null, 
];

    $data['hcp'] = $hcpData; 
    
    return view('patients.labs', $data);
}

 public function nearLabs()  {
 
 
 return view('patients.near_labs');
 
 }
 
 public function ecg()  {
 
 
 return view('patients.ecg');
 
 }
 


 public function saveSelectedLab(Request $request)
{

    try {
        $patient = Auth::guard('patients')->user();

        $existingLab = Labtest::where('patient_id', $patient->patient_id)
            ->where('lab_id', $request->lab_id)
            ->first(); 
 
        if ($existingLab) { 
            return response()->json(['success' => false, 'message' => 'Lab already Selected!']);
        }

        Labtest::create([
            'patient_id' => $patient->patient_id,
            'lab_id' => $request->lab_id,
            'lablogin_id' => $request->labLogin
        ]);
        $hcp = Lab::with('hcp')->where('id', $request->lab_id)->first();

        if (!$hcp) {
            return response()->json(['error' => 'Lab not found'], 404);
        }
        
        if (!$hcp->hcp) {
            return response()->json(['error' => 'HCP not found'], 404);
        }
         
        $message = "Dr ".$hcp->hcp->first_name . " has requested a lab test for " . $patient->first_name;

        Labnotification::create([
            'patient_id' => $patient->patient_id,
            'message' => $message,  
            'lablogin_id' => $request->labLogin
        ]);

        Log::info('Lab Selected', [
            'patient_id' => $patient->patient_id,
            'lab_id' => $request->lab_id, 
            'lablogin_id' => $request->labLogin
        ]);

        return response()->json(['success' => true, 'message' => 'Lab Selected!']);

    } catch (\Exception $e) {
        Log::error('Error while saving lab for patient.', [
            'error' => $e->getMessage(),
            'patient_id' => isset($patient) ? $patient->patient_id : 'N/A',
            'request_data' => $request->all()
        ]);
        return response()->json([
            'success' => false,
            'message' => 'Error while saving lab.',
            'error' => $e->getMessage()
        ], 500);
    }
}


public function getNotifications()
{
    try {
        $patient = Auth::guard('patients')->user();
        if (!$patient) {
            Log::error('Patient not found while retrieving notifications.');
            return response()->json(['success' => false, 'message' => 'Patient not found!'], 404);
        }

        $notifications = PatientNotification::where('patient_id', $patient->patient_id)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get(); 

        Log::info('Notifications retrieved successfully for patient.', [
            'patient_id' => $patient->patient_id,
        ]);

        return response()->json([
            'notifications' => $notifications,
        ]);

    } catch (\Exception $e) {
        Log::error('Error retrieving notifications for patient.', [
            'error' => $e->getMessage(),
            'patient_id' => $patient->patient_id ?? 'N/A'
        ]); 
        return response()->json([
            'success' => false,
            'message' => 'Error retrieving notifications.',
            'error' => $e->getMessage()
        ], 500);
    }
} 

 
public function clearNotifications(Request $request)
{
    try {

        $patient = Auth::guard('patients')->user();

        if (!$patient) {

            Log::error('Patient not found while attempting to clear notifications.');
            return response()->json(['success' => false, 'message' => 'Patient not found!'], 404);
        }

        $deletedCount = PatientNotification::where('patient_id', $patient->patient_id)->delete();

        Log::info('Notifications cleared successfully for patient.', [
            'patient_id' => $patient->patient_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(),
            'patient_id' => isset($patient) ? $patient->patient_id : 'N/A',
            'request_data' => $request->all()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'Error clearing notifications.',
            'error' => $e->getMessage()
        ], 500);
    }
}

 


  public function saveRadiology(Request $request)
{
    $validatedData = $request->validate([
        '_token' => 'required|string',
        'reason' => 'nullable|array',
        'reason_other' => 'nullable|string',
        'imaging' => 'nullable|array',
        'xRay_area' => 'nullable|string',
        'ultrasound_area' => 'nullable|string',
        'ctScan_area' => 'nullable|string',
        'mri_area' => 'nullable|string',
        'nuclearMedicine_area' => 'nullable|string',
        'interventionalRadiology_procedure' => 'nullable|string',
        'otherImaging_specify' => 'nullable|string',
        'diagnostics' => 'nullable|array',
        'stressTestSpecify' => 'nullable|string',
        'endoscopySpecify' => 'nullable|string',
        'biopsySpecify' => 'nullable|string',
        'bloodTestsSpecify' => 'nullable|string',
        'urineTestsSpecify' => 'nullable|string',
        'otherDiagnosticsSpecify' => 'nullable|string',
    ]);

    $hcp = Auth::guard('hcp')->user();
    if (!$hcp) {
        return redirect()->route('hcp.login');
    }

    $patient = Auth::guard('patients')->user();

    try {
        $today = \Carbon\Carbon::today()->toDateString();

        $data = [
            'reason' => $validatedData['reason'] ? json_encode($validatedData['reason']) : null,
            'reason_other' => $validatedData['reason_other'] ?? null,
            'imaging' => $validatedData['imaging'] ? json_encode($validatedData['imaging']) : null,
            'xRay_area' => $validatedData['xRay_area'] ?? null,
            'ultrasound_area' => $validatedData['ultrasound_area'] ?? null,
            'ctScan_area' => $validatedData['ctScan_area'] ?? null,
            'mri_area' => $validatedData['mri_area'] ?? null,
            'nuclearMedicine_area' => $validatedData['nuclearMedicine_area'] ?? null,
            'interventionalRadiology_procedure' => $validatedData['interventionalRadiology_procedure'] ?? null,
            'otherImaging_specify' => $validatedData['otherImaging_specify'] ?? null,
            'diagnostics' => $validatedData['diagnostics'] ? json_encode($validatedData['diagnostics']) : null,
            'stressTestSpecify' => $validatedData['stressTestSpecify'] ?? null,
            'endoscopySpecify' => $validatedData['endoscopySpecify'] ?? null,
            'biopsySpecify' => $validatedData['biopsySpecify'] ?? null,
            'bloodTestsSpecify' => $validatedData['bloodTestsSpecify'] ?? null,
            'urineTestsSpecify' => $validatedData['urineTestsSpecify'] ?? null,
            'otherDiagnosticsSpecify' => $validatedData['otherDiagnosticsSpecify'] ?? null,
            'hcp_id' => $hcp->hcp_id, 
            'patient_id' => $patient->patient_id
        ];

        $existingRecord = Radiology::whereDate('created_at', $today)
            ->where('hcp_id', $hcp->hcp_id)
            ->where('patient_id', $patient->patient_id)
            ->first();

        if ($existingRecord) {
            $existingRecord->update($data);

            return redirect()->route('show-patient-portal')
                ->with('success', 'Radiology record updated successfully.');
        } else {

            Radiology::create($data);

            return redirect()->route('show-patient-portal')
                ->with('success', 'Radiology added successfully.');
        }
    } catch (\Exception $e) {

        \Log::error('Error saving Radiology: ' . $e->getMessage());

        return redirect()->back()->with('error', 'An error occurred while adding the Radiology.');
    }
}



   public function savelab(Request $request)
{

    $validated = $request->validate([
        'reason_for_blood_work' => 'nullable|array',
        'other_reason' => 'nullable|string',
        'basic_panel' => 'nullable|array',
        'basic_panel_options' => 'nullable|array',
        'thyroid_tests' => 'nullable|array',
        'specialty_tests' => 'nullable|array',
        'cardiac_tests' => 'nullable|array',
        'inflammatory_tests' => 'nullable|array',
        'hormone_tests' => 'nullable|array',
    ]);

    $hcp = Auth::guard('hcp')->user();
    if (!$hcp) {
        return redirect()->route('hcp.login');
    }
    
    self::$notificationCount++;
    
    $patient = Auth::guard('patients')->user();
   
    try {
   
        $today = \Carbon\Carbon::today()->toDateString();

        $data = [
            'reason_for_blood_work' => json_encode($validated['reason_for_blood_work'] ?? null),
            'other_reason' => $validated['other_reason'] ?? null,
            'basic_panel' => json_encode($validated['basic_panel'] ?? null),
            'basic_panel_options' => json_encode($validated['basic_panel_options'] ?? null),
            'thyroid_tests' => json_encode($validated['thyroid_tests'] ?? null),
            'specialty_tests' => json_encode($validated['specialty_tests'] ?? null),
            'cardiac_tests' => json_encode($validated['cardiac_tests'] ?? null),
            'inflammatory_tests' => json_encode($validated['inflammatory_tests'] ?? null),
            'hormone_tests' => json_encode($validated['hormone_tests'] ?? null),
            'hcp_id' => $hcp->hcp_id, 
            'patient_id' => $patient->patient_id,
        ];

        $existingRecord = Lab::whereDate('created_at', $today)
            ->where('hcp_id', $hcp->hcp_id)
            ->first();

        if ($existingRecord) {

            $existingRecord->update($data);

            return redirect()->route('show-patient-portal')
                ->with('success', 'Lab record updated successfully.');
        } else {
            
            $id = Lab::create($data); 
              $message = "Dr ".$hcp->first_name." has requested a lab test for ".$patient->first_name; 
              PatientNotification::create(['patient_id' => $patient->patient_id, 'hcp_id' => $hcp->hcp_id, 'message' => $message]);
             event(new NotificationEvent($message));

            return redirect()->route('show-patient-portal')
                ->with('success', 'Lab record created successfully.');
        }
    } catch (\Exception $e) {
      
        \Log::error('Error saving lab: ' . $e->getMessage());

        return redirect()->back()->with('error', 'An error occurred while adding the lab.');
    }
}

public function favourite(Request $request) 
{
    try {
        $patient_id = $request->patient_id;
        $hcp = Auth::guard('hcp')->user();
          $hcp_id = $hcp->hcp_id;
        // Check if the patient is already a favorite
        $favourite = FavouritePatient::where('patient_id', $patient_id)
                                     ->where('hcp_id', $hcp_id)
                                     ->first();

        if ($favourite) {
            $favourite->delete(); // Remove from favorites
            return response()->json(['status' => 'removed']);
        } else {
            // Add as favorite
            FavouritePatient::create([
                'patient_id' => $patient_id,
                'hcp_id' => $hcp_id,
                'date' => now()
            ]);
            return response()->json(['status' => 'added']);
        }
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    } 
}

  public function radiologyPrint($id = null) 
{
    $patient = Auth::guard('patients')->user();
    
    $Radiology = Radiology::find($id);
    if (!$Radiology) {
        abort(404, "Radiology record not found.");
    }

    $hcpData = Hcp::find($Radiology->hcp_id);  

    $data = [
        'reason' => $Radiology ? json_decode($Radiology->reason, true) : null,
        'imaging' => $Radiology ? json_decode($Radiology->imaging, true) : null,
        'diagnostics' => $Radiology ? json_decode($Radiology->diagnostics, true) : null,
        'reason_other' => $Radiology ? $Radiology->reason_other : null,
        'xRay_area' => $Radiology ? $Radiology->xRay_area : null,
        'ultrasound_area' => $Radiology ? $Radiology->ultrasound_area : null,
        'interventionalRadiology_procedure' => $Radiology ? $Radiology->interventionalRadiology_procedure : null,
        'biopsySpecify' => $Radiology ? $Radiology->biopsySpecify : null,
        'urineTestsSpecify' => $Radiology ? $Radiology->urineTestsSpecify : null,
        'nuclearMedicine_area' => $Radiology ? $Radiology->nuclearMedicine_area : null,
        'endoscopySpecify' => $Radiology ? $Radiology->endoscopySpecify : null,
        'ctScan_area' => $Radiology ? $Radiology->ctScan_area : null,
        'mri_area' => $Radiology ? $Radiology->mri_area : null,
        'otherImaging_specify' => $Radiology ? $Radiology->otherImaging_specify : null,
        'bloodTestsSpecify' => $Radiology ? $Radiology->bloodTestsSpecify : null,
        'otherDiagnosticsSpecify' => $Radiology ? $Radiology->otherDiagnosticsSpecify : null, 
        'stressTestSpecify' => $Radiology ? $Radiology->stressTestSpecify : null,
        
        'radiologyRecord' => $Radiology, 
        'hcp' => $hcpData, 
        'labsdata' => $Radiology, 
        'radiologyid' => $Radiology->id, 
        'patient' => $patient, 
        
    ]; 

    $pdf = Pdf::loadView('patients.radiologyprint', $data);  

    return response($pdf->stream('radiologyprint.pdf'), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="radiologyprint.pdf"',
    ]);  
}
  

    public function Radiology($id = null) 
{
    $patient = Auth::guard('patients')->user();
    $today = Carbon::today()->toDateString();
     $hcp = Auth::guard('hcp')->user();
  
    if ($id) {
        
        $RadiologyRecord = Radiology::where('patient_id', $patient->patient_id)->find($id);
    } else {
       
        $RadiologyRecord = Radiology::where('patient_id', $patient->patient_id)
                                     ->orderBy('created_at', 'desc')
                                     ->first();
                                     
                                      if ($hcp) {
       
          $RadiologyRecord = Radiology::where('patient_id', $patient->patient_id)
                                      ->whereDate('created_at', $today) 
                                     ->orderBy('created_at', 'desc')
                                     ->first();
                                     
      }
    }
    
    
      
    
 
    $Radiology = $id ? Radiology::find($id) : Radiology::latest('id')->first();


    $radiology_id = 0;
    if($Radiology){
        $radiology_id = $Radiology->id;
    }

    $previous = Radiology::where('patient_id', $patient->patient_id)
                         ->where('id', '<', $radiology_id)
                         ->orderBy('id', 'desc')
                         ->first();

    $next = Radiology::where('patient_id', $patient->patient_id)
                     ->where('id', '>', $radiology_id)
                     ->orderBy('id', 'asc')
                     ->first();
       $hcpData = $RadiologyRecord ? Hcp::find($RadiologyRecord->hcp_id) : null; 
    $data = [
        'reason' => $RadiologyRecord ? json_decode($RadiologyRecord->reason, true) : null,
        'imaging' => $RadiologyRecord ? json_decode($RadiologyRecord->imaging, true) : null,
        'diagnostics' => $RadiologyRecord ? json_decode($RadiologyRecord->diagnostics, true) : null,
        'reason_other' => $RadiologyRecord ? $RadiologyRecord->reason_other : null, 
        'xRay_area' => $RadiologyRecord ? $RadiologyRecord->xRay_area : null,
        'ultrasound_area' => $RadiologyRecord ? $RadiologyRecord->xRay_area : null,
        'interventionalRadiology_procedure' => $RadiologyRecord ? $RadiologyRecord->interventionalRadiology_procedure : null,
        'biopsySpecify' => $RadiologyRecord ? $RadiologyRecord->biopsySpecify : null,
        'urineTestsSpecify' => $RadiologyRecord ? $RadiologyRecord->urineTestsSpecify : null,
        'nuclearMedicine_area' => $RadiologyRecord ? $RadiologyRecord->nuclearMedicine_area : null,
        'endoscopySpecify' => $RadiologyRecord ? $RadiologyRecord->endoscopySpecify : null,
        'ctScan_area' =>   $RadiologyRecord ? $RadiologyRecord->ctScan_area : null,
        'mri_area' =>   $RadiologyRecord ? $RadiologyRecord->mri_area : null,
        'otherImaging_specify' =>   $RadiologyRecord ? $RadiologyRecord->otherImaging_specify : null,
        'bloodTestsSpecify' =>   $RadiologyRecord ? $RadiologyRecord->bloodTestsSpecify : null,
        'otherDiagnosticsSpecify' =>   $RadiologyRecord ? $RadiologyRecord->otherDiagnosticsSpecify : null, 
        
        'stressTestSpecify' => $RadiologyRecord ? $RadiologyRecord->stressTestSpecify : null,
        
        'radiologyRecord' => $RadiologyRecord ?? null, 
        'hcp' => $hcpData, 
        'previous' => $previous,  
        'next' => $next,
        'labsdata' => $RadiologyRecord ?? null,
        'radiologyid' => $radiology_id, 
    ];  
    
    
   // dd($data);

    return view('patients.radiology', $data);
}


    public function index()
    {

        return view('patients.index');
    }


    function cleanNumericValue($value) {
       
        return preg_replace('/[^0-9.]/', '', $value);
    }
    
    
     public function vitals(Request $request)
     {
     
    $patient = Auth::guard('patients')->user();
    $userContent_data = PatientVitals::where('patient_id', $patient->patient_id)
    ->orderBy('vital_id', 'desc')
     ->first();


    if ($request->isMethod('post')) {
        $vitalsData = $request->all();
        

        $Blood_Pressure = explode("/", $vitalsData['Blood_Pressure']);

        $data['patient_id'] = "010060"; 
        $data['body_temperature'] = $this->cleanNumericValue($vitalsData['Temperature']);
        $data['pulse_rate'] = $this->cleanNumericValue($vitalsData['Heart_Rate']);
        $data['respiration_rate'] = $this->cleanNumericValue($vitalsData['Respiratory_Rate_(RR)']);
        $data['blood_pressure_systolic'] = $this->cleanNumericValue($Blood_Pressure[0]);  
        $data['blood_pressure_diastolic'] = $this->cleanNumericValue($Blood_Pressure[1]);
        $data['blood_oxygen'] = $this->cleanNumericValue($vitalsData['Oxygen_Saturation_(SpO₂)']);
        $data['bmi'] = $this->cleanNumericValue($vitalsData['BMI']);
        $data['blood_glucose_level'] = $this->cleanNumericValue($vitalsData['Blood_Glucose_Level_(Fasting)']);

        $userContent = json_encode($data, JSON_UNESCAPED_UNICODE);

    } else {
      
         if (empty($userContent_data)) {
        // Handle the case when there's no data (perhaps default values or an empty JSON)
        $userContent = json_encode([
            "patient_id" => null,
            "body_temperature" => null,
            "pulse_rate" => null,
            "respiration_rate" => null,
            "blood_pressure_systolic" => null,
            "blood_pressure_diastolic" => null,
            "blood_oxygen" => null,
            "bmi" => null,
            "blood_glucose_level" => null,
        ], JSON_UNESCAPED_UNICODE);
    } else {
        $userContent = json_encode([
            "patient_id" => $userContent_data->patient_id,
            "body_temperature" => $userContent_data->body_temperature,
            "pulse_rate" => $userContent_data->pulse_rate,
            "respiration_rate" => $userContent_data->respiration_rate,
            "blood_pressure_systolic" => $userContent_data->blood_pressure_systolic,
            "blood_pressure_diastolic" => $userContent_data->blood_pressure_diastolic,
            "blood_oxygen" => $userContent_data->blood_oxygen,
            "bmi" => $userContent_data->bmi,
            "blood_glucose_level" => $userContent_data->blood_glucose_level,
        ], JSON_UNESCAPED_UNICODE);
    }
    }

    $systemContent = mb_convert_encoding("You are an AI medical assistant. Your task is to evaluate patient health metrics based on the following parameters:\n- Body Temperature\n- Pulse Rate\n- Respiration Rate\n- Blood Pressure (Systolic & Diastolic)\n- Blood Oxygen Level\n- BMI\n- Blood Glucose Level\n\nAnalyze the patient's health data and provide a detailed, patient-friendly summary in JSON format. The output must follow this structure:\n{\n    \"Patient_ID\": xxxx,\n    \"AI_Analysis\": {\n        \"Health_Insights\": \"Summarize key findings, highlighting any abnormal values or trends.\",\n        \"Possible_Medical_Conditions\": \"If applicable, suggest potential health conditions in simple terms and explain why they may be relevant based on the data. Ensure the language is easy for the patient to understand.\",\n        \"Health_Advice\": \"Provide general wellness advice, including lifestyle or dietary recommendations, if relevant.\"\n    }\n}\n\nUse these reference ranges for normal values:\n1. **Body Temperature**: 36.5�C to 37.5�C\n2. **Pulse Rate**: 60-100 bpm\n3. **Respiration Rate**: 12-16 breaths per minute\n4. **Blood Pressure**: Systolic 90-120 mmHg, Diastolic 60-80 mmHg\n5. **Blood Oxygen Level**: 95-100%\n6. **BMI**: 18.5-24.9\n7. **Blood Glucose Level**: 70-99 mg/dL (fasting)\nEnsure that the output is valid JSON.", 'UTF-8');

 
    $url = 'https://bluai-azureopenai.openai.azure.com/openai/deployments/gpt-4o-mini/chat/completions?api-version=2024-08-01-preview';

    $response = Http::retry(3, 1000)
     ->withHeaders([
        'Content-Type' => 'application/json',
        'api-key' => '3e502b17237c44bf9a7c61ecf012e7d2',  
    ])->post($url, [
        'messages' => [
            [
                'role' => 'system',
                'content' => $systemContent
            ],
            [
                'role' => 'user',
                'content' => $userContent
            ]
        ]
    ]);
    
    if ($response->successful()) {
        $rawContent = $response['choices'][0]['message']['content'];

        $cleanedContent = trim($rawContent);
        $cleanedContent = preg_replace('/```json/', '', $cleanedContent);
        $cleanedContent = preg_replace('/```/', '', $cleanedContent);
        $fixedResponse = preg_replace('/,\s*}/', '}', $cleanedContent);
        $fixedResponse = preg_replace('/"([^"]+?)":\s*"([^"]*?)(?<!\s)"(?=[,}])/', '"$1":"$2"', $fixedResponse); // Fix any dangling quotes

        $data['patientData'] = json_decode($fixedResponse, true);
    } else {
        $data['error'] = 'Failed to retrieve data from AI API';
    }





    
    if ($request->isMethod('post')) {
        
    $userContent_data['patient_id'] = "010060"; 
    $userContent_data['body_temperature'] = $this->cleanNumericValue($vitalsData['Temperature']);
    $userContent_data['pulse_rate'] = $this->cleanNumericValue($vitalsData['Heart_Rate']);
    $userContent_data['respiration_rate'] = $this->cleanNumericValue($vitalsData['Respiratory_Rate_(RR)']);
    $userContent_data['blood_pressure_systolic'] = $this->cleanNumericValue($Blood_Pressure[0]);  
    $userContent_data['blood_pressure_diastolic'] = $this->cleanNumericValue($Blood_Pressure[1]);
    $userContent_data['blood_oxygen'] = $this->cleanNumericValue($vitalsData['Oxygen_Saturation_(SpO₂)']);
    $userContent_data['bmi'] = $this->cleanNumericValue($vitalsData['BMI']);
    $userContent_data['blood_glucose_level'] = $this->cleanNumericValue($vitalsData['Blood_Glucose_Level_(Fasting)']);
        
        return response()->json([
            'userContent' => $userContent_data, 
            'patientData' => $data['patientData'] ?? null 
        ]);
        
    } else {
         
        $data['userContent'] = $userContent_data;
       
        return view('patients.vitals', $data); 
    }
}


public function savenotes(Request $request)
{
    $validatedData = $request->validate([
        'hcp_notes' => 'required|string',
    ]);

    $hcp_id = '';
    if (Auth::guard('hcp')->check()) {
        $hcp_data = Auth::guard('hcp')->user();
    } 

    try {
        $patient = Auth::guard('patients')->user();
        $today = Carbon::now()->format('Y-m-d'); 

        $existingRecord = PatientHealthHistory::where('hcp_id', $hcp_data->hcp_id)
                                              ->whereDate('diagnosis_date', $today) 
                                              ->first();

        if ($existingRecord) {
            $existingRecord->hcp_notes = $validatedData['hcp_notes'];
            $existingRecord->save();

            // Redirect back instead of 'patient-portal'
            return redirect()->back()->with('success', 'Note updated successfully.');
        } else {
            $patientHealthHistory = new PatientHealthHistory();
            $patientHealthHistory->hcp_notes = $validatedData['hcp_notes'];
            $patientHealthHistory->diagnosis_date = $today;
            $patientHealthHistory->hcp_id = $hcp_data->hcp_id;
            $patientHealthHistory->patient_id = $patient->patient_id;
            $patientHealthHistory->save();
            
            $patientHcpName = new patientHcpName();
            $patientHcpName->health_history_id  = $patientHealthHistory->health_history_id;
            $patientHcpName->provider_name  = $hcp_data->first_name.' '.$hcp_data->last_name;
            $patientHcpName->provider_contact  = $hcp_data->contact_phone_personal;
            $patientHcpName->patient_id = $patient->patient_id;  
            $patientHcpName->save();

            // Redirect back instead of 'patient-portal'
            return redirect()->back()->with('success', 'Note added successfully.');
        }
    } catch (\Exception $e) {
        \Log::error('Error saving notes: ' . $e->getMessage());
        return redirect()->back()->with('error', 'An error occurred while adding the note.');
    }
}


    public function getPatientData()
    {
        $patients = Patient::all();

        return DataTables::of($patients)
            ->addColumn('age', function ($patient) {
                return isset($patient->date_of_birth) ? Carbon::parse($patient->date_of_birth)->age : '';
            })
            ->addColumn('qr_code', function ($patient) {
                $qrCode = $patient->qr_code ?? $patient->qr_code ?? '';
                return $qrCode ? '<img src="' . asset('storage/qr_codes/' . $qrCode) . '" style="width: 64px;" alt="Image">' : '';
            })
            ->addColumn('action', function ($patients) {
                return '<a href="' . url('patients/' . $patients->patient_id . '/edit') . '" class="btn btn-sm btn-primary me-2">Edit</a>' .
                    '<a href="' . url('patients/' . $patients->patient_id . '/delete') . '" class="btn btn-sm btn-danger">Delete</a>';
            })
            ->rawColumns(['qr_code', 'action'])
            ->make(true);
    }

    public function patient_profile()
    {
        return view('patients.profile');
    }

    public function create()
    {


        $dialingCode = null;
        $ip = $this->locationService->getPublicIP();

        $countryCode = $this->locationService->getCountryCodeByIp($ip);

        if ($countryCode) {

            $dialingCode = $this->locationService->getDialingCode($countryCode);
        }
        return view('patients.create', compact('dialingCode'));
    }


    public function register()
    {


        $dialingCode = null;
        $ip = $this->locationService->getPublicIP();

        $countryCode = $this->locationService->getCountryCodeByIp($ip);

        if ($countryCode) {

            $dialingCode = $this->locationService->getDialingCode($countryCode);
        }
        return view('patients.patients_register', compact('dialingCode'));
    }

   
    
     public function patientRegister(Request $request)
    {
   
        
         $rules = [
        'first_name' => 'required|string|max:50',
        'date_of_birth' => 'required|date',
        'sex' => 'required|string|max:10',
        'address' => 'required|string',
        'patient_phone_number' => 'nullable|string|max:20',
        'photo' => 'required',
        'email' => 'required|email|unique:patient,email', 
      ];
      
     
        
        if ($request->has('aadhar_card_num') && !empty($request->aadhar_card_num)) { 
        $rules['aadhar_card_num'] = 'numeric|unique:patient,aadhar_card_num';
        }
       

          if ($request->has('ssn_card_num') && !empty($request->ssn_card_num)) {
        $rules['ssn_card_num'] = 'numeric|unique:patient,ssn_card_num';
        } 


       $validatedData = $request->validate($rules);
       

        try {
            $patient = new Patient();

            $validatedData['disability'] = $request->input('disability'); 
            
            if ($validatedData['disability'] === 'other') {
                $validatedData['disability'] = $request->input('other_disability');
            }

            if ($validatedData['disability'] === 'other') {
                $validatedData['disability'] = $request->input('other_disability');
            }
            if ($request->has('vaccines')) {
                $validatedData['vaccines'] = json_encode($request->input('vaccines'));
            } 
           
             
            $patient->fill($validatedData);


            $patient->patient_phone_num_country_code = $request->patient_phone_num_country_code;
             $patient->email = $request->email;
            
             
            if ($request->has('ssn_card_num')) {
            $patient->ssn_card_num = $request->ssn_card_num;
        }
        
   
        if ($request->has('aadhar_card_num')) {
            $patient->aadhar_card_num = $request->aadhar_card_num;
        }
        
        if ($request->has('blood_group') && !empty($request->blood_group)) { 
          $patient->blood_group = $request->blood_group;
        }
         if ($request->has('organ_donors') && !empty($request->organ_donors)) { 
          $patient->organ_donors = $request->organ_donors;
        }
       

            $patient->unique_id = $request->unique_id;


            if ($request->hasFile('photo')) {
                $file = $request->file('photo');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $file->storeAs('photos', $fileName, 'public');
                $patient->photo = $fileName;
            }

     
            if ($request->hasFile('aadhar_card')) {
                $file = $request->file('aadhar_card');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $file->storeAs('documents', $fileName, 'public');
                $patient->aadhar_card = $fileName;
            }

            if ($request->hasFile('ssn_card')) {
                $file = $request->file('ssn_card');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $file->storeAs('documents', $fileName, 'public');
                $patient->ssn_card = $fileName;
            }



            $qr_text = '';

            $qr_text = "Patient Information:\n";
            $qr_text .= "--------------------------\n\n";

            if ($request->first_name) {
                $qr_text .= "First Name: " . $request->first_name . "\n\n";
            }
            if ($request->last_name) {
                $qr_text .= "Last Name: " . $request->last_name . "\n\n";
            }
           
            if ($request->date_of_birth) {
                $qr_text .= "Date of Birth: " . $request->date_of_birth . "\n\n";
            }
            if ($request->sex) {
                $qr_text .= "Sex: " . $request->sex . "\n\n";
            }
            if ($request->address) {
                $qr_text .= "Address: " . $request->address . "\n\n";
            }
              if ($request->email) {
                $qr_text .= "Email: " . $request->email . "\n\n";   
            }
            if ($request->patient_phone_num_country_code) {
                $qr_text .= "Phone Country Code: " . $request->patient_phone_num_country_code . "\n\n";
            }
            if ($request->patient_phone_number) {
                $qr_text .= "Phone Number: " . $request->patient_phone_number . "\n\n";
            }
          
            if ($request->aadhar_card_num) {
                $qr_text .= "Aadhar Card: " . $request->aadhar_card_num . "\n\n";
            }
           
            if ($request->ssn_card_num) {
                $qr_text .= "SSN Card: " . $request->ssn_card_num . "\n\n";
            }
           
             if ($request->blood_group) {
                $qr_text .= "Blood Group: " . $request->blood_group . "\n\n";
            }
            if ($request->organ_donors) {
             $qr_text .= "Organ Donors: I am an organ donor\n\n";  
             }

            if ($request->unique_id) {
                $qr_text .= "Unique ID: " . $request->unique_id . "\n\n";
            }
            if ($request->disability) {
                $qr_text .= "Disability: " . $request->disability . "\n\n";
            }
             
            $qr_text .= "--------------------------\n";

            $filename = 'qr_code_' . time();
            $dataUri = $this->qrCodeService->saveQrCode($qr_text, $filename);
            $qrCode =  explode('/', $dataUri);
            if (isset($qrCode[1])) {
                $patient->qr_code = $qrCode[1];
            }
            
         

               $patient->save(); // Save the patient


            
             $data = [
               'title' => 'Activation Link',
                'body' => 'This is Bluai Patient Activation Link: ' . url('/activation/' . $patient->patient_id),
             ];
             Mail::to($request->email)->send(new ActivationPatientMail($data));  
               
           
           return redirect()->route('patients.success', ['id' => $patient->patient_id]) 
                 ->with('success', 'Patient added successfully.');

        } catch (\Exception $e) {
         
            return redirect()->back()->with('errors', $e->getMessage());
        }
    }
    
    
    
    public function updatePatientStatus($id){
    
     $patient = Patient::findOrFail($id);

    $patient->status = '1'; 

    $patient->save();

    return redirect()->route('patients.success', ['id' => $id])  
                 ->with('success', 'Patient Activation successfully');
    }


    public function edit($id)
    {
        $patient = Patient::findOrFail($id);
        return view('patients.edit', compact('patient'));
    }

    public function update(Request $request, $id)
    {
        // Validate the request
        $validatedData = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'middle_name' => 'nullable|string|max:255',
            'date_of_birth' => 'required|date',
            'sex' => 'required|string',
            'address' => 'required|string|max:255',
            'patient_phone_num_country_code' => 'nullable|string|max:10',
            'patient_phone_number' => 'nullable|string|max:15',
            'patient_er_country_code' => 'nullable|string|max:10',
            'patient_er_phone_number' => 'nullable|string|max:15',
            'aadhar_card_num' => 'nullable|string|max:20',
            'pan_card_num' => 'nullable|string|max:20',
            'ssn_card_num' => 'nullable|string|max:20',
            'cibil_score' => 'nullable|integer|min:0|max:999',
            'profession' => 'nullable|string|max:255',
            'employment_status' => 'nullable|string|max:255',
            'marital_status' => 'nullable|string|max:255',
            'father_name' => 'nullable|string|max:255',
            'mother_name' => 'nullable|string|max:255',
            'male_siblings' => 'nullable|integer|min:0',
            'female_siblings' => 'nullable|integer|min:0',
            'consent_to_contact' => 'nullable|boolean',
            'medical_billing_address' => 'nullable|string|max:255',
            'current_medications' => 'nullable|string|max:255',
            'previous_health_history' => 'nullable|string|max:255',
            'consent_to_treatment' => 'nullable|boolean',
            'allergies' => 'nullable|string|max:255',
            'disability' => 'string',
            'other_disability' => 'nullable|string|max:255',
        ]);
    
        // Handle 'other' disability
        if ($validatedData['disability'] === 'other') {
            $validatedData['disability'] = $validatedData['other_disability'];
        }
    
        // Find patient and update data except for files and unique_id
        $patient = Patient::findOrFail($id);

        $patient->update(array_merge($request->except(['unique_id', 'photo', 'drivers_license', 'aadhar_card', 'ssn_card', 'pan_card']), [
            'disability' => $validatedData['disability'],
        ]));
     
        // Generate unique_id using phone and aadhar number
        $unique_id = substr($request->input('patient_phone_number'), -4) . '.' . substr($request->input('aadhar_card_num'), -4);
        $patient->unique_id = $unique_id;
    
        // Handle photo upload
        if ($request->hasFile('photo')) {
            $file = $request->file('photo');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->storeAs('photos', $fileName, 'public');
            $patient->photo = 'photos/' . $fileName;
        }
    
        // Handle document uploads
        $documents = ['drivers_license', 'aadhar_card', 'ssn_card', 'pan_card'];
        foreach ($documents as $document) {
            if ($request->hasFile($document)) {
                $file = $request->file($document);
                $fileName = time() . '_' . $file->getClientOriginalName();
                $file->storeAs('documents', $fileName, 'public');
                $patient->$document = 'documents/' . $fileName;
            }
        }
    
        // Generate QR Code
        $qr_text = 'aadhar_card= ' . $request->aadhar_card_num . ', pan_card= ' . $request->pan_card_num;
        $filename = 'qr_code_' . time();
        $dataUri = $this->qrCodeService->saveQrCode($qr_text, $filename);
        $qrCode = explode('/', $dataUri);
    
        if (isset($qrCode[1])) {
            $patient->qr_code = $qrCode[1];
        }
    
        $patient->save();
    
        return redirect()->back()->with('success', 'Patient updated successfully');
    }
    

    public function destroy($id)
    {
        $patient = Patient::findOrFail($id);
        $patient->delete();

        return redirect()->route('patients.index')->with('success', 'Patient deleted successfully');
    }

    public function bulkDelete(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'ids' => 'required|array',
            'ids.*' => 'exists:patient,patient_id',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        Patient::destroy($request->ids);

        return response()->json(['success' => 'Patients deleted successfully.']);
    }


    // public function uploadCsv(Request $request)
    // {
    //     $request->validate([
    //         'csv_file' => 'required|mimes:csv,txt',
    //     ]);

    //     $file = $request->file('csv_file');
    //     $csv = Reader::createFromPath($file->getRealPath(), 'r');
    //     $csv->setHeaderOffset(0);

    //     $records = $csv->getRecords();
    //     $patientsData = [];

    //     foreach ($records as $record) {
    //         $patientsData[] = [
    //             'unique_id' => $record['unique_id'],
    //             'first_name' => $record['first_name'],
    //             'middle_name' => $record['middle_name'] ?? null,
    //             'last_name' => $record['last_name'],
    //             'address' => $record['address'],
    //             'date_of_birth' => $record['date_of_birth'],
    //             'sex' => $record['sex'],
    //             'patient_phone_num_country_code' => $record['patient_phone_num_country_code'] ?? null,
    //             'patient_phone_number' => $record['patient_phone_number'] ?? null,
    //             'patient_er_country_code' => $record['patient_er_country_code'] ?? null,
    //             'patient_er_phone_number' => $record['patient_er_phone_number'] ?? null,
    //             'aadhar_card_num' => $record['aadhar_card_num'] ?? null,
    //             'pan_card_num' => $record['pan_card_num'] ?? null,
    //             'ssn_card_num' => $record['ssn_card_num'] ?? null,
    //             'cibil_score' => $record['cibil_score'] ?? null,
    //             'profession' => $record['profession'] ?? null,
    //             'employment_status' => $record['employment_status'] ?? null,
    //             'marital_status' => $record['marital_status'] ?? null,
    //             'father_name' => $record['father_name'] ?? null,
    //             'mother_name' => $record['mother_name'] ?? null,
    //             'male_siblings' => $record['male_siblings'] ?? null,
    //             'female_siblings' => $record['female_siblings'] ?? null,
    //             'consent_to_contact' => $record['consent_to_contact'],
    //             'medical_billing_address' => $record['medical_billing_address'] ?? null,
    //             'current_medications' => $record['current_medications'] ?? null,
    //             'previous_health_history' => $record['previous_health_history'] ?? null,
    //             'consent_to_treatment' => $record['consent_to_treatment'],
    //             'allergies' => $record['allergies'] ?? null,
    //             'photo' => $record['photo'] ?? null,
    //             'drivers_license' => $record['drivers_license'] ?? null,
    //             'aadhar_card' => $record['aadhar_card'] ?? null,
    //             'ssn_card' => $record['ssn_card'] ?? null,
    //             'pan_card' => $record['pan_card'] ?? null,
    //         ];
    //     }

    //     (new Patient())->bulkInsert($patientsData);

    //     return redirect()->back()->with('success', 'Patients imported successfully.');
    // }

}
