<?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 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 
            ]
        );

        //get agent name
        $agent = User::where('id', $user_id)->first();
        //update the lead user id when select from frontend end.
//   agent will bet a message when assign 
        $mobile='+91'.$agent->phone;
        $curl = curl_init();
        curl_setopt_array($curl, [
        CURLOPT_URL => "https://public.doubletick.io/whatsapp/message/template",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode([
        'messages' => [
        [
        'from' => '+919294929421',
        'to' =>  $mobile,
        'content' => [
        'templateName' => 'medflick_assign_lead',
        'language' => 'en',
        'templateData' => [
        'header' => [
        'type' => 'IMAGE',
        'placeholder' => 'Agent Assignment',
        'mediaUrl' => 'https://quickscale-template-media.s3.ap-south-1.amazonaws.com/org_7dcmlorPdK/8738b874-7a83-4ca6-a14f-36b208512cd0.png'
        ],
        'body' => [
        'placeholders' => [
        "$agent->name",
        "$patient_data->name"
        ]
        ]
        ]
        ]
        ]
        ]
        ]),
        CURLOPT_HTTPHEADER => [
        "Authorization: key_vJpyKeBA1B",
        "accept: application/json",
        "content-type: application/json"
        ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
        //echo "cURL Error #:" . $err;
        } else {
        //echo $response;
        }
        //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]);
        
    }
    
}