<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\PatientNotification;
use App\Models\Lablogin;
use App\Models\Labtest;

use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function sendNotification()
    {
        $message = 'Notification geting!';
        event(new NotificationEvent($message));

        return response()->json(['success' => utf8_encode('Notification Sent!')]);
    }
    
    
    
public function getNotifications()
{ 
    $patient = Auth::guard('patients')->user(); 

    $notifications = PatientNotification::where('patient_id', $patient->patient_id)
        ->orderBy('created_at', 'desc')
        ->limit(10)
        ->get();

    return response()->json(['notifications' => $notifications]);
}

public function getAllLabs(Request $request)
{ 
    $query = strtolower($request->input('search')); // Convert input to lowercase

    $results = Lablogin::whereRaw("LOWER(first_name) LIKE ?", ["%{$query}%"])
                ->limit(10)
                ->get();
    
    return response()->json(['results' => $results]);
}


 
 public function clearNotifications(Request $request)
    {
       $patient = Auth::guard('patients')->user(); 
        // Delete only the notifications for the given patient
        PatientNotification::where('patient_id', $patient->patient_id)->delete(); 

        return response()->json(['success' => true, 'message' => 'Notifications cleared successfully!']);
    }
    
public function saveSelectedLab(Request $request)
{
    $patient = Auth::guard('patients')->user();

    // Check if this lab is already assigned to the patient
    $existingLab = Labtest::where('patient_id', $patient->patient_id)
        ->where('lablogin_id', $request->labLogin)
        ->first();

    if ($existingLab) {
        return response()->json(['success' => false, 'message' => 'Lab already selected!']);
    }

    // Save the selected lab for the patient
    Labtest::create([
        'patient_id' => $patient->patient_id,
        'lab_id' => $request->lab_id,
        'lablogin_id' => $request->labLogin
    ]);

    return response()->json(['success' => true, 'message' => 'Lab saved successfully!']);
}

    
    
}
  