<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Hcp;
use App\Models\Patient;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Carbon\Carbon;
use App\Services\LocationService;
use App\Services\QrCodeService;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Models\Role;
class PatientsController extends Controller
{

    protected $locationService;
    protected $qrCodeService;
   
       public function __construct(LocationService $locationService, QrCodeService $qrCodeService)
       {
           
           $this->locationService = $locationService;
           $this->qrCodeService = $qrCodeService;
           
       }
  
    public function index(Request $request){

        
        return view('admin.patient.index');

    }

    public function getDataPatient(){
        $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('admin/patient/' . $patients->patient_id . '/edit') . '" class="btn btn-sm btn-primary me-2">Edit</a>' .
            '<a href="javascript:void(0)" onclick="patentDelete(' . $patients->patient_id . ')"  class="btn btn-sm btn-danger">Delete</a>';

          })
          ->rawColumns(['qr_code', 'action']) 
          ->make(true); 
    }
    public function patientCreate(Request $request){

        $dialingCode = null; 
        $ip = $this->locationService->getPublicIP(); 
  
        $countryCode = $this->locationService->getCountryCodeByIp($ip);
  
        if ($countryCode) {
        
            $dialingCode = $this->locationService->getDialingCode($countryCode);
  
         }
        return view('admin.patient.create', compact('dialingCode'));

    }

    public function patientStore(Request $request){


       
        $validatedData = $request->validate([
            'first_name' => 'required|string|max:50',
            'last_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',
              'aadhar_card_num' => 'required|numeric|unique:patient,aadhar_card_num',
            'pan_card_num' => 'nullable|string|max:20',
            'ssn_card_num' => 'nullable|string|max:20',
            'cibil_score' => 'nullable|integer',
            'consent_to_contact' => 'required|boolean',
            'consent_to_treatment' => 'required|boolean',
          
        ]);

        try { 
        $patient = new Patient();

        $patient->fill($validatedData);
        
        $patient->middle_name = $request->middle_name; 
        $patient->patient_phone_num_country_code = $request->patient_phone_num_country_code; 
        $patient->patient_er_country_code = $request->patient_er_country_code; 
        $patient->patient_er_phone_number = $request->patient_er_phone_number; 
        $patient->profession = $request->profession; 
        $patient->employment_status = $request->employment_status; 
        $patient->marital_status = $request->marital_status; 
        $patient->father_name = $request->father_name; 
        $patient->mother_name = $request->mother_name; 
        $patient->male_siblings = $request->male_siblings; 
        $patient->female_siblings = $request->female_siblings; 
        $patient->medical_billing_address = $request->medical_billing_address; 
        $patient->previous_health_history = $request->previous_health_history; 
        $patient->current_medications = $request->current_medications; 
        $patient->allergies = $request->allergies; 
      
         
      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('drivers_license')) {
            $file = $request->file('drivers_license');
            $fileName = time() . '_' . $file->getClientOriginalName(); 
            $file->storeAs('documents', $fileName, 'public'); 
            $patient->drivers_license = $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; 
        }
     
        if ($request->hasFile('pan_card')) {
            $file = $request->file('pan_card');
            $fileName = time() . '_' . $file->getClientOriginalName(); 
            $file->storeAs('documents', $fileName, 'public'); 
            $patient->pan_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->middle_name) {
            $qr_text .= "Middle Name: " . $request->middle_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->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->patient_er_country_code) {
            $qr_text .= "Emergency Contact Country Code: " . $request->patient_er_country_code . "\n\n";
        }
        if ($request->patient_er_phone_number) {
            $qr_text .= "Emergency Contact Phone Number: " . $request->patient_er_phone_number . "\n\n";
        }
        if ($request->aadhar_card_num) {
            $qr_text .= "Aadhar Card: " . $request->aadhar_card_num . "\n\n";
        }
        if ($request->pan_card_num) {
            $qr_text .= "PAN Card: " . $request->pan_card_num . "\n\n";
        }
        if ($request->ssn_card_num) {
            $qr_text .= "SSN Card: " . $request->ssn_card_num . "\n\n";
        }
        if ($request->cibil_score) {
            $qr_text .= "CIBIL Score: " . $request->cibil_score . "\n\n";
        }
        if ($request->profession) {
            $qr_text .= "Profession: " . $request->profession . "\n\n";
        }
        if ($request->employment_status) {
            $qr_text .= "Employment Status: " . $request->employment_status . "\n\n";
        }
        if ($request->marital_status) {
            $qr_text .= "Marital Status: " . $request->marital_status . "\n\n";
        }
        if ($request->father_name) {
            $qr_text .= "Father's Name: " . $request->father_name . "\n\n";
        }
        if ($request->mother_name) {
            $qr_text .= "Mother's Name: " . $request->mother_name . "\n\n";
        }
        if ($request->male_siblings) {
            $qr_text .= "Male Siblings: " . $request->male_siblings . "\n\n";
        }
        if ($request->female_siblings) {
            $qr_text .= "Female Siblings: " . $request->female_siblings . "\n\n";
        }
        if ($request->consent_to_contact) {
            $qr_text .= "Consent to Contact: " . $request->consent_to_contact . "\n\n";
        }
        if ($request->medical_billing_address) {
            $qr_text .= "Medical Billing Address: " . $request->medical_billing_address . "\n\n";
        }
        if ($request->current_medications) {
            $qr_text .= "Current Medications: " . $request->current_medications . "\n\n";
        }
        if ($request->previous_health_history) {
            $qr_text .= "Previous Health History: " . $request->previous_health_history . "\n\n";
        }
        if ($request->consent_to_treatment) {
            $qr_text .= "Consent to Treatment: " . $request->consent_to_treatment . "\n\n";
        }
        if ($request->allergies) {
            $qr_text .= "Allergies: " . $request->allergies . "\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";
        }
        
        $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();
        Log::info('patient create Successful.');
        return redirect()->route('admin.patient')->with('success', 'Patient added successfully.');
        
    } catch (\Throwable $th) {
        Log::error('Error patient create: ' . $th->getMessage());
        return redirect()->back()->with('error', 'An error occurred while patient the create.');
    }

    }
    

    public function patientDelete($id){
   
       $delete =  Patient::findOrFail($id);
       
       $filePath = 'qr_codes/' . $delete->qr_code; 
      
       if (Storage::disk('public')->exists($filePath)) {
        Storage::disk('public')->delete($filePath);
        if (!Storage::disk('public')->exists($filePath)) {
            
        }
    }
    $delete->delete();
       return redirect()->route('admin.patient')->with('success', 'Patient Delete successfully.');
    }



    public function patienEdit(Request $request, $id){
        $Patientdata = Patient::find($id);
         $roles = Role::all(); // Sabhi roles fetch karna
       return view('admin.patient.edit', compact('Patientdata', 'roles'));
}
public function patienUpdate(Request $request, $id){

    $validatedData = $request->validate([
        'first_name' => 'required|string|max:50',
        'last_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',
        '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',
        'consent_to_contact' => 'required|boolean',
        'consent_to_treatment' => 'required|boolean',
      
    ]);

    try { 
        
        $patient = Patient::findOrFail($id);
    
     $patient->update($request->except(['unique_id', 'photo', 'drivers_license', 'aadhar_card', 'ssn_card', 'pan_card']));

    
    $patient->middle_name = $request->middle_name; 
    $patient->patient_phone_num_country_code = $request->patient_phone_num_country_code; 
    $patient->patient_er_country_code = $request->patient_er_country_code; 
    $patient->patient_er_phone_number = $request->patient_er_phone_number; 
    $patient->profession = $request->profession; 
    $patient->employment_status = $request->employment_status; 
    $patient->marital_status = $request->marital_status; 
    $patient->father_name = $request->father_name; 
    $patient->mother_name = $request->mother_name; 
    $patient->male_siblings = $request->male_siblings;  
    $patient->female_siblings = $request->female_siblings; 
    $patient->medical_billing_address = $request->medical_billing_address; 
    $patient->previous_health_history = $request->previous_health_history; 
    $patient->current_medications = $request->current_medications; 
    $patient->allergies = $request->allergies; 
    
     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;
        }
        
     
  
    if ($request->hasFile('photo')) {
        $file = $request->file('photo');
        $fileName = time() . '_' . $file->getClientOriginalName(); 
        $file->storeAs('photos', $fileName, 'public');
        $patient->photo = $fileName;
    }

    if ($request->hasFile('drivers_license')) {
        $file = $request->file('drivers_license');
        $fileName = time() . '_' . $file->getClientOriginalName(); 
        $file->storeAs('documents', $fileName, 'public'); 
        $patient->drivers_license = $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; 
    }
 
    if ($request->hasFile('pan_card')) {
        $file = $request->file('pan_card');
        $fileName = time() . '_' . $file->getClientOriginalName(); 
        $file->storeAs('documents', $fileName, 'public'); 
        $patient->pan_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->middle_name) {
            $qr_text .= "Middle Name: " . $request->middle_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->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->patient_er_country_code) {
            $qr_text .= "Emergency Contact Country Code: " . $request->patient_er_country_code . "\n\n";
        }
        if ($request->patient_er_phone_number) {
            $qr_text .= "Emergency Contact Phone Number: " . $request->patient_er_phone_number . "\n\n";
        }
        if ($request->aadhar_card_num) {
            $qr_text .= "Aadhar Card: " . $request->aadhar_card_num . "\n\n";
        }
        if ($request->pan_card_num) {
            $qr_text .= "PAN Card: " . $request->pan_card_num . "\n\n";
        }
        if ($request->ssn_card_num) {
            $qr_text .= "SSN Card: " . $request->ssn_card_num . "\n\n";
        }
        if ($request->cibil_score) {
            $qr_text .= "CIBIL Score: " . $request->cibil_score . "\n\n";
        }
        if ($request->profession) {
            $qr_text .= "Profession: " . $request->profession . "\n\n";
        }
        if ($request->employment_status) {
            $qr_text .= "Employment Status: " . $request->employment_status . "\n\n";
        }
        if ($request->marital_status) {
            $qr_text .= "Marital Status: " . $request->marital_status . "\n\n";
        }
        if ($request->father_name) {
            $qr_text .= "Father's Name: " . $request->father_name . "\n\n";
        }
        if ($request->mother_name) {
            $qr_text .= "Mother's Name: " . $request->mother_name . "\n\n";
        }
        if ($request->male_siblings) {
            $qr_text .= "Male Siblings: " . $request->male_siblings . "\n\n";
        }
        if ($request->female_siblings) {
            $qr_text .= "Female Siblings: " . $request->female_siblings . "\n\n";
        }
        if ($request->consent_to_contact) {
            $qr_text .= "Consent to Contact: " . $request->consent_to_contact . "\n\n";
        }
        if ($request->medical_billing_address) {
            $qr_text .= "Medical Billing Address: " . $request->medical_billing_address . "\n\n";
        }
        if ($request->current_medications) {
            $qr_text .= "Current Medications: " . $request->current_medications . "\n\n";
        }
        if ($request->previous_health_history) {
            $qr_text .= "Previous Health History: " . $request->previous_health_history . "\n\n";
        }
        if ($request->consent_to_treatment) {
            $qr_text .= "Consent to Treatment: " . $request->consent_to_treatment . "\n\n";
        }
        if ($request->allergies) {
            $qr_text .= "Allergies: " . $request->allergies . "\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";
        }
        
        $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();
    $patient->syncRoles($request->roles);
    Log::info('patient update Successful.');
    return redirect()->route('admin.patient')->with('success', 'Patient update successfully.');
    
} catch (\Throwable $th) {

    Log::error('Error patient update: ' . $th->getMessage());
    return redirect()->back()->with('error', 'An error occurred while patient the update.');
}
}
}