<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PatientJourney;
use App\Models\User;
use App\Models\Patient;
use App\Models\Lead;
use App\Models\PatientReports;
use App\Models\Speciality;
use App\Models\patientJourneyConversation;
use Hash;
use Storage;
use DB;
use Validator;
class PatientJourneyController extends Controller
{
    public function __construct(){
        $this->use = new User;
        $this->patient= new Patient;
    }
    
    public function getpatientagentId($user_id, $id){
        
        $jsondata =[];
        $data = Lead::where(['id'=>$id])->select('form_data', 'id','patient_name','patient_email','patient_phone')->first();
        //store patient data on behalf of leads id
        $formData= $data->form_data;
      
         $dataArray = json_decode($formData, true);
            $name = '';
            $email = '';
            $phone = '';
        if(!is_null($dataArray)) {
            foreach ($dataArray as $field) {
                $jsondata=[];
                if($field['name']=='full_name'){
                $name = implode(", ", array_map('htmlspecialchars', $field['values']));
                }
                if($field['name']=='email'){
                    $email =  implode(", ", array_map('htmlspecialchars', $field['values']));
                }
                if($field['name']=='phone_number'){
                    $phone =  implode(", ", array_map('htmlspecialchars', $field['values']));
                }
             $jsondata= ['name'=>$name, 'email'=>$email, 'phone'=>$phone, 'country'=>'', 'username'=>$phone, 'password'=>Hash::make($phone)];
            }
        } else {
            $jsondata= ['name'=>$data->patient_name, 'email'=>$data->patient_email, 'phone'=>$data->patient_phone, 'country'=>'', 'username'=>$data->patient_phone, 'password'=>Hash::make($data->patient_phone)];
        }
        //medflick data entry

             $curl = curl_init();
                curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://dev.medflick.com/api/free_consultants',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>$jsondata,
                CURLOPT_HTTPHEADER => array(
                'Cookie: XSRF-TOKEN=eyJpdiI6IjJLS3RZZExhOHppRXJUMDhpdnVzU1E9PSIsInZhbHVlIjoiMWliR05KY01MYVQreHZLeDh5MTI1Y0VPQjNISDdCbzF3aVlOcWFzMkJzZUFSQkNack5VU2VjdUFvUzBtc25hcGF6WGVhOGhzUzZGQnRieU43UzlTczRUZUNsQmFMTmFsR0xDcmgrcStqS2sya2VCQ1ovd0wzM1BlUjBUSkF5MEQiLCJtYWMiOiJmNjc2NmZhMmM2YWE4NjE5ZTExZjNjNzBlMjVlZTBkMzM4ODUxODMxNTdjOTA1ODIyNDExMmJhMjA3ZWVjZTVkIiwidGFnIjoiIn0%3D; medflick_session=eyJpdiI6InJrYkVCSERLYUZLaU1VeXAvalMwTHc9PSIsInZhbHVlIjoiVm9yUFZYVVo4aDkvbGVRSWR1cEQ0YnFOekVZNW1nc3lWSlFzSDJ3WXU5aVRCNEFma1Q2OFMzQU5DNXIxcHlzQ2FFd0RmOGM0UldVdlM5YTVPc0VsOFdkQzNmMmlBbzdTMU1JeDBUYkM2SHdLNmxxQlFvc2Vic2xhbkNJMnVGTXkiLCJtYWMiOiI1NGUxYzcyODBmYmY0ZDJjN2MyNzI2ZWI0YmRiNzQzNzAzMDViMDE4MzcxMzllYjExNGQzMDNhMjgzMmEzNDk0IiwidGFnIjoiIn0%3D'
                ),
                ));
                $response = curl_exec($curl);
                curl_close($curl);  

        //medflick data entry    end
               
        $patient_data =Patient::updateOrCreate([ 'phone'   => $phone, 'email'=>$email], $jsondata);
         //store patietn data on behalf of leads id end
        //update the lead user id when select from frontend.
        $update = Lead::where(['id'=>$id])->update(
            [
            'user_id' =>$user_id, 'patient_id'=>$patient_data->id, 'assigned_by'=>1, 'assigned_to'=>$user_id,
            'patient_name'=>$patient_data->name, 'patient_email' =>$patient_data->email, 'patient_phone'=>$patient_data->phone 
            ]
        );
        //update the lead user id when select from frontend end.

        //insert data into patient journey
        $patientJourney = PatientJourney::updateOrCreate([ 'patient_id'   => $patient_data->id],
        
                          ['patient_id'=>$patient_data->id,'user_id' =>$user_id]);
                          
         //insert data into patient journey end
        return response()->json(['message'=>'Patient journey created, lead updated and patient table data feed', 'patientJourney'=>$patientJourney,
                   'patient'=>$data, 'lead updated'=>$update
                ]);
    }

    public function getLeadsbyUserId($user_id){
        $jsondata=[];
  
        $leads = Lead::where(['user_id'=>$user_id])->get();
        $jsondata= $leads;
        return response()->json(['data'=>$jsondata]);
    }

    //get patient detail lead detail 

    public function getLeadDetails($lead_id){
       
       $jsondata =[]; 
  
    
       $lead= Lead::where(['id'=>$lead_id])->first();
       
       $patient = Patient::where(['id'=>$lead->patient_id])->first();
       
       $user = User::where(['id'=>$lead->user_id])->get();
       
       $patientJourneydata = PatientJourney::where(['patient_id'=>$lead->patient_id])->first();
       
       $patientReport = PatientReports::where('patient_id', $lead->patient_id)->get();

       $patient_speciality = Speciality::where('id', $lead->speciality_id)->select('id', 'name', 'created_at')->first();
       
       $jsondata = ['lead_data'=>$lead, 'patient'=>$patient, 'user'=>$user, 'patientJourneydata'=>$patientJourneydata,
        'patientReport'=>$patientReport, 'patient_speciality'=>$patient_speciality];
       return response()->json( $jsondata );
       
    }

    public function UploadPatientReportUpload(Request $request){
        
        $jsondata=[];
        if($request->hasFile(key: 'file')){
            $file = $request->file(key: 'file');
            $report =uniqid().str_ireplace(' ','-', $file->getClientOriginalName()); 
            $file->storeAs('crm/patientReport/', $report);
            } else {
            $report = null ; 
        } 
        $patient_id = $request->patient_id;
        $user_id = $request->user_id;

        $patientReport = PatientReports::create([
                       'patient_id' =>$patient_id,
                       'user_id' =>$user_id,
                       'reports' =>env('AWS_CLOUDFLARE_URL')."/crm/patientReport/$report"
        ]);
        
        $jsondata=$patientReport;
        return response()->json(['data'=>$jsondata]);
        
    }

    public function patientReportDelete($report_id){
          
        $reportDelete = PatientReports::where('id', $report_id)->delete();
        if($reportDelete){
            return response()->json(['message'=>'report deleted successfully']);
        } else {
            return response()->json(['error'=>'Somethimg error, report not deleted']);
        }
    }

    public function assignSpecialityPatient(Request $request){
        
        $jsondata=[];
        $validator = Validator::make($request->all(),[
            'patient_id' => 'required',
            'user_id' => 'required',
            'lead_id' => 'required',
            'speciality_id' => 'required',
            'speciality_name' => 'required'
        ]);
        
        $patient_id = $request->patient_id;
        $user_id = $request->user_id;
        $lead_id = $request->lead_id;
        $speciality_id = $request->speciality_id;
        $speciality_name = $request->speciality_name;
        
        //patient journey
        $patient_journey = PatientJourney::where('patient_id', $patient_id)->update([
            'speciality_id' =>$speciality_id
        ]);
        
        // $patient_journey = PatientJourney::updateOrcreate(['patient_id'=>$patient_id],[
            
        //     'speciality_id'  =>$speciality_id,
            
        // ]);
        //lead speciality update
        $lead_spec = Lead::where('patient_id', $patient_id)->update([
            'speciality_id' =>$speciality_id
        ]);
        //speciality
        $speciality = Speciality::updateOrcreate(['id'=>$speciality_id],[
            
            'name'  =>$speciality_name,
            'status'=>1 
        ]);

        $jsondata=['patient_journey'=>$patient_journey, 'speciality'=>$speciality, 'lead_spec'=>$lead_spec];
        return response()->json($jsondata);
        if($jsondata){
            return response()->json(['message'=>'data updated']);
        } else {
            return response()->json(['error' =>'Something went wrong']);
        }
    }

    public function patientHealthIssue(Request $request) {
        
        $validator = Validator::make($request->all(),[
            'patient_id' => 'required',
            'health_issue' => 'required',
            'description' => 'required'
        ]);
        $patient_id = $request->patient_id;
        $user_id  = $request->user_id;
        $review_reported_by = 'Medflick';
        $health_issue = $request->health_issue;  // in enum field yes or no  
        $description = $request->description;
        //update patient health issue in patient journey

        $patient_health_issue_journey_journey = PatientJourney::where('patient_id', $patient_id)->update([
            'health_issue' =>$health_issue, 'description' =>$description, 'review_reported_by' =>$review_reported_by
        ]);

        //patient journey conversation
        $patient__journey_id = PatientJourney::where(['patient_id' => $patient_id, 'user_id' =>$user_id])->first();
         
        $conversation = patientJourneyConversation::create([
        
             'patient_id'=>$request->patient_id,
             'user_id'  => $request->user_id,
             'patient_journey_id' => $patient__journey_id->id,
             'health_description' =>  $request->description,
             'status'  => '1'
        ]);
        
        if($conversation){
            return response()->json(['message'=>'Conversation successfully updated', 'conversation' => $conversation]);
        } else {
            return response()->json(['error' =>'Something went wrong']);
        }
    }
    
    public function getConversation($patient_id, $user_id, $patient_journey_id){
        $jsondata=[];
        $convrsation_list = patientJourneyConversation::where(['patient_id'=>$patient_id, 'user_id'=>$user_id, 'patient_journey_id'=>$patient_journey_id])->orderBy('id', 'desc')->get();
        $jsondata = $convrsation_list;
        return response()->json(['data'=>$jsondata]);
    }
    
}