<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Helpers\SalesforceHelper;
use App\Helpers\CommonHelper;
use App\Helpers\WpAPI;
use App\User;
use Validator;
use Hash;
use Config;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\File;
use App\Models\AccessToken;
use App\Models\LogsAPIs;
use App\Models\CheifComplainTypes;
use App\Models\Questions;
use App\Models\QuestionOptions;
use App\Models\PatientDetails;
use App\Models\PatientNarratives;
use App\Models\PatientCheifComplainAnswers;
use App\Models\QuestionBranchingLogic;
use App\Models\QuestionCategories;
use App\Models\SurgeonPatientComplainAnswers;
use App\Models\PendingQuestions;
use App\Models\MultiSelectPicCoordinates;


use App\Models\UserDevices;

use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;
use Auth;

class PatientController extends Controller
{
  /**
     * Create a new controller instance.
     *
     * @return void
     */
  public $data = array();
  public $api_log_id = 0;
  public $api_start_time = 0;
  public $current_request;

  public function __construct(Request $request)
  {
    $this->current_request = $request;
    $return = CommonHelper::contructLog($request);
    if(isset($return['api_start_time']))
    {
      $this->api_start_time = $return['api_start_time'];
    }
    if(isset($return['api_log_id']))
    {
      $this->api_start_time = $return['api_log_id'];
    }
  }

  public function saveSearchQuestion(Request $request)
  { 
    
    $optionData    = json_decode($request['data'],true);

    $patient_id    = $request['patient_id'];
    $complain_id   = $request['complain_id'];
    $surgeon_id    = $request['surgeon_id'];
    $narrativeData = PatientNarratives::where('patient_id',$patient_id)->where('complain_type_id',$complain_id)->first();
    $narrative_id  = $narrativeData->id;
    $questionData  = Questions::find($optionData['question_id']);

    $category_id   = $questionData->category_id;
    if(isset($optionData['required_input_text']))
    {
      $optionData['narrative_text'] = str_replace("<x>",$optionData['required_input_text'] , $optionData['narrative_text']);
    }
   
    //dd($narrative_id);
    $surgeonPatientComplainAnswers = new SurgeonPatientComplainAnswers();

    $surgeonPatientComplainAnswers->patient_id            = $patient_id;
    $surgeonPatientComplainAnswers->complain_id           = $complain_id;
    $surgeonPatientComplainAnswers->surgeon_id            = $surgeon_id;
    $surgeonPatientComplainAnswers->narrative_id          = $narrative_id;
    $surgeonPatientComplainAnswers->option_id             = $optionData['id'] ;
    $surgeonPatientComplainAnswers->narrative_text        = $optionData['narrative_text'] ;
    $surgeonPatientComplainAnswers->question_id           = $optionData['question_id'] ;
    $surgeonPatientComplainAnswers->sort_order            = $optionData['sort_order'] ;
    $surgeonPatientComplainAnswers->category_id           = $category_id;
    $surgeonPatientComplainAnswers->required_input_text   = @$optionData['required_input_text'];
    $surgeonPatientComplainAnswers->save();

    if ($surgeonPatientComplainAnswers->id) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $surgeonPatientComplainAnswers;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '400';
      $data["header"]["message"]  = "Invalid Parameters";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 

  }
  
  public function savePendingQuestion(Request $request)
  { 
    

    $complain_id   = $request['complain_id'];
    $surgeon_id    = $request['surgeon_id'];
    $patient_id    = $request['patient_id'];
    $category_id   = config('constants.DEFAULT_QUESTION_CATEGORY_ID');
    $title         = $request['title'];
    $response      = $request['response'];
    //dd($narrative_id);
    $pendingQuestions = new PendingQuestions();

    $pendingQuestions->complain_id  = $complain_id;
    $pendingQuestions->surgeon_id   = $surgeon_id;
    $pendingQuestions->category_id  = $category_id;
    $pendingQuestions->title        = $title;
    $pendingQuestions->response     = $response;
    $pendingQuestions->patient_id   = $patient_id;

   
    $pendingQuestions->save();

    if ($pendingQuestions->id) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $pendingQuestions;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '400';
      $data["header"]["message"]  = "Invalid Parameters";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 

  }
  
