<?php

namespace App\Http\Controllers\Hcp;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Patient;
use App\Models\PatientAllergies;
use App\Models\PatientVitals;
use App\Models\PatientHealthHistory;
use App\Models\Hcp;
use App\Models\Lab;
use App\Models\Radiology;
use App\Models\FavouritePatient;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Storage;  
use App\Services\TwilioService;
use App\Services\LocationService;
use Illuminate\Support\Facades\Log;
class HcpController extends Controller
{

 protected $twilioService;
 protected $locationService;

    public function __construct(TwilioService $twilioService, LocationService $locationService)
    {
        
        $this->twilioService = $twilioService;
        $this->locationService = $locationService;
        
    }
  
  public function login(){
        return view('hcp.login');
   } 
   
public function register(Request $request)
{
    // Save previous URL into session
    session(['previous_url' => url()->previous()]);
    return view('hcp.register');
}


public function signup(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|string|max:50',
        'first_name' => 'required|string|max:50',
        'last_name' => 'required|string|max:50',
        'patient_phone_num_country_code' => 'required|string',
        'contact_phone_office' => 'required|string|max:20',
        'email' => 'required|email|max:100|unique:hcp,email',
        'address' => 'required|string',
        'school_graduated' => 'required|string|max:100',
        'password' => 'required|string|min:8',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp',
    ]);

    try {
        $validatedData['phone_number'] = $validatedData['patient_phone_num_country_code'] . ' ' . $validatedData['contact_phone_office'];

        if ($request->hasFile('image')) {
            $photoPath = $request->file('image')->store('hcp/photos', 'public');
            $validatedData['image'] = $photoPath;
        }

        $validatedData['password'] = Hash::make($validatedData['password']);

        $hcp = Hcp::create($validatedData);

        Auth::guard('hcp')->login($hcp);

        // Get second previous URL from session
        $secondPrevious = session('previous_url');

        // For debugging
        // dd(['referer' => $request->headers->get('referer'), 'secondPrevious' => $secondPrevious]);

        // Redirect condition
      if ($secondPrevious && str_contains($secondPrevious, 'https://blunotes.bluai.ai/')) {
    return response()->json([
        'message' => 'Registration successful from blunotes!',
    ]);
}

return redirect()->route('hcp.dashboard')->with('success', 'Registration successful!');  
    } catch (\Exception $e) {
        if (isset($photoPath)) {
            Storage::disk('public')->delete($photoPath);
        }

        Log::error('HCP Registration Error: ' . $e->getMessage());

        return redirect()->back()
            ->with('error', 'Registration failed: ' . $e->getMessage())
            ->withInput();
    }
}
  
   
   public function signin(Request $request)
{ 

  
    $validator = Validator::make($request->all(), [
        'email' => 'required|email|regex:/\.[a-z]{2,}$/i',
        'password' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

    try {
        $checkAdmin = Hcp::where('email', $request->email)->first();

        if (!$checkAdmin) {
            return redirect()->back()->withErrors(['email' => 'This email is not registered.'])->withInput();   
        } 

        $credentials = $validator->validated();

        // Use Hash::check to verify the password
        if (Hash::check($credentials['password'], $checkAdmin->password)) {
            Auth::guard('hcp')->login($checkAdmin); // Log the user in
            Log::info('Hcp login successful.');
            return redirect()->route('hcp.dashboard')->with('success', 'Hcp login successfully!'); 
        } else {
            return redirect()->back()->withErrors(['password' => 'The password you entered is incorrect.'])->withInput();
        }
    } catch (\Throwable $th) {
        Log::error('Error login Hcp: ' . $th->getMessage());
        return redirect()->back()->with('error', 'An error occurred while logging in the Hcp.');
    }
}



public function favouriteRemove(Request $request)
{
    // Validate the incoming request
    $request->validate([
        'favourite_id' => 'required|integer|exists:favourite_patients,id',
    ]);

    // Attempt to delete the favourite record
    $isDeleted = FavouritePatient::where('id', $request->input('favourite_id'))->delete();

    // Return response based on the result
    if ($isDeleted) {
        return response()->json([
            'status' => 'success',
            'message' => 'Favourite removed successfully.',
        ]);
    }

    return response()->json([
        'status' => 'error',
        'message' => 'Failed to remove favourite.',
    ], 500); // Return HTTP 500 for failure
}
 
    
public function dashboard()
{
    try {
        $hcp = Auth::guard('hcp')->user();

        if (!$hcp) {
            return redirect()->route('hcp.login')->with('error', 'Please log in to access the dashboard.');
        }


            
           
        return view('hcp.index');
    } catch (\Exception $e) {
        \Log::error('Dashboard error: ' . $e->getMessage());
        return redirect()->route('hcp.login')->with('error', 'An unexpected error occurred. Please try again later.');
    }
}
 
public function favourite_patient(Request $request)
{
    try {
        // Ensure the user is authenticated
        $hcp = Auth::guard('hcp')->user();

        if (!$hcp) {
            return response()->json(['error' => 'Unauthorized access. Please log in.'], 401);
        }

        // Query the favourite patients with the necessary relationships
        $query = FavouritePatient::with('patient')
            ->where('hcp_id', $hcp->hcp_id);

        // Apply server-side processing
        return datatables($query)
            ->addColumn('favorite', function ($favouritePatient) {
            return '<i class="mdi mdi-heart text-danger remove_icon" data-id="' . $favouritePatient->id . '"></i>';
           })
            ->addColumn('first_name', function ($favouritePatient) {
                return $favouritePatient->patient->first_name ?? 'N/A'; // Ensure this field exists in the Patient model
            })
            ->addColumn('last_name', function ($favouritePatient) {
                return $favouritePatient->patient->last_name ?? 'N/A'; // Ensure this field exists in the Patient model
            })
            ->addColumn('date_of_birth', function ($favouritePatient) {
                return $favouritePatient->patient->date_of_birth ?? 'N/A'; // Ensure this field exists in the Patient model
            })
            ->addColumn('last_visit', function ($favouritePatient) {
                return $favouritePatient->date ?? 'N/A'; // Ensure this field exists in the Patient model
            })
            ->addColumn('login', function ($favouritePatient) {
                return '<a href="' . route('hcp.patients', ['id' => $favouritePatient->patient_id]) . '" class="btn btn-sm btn-primary">Login</a>';
            })
            ->rawColumns(['favorite', 'login']) // Allow HTML in these columns
            ->make(true);

    } catch (\Exception $e) {
        \Log::error('Favourite Patient error: ' . $e->getMessage());
        return response()->json(['error' => 'An unexpected error occurred. Please try again later.'], 500);
    }
}


   
   
       public function logout(Request $request)

    { 
        Auth::guard('hcp')->logout(); 
        session()->invalidate();
        session()->regenerateToken();
        return redirect('/hcp/login');   
 
    }
    
    
     public function patients($id = null){
      $patient = null;
      if ($id) {
        $patient = Patient::find($id); 
    
       }
     
         return view('hcp.patients_login', compact('patient'));
   } 
   public function mentalhealthpatientsView($id = null){
      $patient = null;
      if ($id) {
        $patient = Patient::find($id); 
    
       }
     
         return view('hcp.mental-health-login', compact('patient'));
   } 
   public function mentalhealthpatients(Request $request){
   
        
    $request->validate([
        'phone' => 'required',
        'identifier' => 'required',
    ]);
 
    try {
        // Find the patient using the correct query
        $patient = Patient::where([
            'patient_phone_number' => $request->phone,
            'aadhar_card_num' => $request->identifier
        ])->first();
 
        if ($patient) {
            Auth::guard('mental-health')->login($patient);  
            $patient = Auth::guard('mental-health')->user();
 
            return response()->json([
                'message' => 'Login successful!',
                'redirect' => route('mentalHealth.dashboard')
            ]);
        } else {
            return response()->json(['error' => 'mental-health not found'], 404);
        }
    } catch (Exception $e) {
        return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
    }
    
   }
   
   
  
   
    public function sendOTP(Request $request)
    {
    
          
       
        $query = Patient::where(['patient_phone_number' => $request->phone, 'patient_phone_num_country_code' => $request->CountryCode]);

        $recordCount = $query->count(); 
        $patient = '';
        if ($recordCount === 1) {
            $patient = $query->first();

        } elseif ($recordCount > 1 ) {

            $patient = $query->where(function ($query) use ($request) {
                $query->where('aadhar_card_num', $request->identifier);
            })->first();

            if(!$request->has('identifier')){ 

            return response()->json(['message' => 'Please Enter Aadhar Card Number', 'status' => true]);
            } 
        } 
        
       
        if (!$patient || $patient === null) {
            return response()->json(['message' => 'Not Registerd, Please Registered As A New patient.', 'status' => true]);
        }
    
        $otp = rand(100000, 999999);
        //$phone = $patient->patient_phone_num_country_code.''.$request->phone;
       
        Session::put('otp', $otp);
       // $this->twilioService->sendOtpViaSms($phone, $otp);
 
        return response()->json(['message' => 'OTP Sent To Message Box!','status' => false]); 
    }
  

    public function whatappsendOTP(Request $request)
    {
    
        $query = Patient::where('patient_phone_number', $request->phone);

        $recordCount = $query->count();
        $patient = '';
        if ($recordCount === 1) {
            $patient = $query->first();

        } elseif ($recordCount > 1 ) {

            $patient = $query->where(function ($query) use ($request) {
                $query->where('aadhar_card_num', $request->identifier);
            })->first();

            if(!$request->has('identifier')){ 

            return response()->json(['message' => 'Please Enter Aadhar Card Number', 'status' => true]);
            } 
        } 
     
        if (!$patient || $patient === null) {
            return response()->json(['message' => 'Invalid credentials.', 'status' => true]);
        }

        $otp = rand(100000, 999999);
        $phone = $patient->patient_phone_num_country_code.''.$request->phone;
        Session::put('otp', $otp);
        $this->twilioService->sendOtp($phone, $otp); 
        
        return response()->json(['message' => 'OTP sent successfully!']); 
    }

    public function verifyOTP(Request $request) 
    {
           $inputOTP = $request->otp;
    $sessionOTP = Session::get('otp');

    //if ($inputOTP != $sessionOTP || $inputOTP == null) { 
   //     return response()->json(['message' => 'Invalid OTP', 'status' => true]);
   // } else {
        // Identify the patient using phone and country code
        $query = Patient::where([
            'patient_phone_number' => $request->patient_phone_number,
            'patient_phone_num_country_code' => $request->patient_phone_num_country_code
        ]);
 
        $recordCount = $query->count(); 
       
        $aadharNumbers = [];

    if ($recordCount === 1) {
    $record = $query->first();
    $aadharNumbers[] = [
        'first_name' => $record->first_name,
        'aadhar_card_num' => $record->aadhar_card_num
    ];
} elseif ($recordCount > 1) {
    $aadharNumbers = $query->select('first_name', 'aadhar_card_num')->get()->toArray();
}

return response()->json([
    'message' => 'OTP Verified',
    'status' => true, // Change to true if OTP is verified
    'aadharNumbers' => $aadharNumbers
]);
   // }
    }

    public function patienthcplogin(Request $request){
   
         
        $request->validate([
            'phone' => 'required',
            'identifier' => 'required',
        ]);
     
        try {
            // Find the patient using the correct query
            $patient = Patient::where([
                'patient_phone_number' => $request->phone,
                'aadhar_card_num' => $request->identifier
            ])->first();
     
            if ($patient) {
               Auth::guard('patients')->login($patient);  
            $patient = Auth::guard('patients')->user(); 
     
                return response()->json([
                    'message' => 'Login successful!',
                    'redirect' => route('mentalHealth.dashboard')
                ]);
            } else {
                return response()->json(['error' => 'mental-health not found'], 404);
            }
        } catch (Exception $e) {
            return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
        }
        
       }
   
}