  public function deletAdditionalInfo(Request $request)
  {
    $id                   = $request['id'];
    $additional_response  = $request['additional_response'];
    if($additional_response==1)
    {
      PendingQuestions::where('id',$id)->delete();
    }
    else
    {
      SurgeonPatientComplainAnswers::where('id',$id)->delete();
    }
    
    $data["header"]["error"]    = '0';
    $data["header"]["message"]  = "Success";
    $data['body']['details']    = $id;
    // $data['body']['details']   = $PatientNarratives;
    return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
   

  }

  public function getAdditionalPatientNarrative(Request $request)
  {
    $patient_id   = $request['patient_id'];
    $_patientAdditionalNarrative = SurgeonPatientComplainAnswers::where('patient_id',$patient_id)->get()->toArray();
    $patientAdditionalNarrative = array();
    foreach ($_patientAdditionalNarrative as $key => $row) 
    { 
      $row['additional_response'] = 0;
      $patientAdditionalNarrative[] = $row;
    }
    $pateitResponse = PendingQuestions::where('patient_id',$patient_id)->get()->toArray();
    if($pateitResponse)
    foreach ($pateitResponse as $key => $row) 
    { 
      $row['narrative_text'] = $row['response'];
      $row['additional_response'] = 1;
      $patientAdditionalNarrative[] = $row;
    }
    if (!empty($patientAdditionalNarrative)) 
    { 
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $patientAdditionalNarrative;
      // $data['body']['details']   = $PatientNarratives;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 

  }

//   public function saveNarrativesByPatientID(Request $request)
//   { 
    
//     $input     = json_decode($request['data'],true);
//     $response   = array();
//     $errors   = array();
//     if(!empty($input))
//     { 
      
//       // dd($input['answers']);
//       $isUpdate = 1;
//       $email='';
//       $isExport=0;
//       $PatientId  = $input['patient_id'];

//         //dd($PatientId);
//       $narrativeSummary = $input['narrative_summary'];
//       $answers        = $input['answers'];

//       if(!$answers)
//       {
//         $errors[] = "Answers Is Required";
//       }
//       if(!$narrativeSummary)
//       {
//         $errors[] = "Narrative Summary Is Required";
//       }
//       if(empty($errors))
//       {
//         if($answers)
//         {

//           $this->addPatientNarrative($answers,$PatientId,$addAnother=1);
//           PatientDetails::updateOrCreate(['id' => $PatientId],
//             array(
//               'narrative_summary' =>$narrativeSummary,
//               'status' =>config('constants.CONSTANT_STATUS_ACTIVE')
//             )
//           );
//         }
//         $response[]  = "Patient Narrative Has Been Saved Successfully";   
//       }
//     }
//     if (!empty($response)) 
//     {
//       $data["header"]["error"]    = '0';
//       $data["header"]["message"]  = "Success";
//       $data['body']['details']    = $response;
//       return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
//     }
//     else
//     {
//       $data["header"]["error"]    = '1';
//       $data["header"]["message"]  = $errors;
//       return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
//     } 
//   }


  public function updatePatientNarrative($answers,$narrative_id,$_narrativeSummary,$patient_additional_info='',$allComplaints="",$newData='')
  { 
    $optionData = PatientCheifComplainAnswers::where('narrative_id',$narrative_id);
    // $optionData = PatientCheifComplainAnswers::find($narrative_id);
    $optionData->delete();
    //dd($answer['optionData']);
    foreach ($answers as $k2 => $answer) 
    {
    //   $optionData = $answer['optionData'];
    //   $complain_type = $answer['complain_type'];
    //   $surgeon_id = $answer['surgeon_id'];
    //   $image_view = $answer['complainLocationData']['image_view'];
    //   $image = $answer['complainLocationData']['image'];
    //   $coordinate_x = $answer['complainLocationData']['coordinate_x'];
    //   $coordinate_y = $answer['complainLocationData']['coordinate_y'];
    //   $narrativeData  = PatientNarratives::find($narrative_id);
      $optionData = $answer['optionData'];
      $complain_type = $answer['complain_type'];
      $surgeon_id = $answer['surgeon_id'];
      $image_view = $answer['complainLocationData']['image_view'];
      $image = $answer['complainLocationData']['image'];
      $coordinate_x = isset($answer['complainLocationData']['coordinate_x']) ? $answer['complainLocationData']['coordinate_x'] : null;
      $coordinate_y = isset($answer['complainLocationData']['coordinate_y']) ? $answer['complainLocationData']['coordinate_y'] : null;$narrativeData  = PatientNarratives::find($narrative_id);
      $patientId  = PatientNarratives::select('patient_id')->where('id',$narrative_id)->first();
     
      
      DB::table('patient_details')->where('id', $patientId->patient_id)->update(['all_complaints' => json_encode($allComplaints),'new_data' =>json_encode($newData) ]);
      
      
      
     if (!empty($optionData)) 
      {
        $narrative_text = array();
        // $optionData = PatientCheifComplainAnswers::find($narrative_id);
        // $optionData->delete();
        foreach ($optionData as $key => $row) 
        {
          $narrative_text[] = isset($row['narrative_text']) ? $row['narrative_text'] : null ;
          $required_input_text = "";
          $required_input = 0;
          $required_input = isset($row['required_input']) ? $row['required_input'] : null ;
          if($required_input == 1) 
          {
            $required_input_text = $row['required_input_text'];
          }
          DB::table('patient_cheif_complain_answers')->insert([
           'narrative_id'       =>  $narrative_id,
           'patient_cheif_complain_type_id'=>$complain_type,
           'question_id'  => isset($row['question_id']) ? $row['question_id'] : null ,
           'option_id'  => isset($row['option_id']) ? $row['option_id'] : null ,
           'sort_order'  => isset($row['sort_order']) ? $row['sort_order'] : null,
           'required_input_text'  =>  $required_input_text,
         ]);

        }

        $narrativeSummary = implode(' ', $narrative_text);
        if(!empty($narrativeData))
        { 
          $patientId =  $narrativeData->patient_id;
          $narrativeData->complain_type_id  = $answer['complain_type'];
          $narrativeData->image_view        = $answer['complainLocationData']['image_view'];
          $narrativeData->coordinate_x      = $answer['complainLocationData']['coordinate_x'];
          $narrativeData->coordinate_y      = $answer['complainLocationData']['coordinate_y'];
          $narrativeData->narrative_summary = $narrativeSummary;
          $narrativeData->save();

          $patientsData = PatientDetails::find($patientId);
          $patientsData->narrative_summary = $_narrativeSummary;
          if($patient_additional_info)
          {
            $patientsData->patient_additional_info = $patient_additional_info;
          }
          $patientsData->save();
        }
      }
    }
  }

  public function pendingPatientNarratives(Request $request)
  { 
    $id = $request['surgeon_id'];
    $offset = @$request['offset'];
    $limit = @$request['limit'];
    if(empty($offset)) 
    { 
      $offset = 0;
    } 
    $offset = $offset*$limit;
    $status = config('constants.CONSTANT_STATUS_INACTIVE');
    if(isset($request['active']))
    {
      $status = config('constants.CONSTANT_STATUS_ACTIVE');
    }
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Surgeon Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $pendingPatientNarratives   = PatientDetails::where('surgeon_id',$id)->where('status',$status);
    $totalRecords               = $pendingPatientNarratives->count();
    $totalPages                 = (int)ceil($totalRecords/$limit);
    if($status == config('constants.CONSTANT_STATUS_ACTIVE'))
    {
      $pendingPatientNarratives   = $pendingPatientNarratives->orderby('id','DESC');
    }
    $pendingPatientNarratives   = $pendingPatientNarratives->offset($offset)->limit($limit)->get();
    $PatientNarratives = array();
    $complainLocationData = array();
    foreach ($pendingPatientNarratives as $row) 
    { 
      $pateint_narratives  = PatientNarratives::where('patient_id',$row->id)->get();
      $multiSelectPicCoordinates  = MultiSelectPicCoordinates::where('patient_id',$row->id)->get();
      $complainTypes = array();
      foreach ($pateint_narratives as $k => $r)
      { 
        $imageType = null;
        if($r->primary_complain)
        {
          $_complainTypes = CheifComplainTypes::find($r->complain_type_id); 
        }
        $complainTypes = $_complainTypes->name;
        if ($r->image_view == config('constants.CHIEF_COMPLAINT_TYPE_IMAGE_FRONT')) 
        {
          $imageType = $_complainTypes->image_front;
        }
        else
        {
          $imageType = $_complainTypes->image_back;
        }
      }
      $row->complain_types = $complainTypes;
      $row->pateint_narratives  = $pateint_narratives;
      $row->complainLocationData  = $row->image_view;
      $complainLocationData['image'] =  $imageType;
      $complainLocationData['image_view'] =  $r->image_view;
      $complainLocationData['selectedLocation'] =  $multiSelectPicCoordinates;
      $row->complainLocationData  = $complainLocationData;
      $resultData[] = $row;
    }
    if (!empty($row)) 
    { 
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = array('data'=>$resultData,'total_pages'=>$totalPages);
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientNarrativesByPatientID(Request $request)
  { 
    $id = $request['patient_id'];
    

    $offset = @$request['offset'];
    $limit = @$request['limit'];
    if(empty($offset)) 
    { 
      $offset = 0;
    } 
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $pendingPatientNarratives  = PatientDetails::where('id',$id)->where('status',config('constants.CONSTANT_STATUS_INACTIVE'))->offset($offset)->limit(config('constants.CONSTANT_API_PAGINATION'))->get();
    $PatientNarratives = array();
    foreach ($pendingPatientNarratives as $row) 
    { 
      $row->pateint_narratives  = PatientNarratives::where('patient_id',$row->id)->get();
      $resultData[] = $row;
    }
    if (!empty($resultData)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $resultData;
        // $data['body']['details']   = $PatientNarratives;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  
  public function patientNarrativesDetails(Request $request)
  { 
    $id = $request['narrative_id'];
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Narrative Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $patientNarratives  = PatientNarratives::find($id);
    if (!empty($patientNarratives)) 
    { 
      $narrativeAnswers   = PatientCheifComplainAnswers::where('narrative_id',$id)->get();
      $complain_type_id = $patientNarratives['complain_type_id'];
      $questionData  = Questions::where('complain_type_id',$complain_type_id)->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderby('parent_question_id')->orderby('question_option_id')->get();
      if($narrativeAnswers)
      {
        foreach($narrativeAnswers as $key => $row)
        {
          $question         = Questions::find($row->question_id); 
          $questionOptions    = QuestionOptions::find($row->option_id);
          $row->question      = $question->name; 
          $row->option      = $questionOptions->title; 
          $row->input_label_rules      = $questionOptions->input_label_rules; 
        }

        if (!empty($questionData)) 
        {
          foreach ($questionData as $key => $row)
          {
            $row->options = QuestionOptions::where('question_id',$row->id)->get();
          }
        }
      }

      $patientNarratives->questions = $questionData;
      $patientNarratives->answers = $narrativeAnswers;
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $patientNarratives;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientComplains(Request $request)
  { 
    $id = $request['patient_id'];

    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $patientNarratives = PatientNarratives::where('patient_id',$id)->get();
    foreach ($patientNarratives as $row) 
    { 
      $cheifComplain  = CheifComplainTypes::find($row->complain_type_id);
      $resultData[] = $cheifComplain;
    }
    if (!empty($resultData)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $resultData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientComplainsDetails(Request $request)
  { 
    $patientId = $request['patient_id'];
    $complainId = $request['complain_id'];

    if(!$patientId)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient ID Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    if(!$complainId)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Complain ID Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }

    $resultData = PatientNarratives::where('patient_id',$patientId)->where('complain_type_id',$complainId)->first();
    $newData = PatientDetails::select('new_data')->where('id',$patientId)->first();
    $resultData['newData'] = json_decode($newData->new_data);
    // foreach ($patientNarratives as $row) 
    // { 
    //   $cheifComplain  = CheifComplainTypes::find($row->complain_type_id);
    //   $resultData[] = $cheifComplain;
    // }
    if (!empty($resultData)) 
    {
      $data["header"]["error"]              = '0';
      $data["header"]["message"]            = "Success";
      $data['body']['details']              = $resultData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  

  public function acceptNarrative(Request $request)
  { 
    $token     = $request['token'];
    $this->CheckAccessToken($token);

    $narrativeId  = $request['narrative_id'];
    $surgeonId    = $request['surgeon_id'];
    if(!$surgeonId && $narrativeId)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Narrative or Surgeon Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $patientNarratives  = PatientNarratives::find($narrativeId);
    if($patientNarratives)
    {
      if($surgeonId==$patientNarratives->via_surgeon_id)
      {
        $patientNarratives->status = config('constants.CONSTANT_STATUS_ACTIVE');

        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = "Narrative accept Successfully";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }

      else
      {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Invalid Surgeon ID";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Invalid Narrative ID";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }

  }





  public function saveNarrativesByPatientID(Request $request)
  { 
    
    $input     = json_decode($request['data'],true);
    $response   = array();
    $errors   = array();
    if(!empty($input))
    { 
      
      // dd($input['answers']);
      $isUpdate = 1;
      $email='';
      $isExport=0;
      $PatientId  = $input['patient_id'];

        //dd($PatientId);
      $narrativeSummary = $input['narrative_summary'];
      $answers          = $input['answers'];
      $newData          = $input['newData'];
      $newData          = json_encode($newData);
      $allComplaints    = $input['all_complaints'];
      $allComplaints     = json_encode($allComplaints);
      if(!$answers)
      {
        $errors[] = "Answers Is Required";
      }
      if(!$narrativeSummary)
      {
        $errors[] = "Narrative Summary Is Required";
      }
       if(!$newData)
      {
        $errors[] = "new Data Is Required";
      }
       if(!$allComplaints)
      {
        $errors[] = "All complains Is Required";
      }
      if(empty($errors))
      {
        if($answers)
        {

          $this->addPatientNarrative($answers,$PatientId,$addAnother=1);
          PatientDetails::updateOrCreate(['id' => $PatientId],
            array(
              'narrative_summary' =>$narrativeSummary,
              'status' =>config('constants.CONSTANT_STATUS_ACTIVE'),
              'all_complaints' => $allComplaints,
              'new_data' => $newData
            )
          );
          $PatientDetails = PatientDetails::find($PatientId);
          $PatientDetails->all_complaints = $allComplaints;
          $PatientDetails->new_data = $newData;
          $PatientDetails->save();
        }
        $response[]  = "Patient Narrative Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $response;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = $errors;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }



  public function mailSent($mail, $data)
  { 
   Mail::to($mail)->send(new SendMailable($data));
   return 'Email was Successfully sent';
 }

 public function CheckAccessToken($token)
 {
    // if (!empty($token)) 
    // {
    //   $AccessToken  = AccessToken::where('token',$token)->first();
    //   if (empty($AccessToken)) 
    //   {
    //       $data["header"]["error"]    = '1';
    //       $data["header"]["message"]  = 'Token does not match';
    //      echo CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    //   die;
    //   }
    // }
 }


  public function updatePatientNarratives(Request $request)
  { 
    $input     = json_decode($request['data'],true);
      
    $response   = array();
    $errors   = array();
   
    if(!empty($input))
    { 

      $narrative_id = $input['narrative_id'];
      $narrativeSummary = $input['narrative_summary'];
      $allComplaints = $input['all_complaints'];
      $newData        = $input['newData'];
      $answers        = $input['answers'];
      
      if(!$answers)
      {
        $errors[] = "Answers Is Required";
      }
      if(!$narrativeSummary)
      {
        $errors[] = "Narrative Summary Is Required";
      }

      if(empty($errors))
      {

        /** TO DO's after auth get user_id which is equla to via_surgeon_id and departmentID **/

          //$savePatientNarratives->department_id     = Auth::user()->department_id;
          //$savePatientNarratives->via_surgeon_id    = Auth::user()->id;
        if($answers)
        {
        
          $this->updatePatientNarrative($answers,$narrative_id,$narrativeSummary,$input['patient_additional_info'],$allComplaints,$newData);

        }
          // if ($input['isExport'] == true) 
          // {
          //   $this->mailSent($email,$narrativeSummary);
          // }

        $response[]  = "Patient Narrative Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $response;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = $errors;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }


  public function saveSurgeonQuestion(Request $request)
  { 
    $input     = json_decode($request['data'],true);
    $response   = array();
    $errors   = array();
    $token     = $request['token'];
    $this->CheckAccessToken($token);
    if(!empty($input))
    { 
      $surgeon_id  = $input['surgeon_id'];
      $complain_type_id        = $input['complain_type_id'];
      $question_title        = $input['question_title'];
      $responseText = $input['response'];

      if(!$surgeon_id)
      {
        $errors[] = "Surgeon Is Required";
      }
      if(!$complain_type_id)
      {
        $errors[] = "Complain Type ID Is Required";
      }
      if(!$question_title)
      {
        $errors[] = "Question Title Is Required";
      }
      if(!$responseText)
      {
        $errors[] = "Response Is Required";
      }

      if(empty($errors))
      { 
        DB::table('surgeon_question')->insertGetId([
         'surgeon_id'=>  $surgeon_id,
         'complain_type_id'       =>  $complain_type_id,
         'question_title'       =>  $question_title,
         'response'       =>  $responseText,
       ]);
        $response[]  = "Surgeon Question Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $response;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = $errors;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  public function getComplaintypes()
  { 
   $userData = CheifComplainTypes::where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderBy('sort_order')->get();
   if (!empty($userData)) 
   {
    $data["header"]["error"]    = '0';
    $data["header"]["message"]  = "Success";
    $data['body']['details']    = $userData;
    return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
  }
  else
  {
    $data["header"]["error"]    = '1';
    $data["header"]["message"]  = "Cheif Complain Types table is empty";
    return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
  } 
  }

  public function getQuestionByComplainTypes(Request $request)
  { 
    $id = $request['complain_type_id'];
    $token     = $request['token'];
    $this->CheckAccessToken($token);

    $questionData  = Questions::where('complain_type_id',$id)->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderby('parent_question_id')->orderby('question_option_id')->get();
    foreach ($questionData as $key => $row)
    {
      $row->options = QuestionOptions::where('question_id',$row->id)->get();
      $questionCategory = QuestionCategories::find($row->category_id);
      $row->category_order = $questionCategory->question_order;
      $row->branchingQuestionData = QuestionBranchingLogic::where('question_id',$row->id)->get();


    }

    if ($questionData->count() > 0) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $questionData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientComplainById(Request $request)
  { 
    $id = $request['patient_id'];
      //$token     = $request['token'];
      //$this->CheckAccessToken($token);

    $patientDetail  = PatientDetails::find($id);

    if ($patientDetail->count() > 0) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $patientDetail;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  public function getPatientOptionsByPatientId(Request $request)
  { 
    $id = $request['patient_id'];
      //$token     = $request['token'];
      //$this->CheckAccessToken($token);

    $patientNarratives  = PatientNarratives::where('patient_id',$id)->get();
    $optionData =   array();

    if($patientNarratives->count() > 0) 
    { 
      foreach ($patientNarratives as $key => $row)
      {
        $_optionData = PatientCheifComplainAnswers::where('narrative_id',$row->id)->get();
        if(!empty($_optionData))
        {
          foreach ($_optionData as $k => $r)
          { 

            $narrativeText = QuestionOptions::find($r->option_id);
              //dd($narrativeText);
            $r->narrative_text = $narrativeText->narrative_text;
            $optionData[$r->patient_cheif_complain_type_id][] = $r;
          }
        }
      }

      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $optionData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function savePatientNarratives(Request $request)
  { 
    $input     = json_decode($request['data'],true);
    $newData     = $input['newData'];
    $allComplains = array();
    $response   = array();
    $errors   = array();
    $token     = $request['token'];
    $this->CheckAccessToken($token);
    if(!empty($input))
    { 
      $title          = $input['title'];
      $firstName      = $input['first_name'];
      $lastName       = $input['last_name'];
      $email          = $input['email'];
      $phone          = $input['phone'];
      $gender         = $input['gender'];
      $dob            = $input['dob'];
      $allComplains   = $input['allComplains'] ;
      $allComplains = json_encode($allComplains);
      $newData = json_encode($newData);
      $patient_additional_info  = $input['patient_additional_info'];
      $surgeon_id     = $input['surgeon_id'];
      $narrativeSummary = $input['narrative_summary'];
      $isExport     = $input['isExport'];
      $answers        = $input['answers'];

      if(!$firstName)
      {
        $errors[] = "First Name Is Required";
      }
      if(!$lastName)
      {
        $errors[] = "Last Name Is Required";
      }
      if(!$dob)
      {
        $errors[] = "Date of Birth Is Required";
      }
      if(!$gender)
      {
        $errors[] = "Gender Is Required";
      }
      if(!$email)
      {
        $errors[] = "Email Is Required";
      }

      if(!$answers)
      {
        $errors[] = "Answers Is Required";
      }
      if(!$narrativeSummary)
      {
        $errors[] = "Narrative Summary Is Required";
      }

      if(empty($errors))
      {

        /* TO DO's after auth get user_id which is equla to via_surgeon_id and departmentID */

          //$savePatientNarratives->department_id     = Auth::user()->department_id;
          //$savePatientNarratives->via_surgeon_id    = Auth::user()->id;
        if($answers)
        {

         $PatientId = DB::table('patient_details')->insertGetId([
           'title'       =>  $title,
           'first_name'  =>  $firstName,
           'last_name'  =>  $lastName,
           'email'      =>  $email,
           'phone'     =>  $phone,
           'gender'    =>  $gender,
           'narrative_summary'       =>  $narrativeSummary,
           'date_of_birth'=>  $dob,
           'surgeon_id'=>  $surgeon_id,
           'patient_additional_info'       =>  $patient_additional_info,
           'surgeon_id'     =>  $surgeon_id,
           'status'     =>  config('constants.CONSTANT_STATUS_INACTIVE'),
           'all_complaints'     =>  $allComplains,
           'new_data'     =>  $newData,
         ]);


         $this->addPatientNarrative($answers,$PatientId);
         if ($isExport == true) 
         {
          $this->mailSent($email,$narrativeSummary);
        }

      }


      $response[]  = "Patient Narrative Has Been Saved Successfully";   
    }
  }
  if (!empty($response)) 
  {
    $data["header"]["error"]    = '0';
    $data["header"]["message"]  = "Success";
    $data['body']['details']    = $response;
    return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
  }
  else
  {
    $data["header"]["error"]    = '1';
    $data["header"]["message"]  = $errors;
    return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
  } 
  }

  public function addPatientNarrative($answers,$PatientId,$addAnother=0)
  {
    foreach ($answers as $k2 => $answer) 
    {
     
      $optionData       = $answer['optionData'];
      $complain_type    = $answer['complain_type'];
      $surgeon_id       = $answer['surgeon_id'];
      $primary_complain = $answer['primary_complain'];
      $selectedLocation = $answer['complainLocationData']['selectedLocation'];
      $image_view       = $answer['complainLocationData']['image_view'];
      $image            = $answer['complainLocationData']['image'];
      $coordinate_x     = $answer['complainLocationData']['coordinate_x'];
      $coordinate_y     = $answer['complainLocationData']['coordinate_y'];
        // $narrative_text   = $answer['optionData'][$k2]['narrative_text'];
        //$primary_complain = 0;
      $narrativeSummary = '';
      if ($k2 == 0) 
      {
        $primary_complain = 1;
      }
      if($addAnother)
      {
        $primary_complain = 0;
      }
      $narrativePatientId = DB::table('patient_narratives')->insertGetId([

       'patient_id'         =>  $PatientId,
       'complain_type_id'   =>  $complain_type,
       'surgeon_id'         =>  $surgeon_id,
       'status'             =>  config('constants.CONSTANT_STATUS_INACTIVE'),
       'primary_complain'   =>  $primary_complain,
       'narrative_summary'  =>  $narrativeSummary,
       'image_view'         =>  $image_view,
       'coordinate_x'       =>  $coordinate_x,
       'coordinate_y'       =>  $coordinate_y,
     ]);
      // dd($selectedLocation);
      if (is_array($selectedLocation)) 
      {
        foreach ($selectedLocation as $key => $value) 
        {
           // Add Multiselect Pic Coordinates
          DB::table('multiselect_pic_coordinates')->insert([

           'patient_id'         =>  $PatientId,
           'complain_type_id'   =>  $complain_type,
           'coordinate_x'       =>  $value['picCoordinates']['x'],
           'coordinate_y'       =>  $value['picCoordinates']['y'],
           'width'              =>  $value['picCoordinates']['width'],
           'height'             =>  $value['picCoordinates']['height'],
           'top'                =>  $value['picCoordinates']['top'],
           'right'              =>  $value['picCoordinates']['right'],   
           'bottom'             =>  $value['picCoordinates']['bottom'],   
           'left'               =>  $value['picCoordinates']['left'],   
           'created_at'         =>  date("Y-m-d H:i:s"),
           'updated_at'         =>  date("Y-m-d H:i:s"),
         ]);
        }
      }
     

      if (!empty($optionData)) 
      {
        $narrative_text = array();
        foreach ($optionData as $key => $row) 
        {
          $required_input_text  = "";
          $isMultiDimentional = array_filter($row,'is_array');
          if(count($isMultiDimentional) > config('constants.CONSTANT_STATUS_INACTIVE'))
          // if   (is_array($row[0]) ) 
          {
            foreach ($row as $key => $value) 
            {
              $required_input       = isset($value['required_input']) ? $value['required_input'] : null;
              $question_id       = isset($value['question_id']) ? $value['question_id'] : null;
              $option_id       = isset($value['option_id']) ? $value['option_id'] : null;
              $sort_order       = isset($value['sort_order']) ? $value['sort_order'] : null;
              if($required_input == 1) 
              {
                $required_input_text = isset($value['required_input_text']) ? $value['required_input_text'] : null;
              }
              $multiSelect = isset($value['multiSelect']) ? $value['multiSelect'] : 0;
              DB::table('patient_cheif_complain_answers')->insert([
               'narrative_id'                     =>  $narrativePatientId,
               'patient_cheif_complain_type_id'   =>  $complain_type,
               'question_id'                      =>  $question_id,
               'option_id'                        =>  $option_id,
               'sort_order'                       =>  $sort_order,
               'required_input_text'              =>  $required_input_text,
               'is_multiselect'                   =>  $multiSelect,
               'created_at'                       =>  date("Y-m-d H:i:s"),
               'updated_at'                       =>  date("Y-m-d H:i:s"),

             ]);
            }
          }
          else
          {
            $required_input       = isset($row['required_input']) ? $row['required_input'] : null;
            $question_id       = isset($row['question_id']) ? $row['question_id'] : null;
            $option_id       = isset($row['option_id']) ? $row['option_id'] : null;
            $sort_order       = isset($row['sort_order']) ? $row['sort_order'] : null;
            if($required_input == 1) 
            {
              $required_input_text = isset($row['required_input_text']) ? $row['required_input_text'] : null;
              // $required_input_text = $row['required_input_text'];
            }
            $multiSelect = isset($row['multiSelect']) ? $row['multiSelect'] : 0;

            DB::table('patient_cheif_complain_answers')->insert([
             'narrative_id'                     =>  $narrativePatientId,
             'patient_cheif_complain_type_id'   =>  $complain_type,
             'question_id'                      =>  $question_id,
             'option_id'                        =>  $option_id,
             'sort_order'                       =>  $sort_order,
             'required_input_text'              =>  $required_input_text,
             'is_multiselect'                   =>  $multiSelect,
           ]);
          }
            
        }

        $narrativeSummary = implode(' ', $narrative_text);

        $updatePatientNarrativeData['narrative_summary']  = $narrativeSummary;
        PatientNarratives::updateOrCreate(['id' => $narrativePatientId]
          ,$updatePatientNarrativeData);
      }
    }
  }


  public function searchQuestion(Request $request)
  {

    $complainType = @$request['complain_id'];
    $patient_id   = @$request['patient_id'];
    $keyword      = @$request['keyword'];
    $patientNarratives = PatientNarratives::where('patient_id',$patient_id)->get()->toArray();
    $narrativeIds = array();
    foreach ($patientNarratives as $key => $row)
    {
      $narrativeIds[] = $row['id'];
    }
    $patientComplainAnswers = PatientCheifComplainAnswers::whereIn('narrative_id', $narrativeIds)->where('patient_cheif_complain_type_id',$complainType)->get()->toArray();
    $questionIds = array();
    foreach ($patientComplainAnswers as $key => $row)
    {
      $questionIds[] = $row['question_id'];
    }
    

    $patientQuestionIds = array();
    if($complainType)
    {
      $questionData = Questions::whereNotIn('id',$questionIds)->where('complain_type_id',$complainType)->where('name','like',"%$keyword%")->get();
      if($questionData->count() > 0)
      {
        foreach ($questionData as $key => $row)
        {
          $row->options = QuestionOptions::where('question_id',$row->id)->get();
        }
        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = $questionData;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      else
      {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Data Not Found";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }

    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Invalid Complain ID";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
  }
  public function approvedPatientNarratived(Request $request)
  {

    $token     = $request['token'];
    $this->CheckAccessToken($token);
    $patientId = @$request['patient_id'];
    if($patientId)
    {
      $patienDetails = PatientDetails::find($patientId);
      $patienDetails->status = config('constants.CONSTANT_STATUS_ACTIVE');
      $patienDetails->save();
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Patient has been approved";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);

    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Invalid Patient ID";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
  }
}
